[ { "post_href": "https://leetcode.com/problems/two-sum/discuss/2361743/Python-Simple-Solution-oror-O(n)-Time-oror-O(n)-Space", "python_solutions": "class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n \n d = {}\n for i, j in enumerate(nums):\n r = target - j\n if r in d: return [d[r], i]\n d[j] = i\n\t\t\n\t\t# An Upvote will be encouraging", "slug": "two-sum", "post_title": "Python Simple Solution || O(n) Time || O(n) Space", "user": "rajkumarerrakutti", "upvotes": 288, "views": 21600, "problem_title": "two sum", "number": 1, "acceptance": 0.491, "difficulty": "Easy", "__index_level_0__": 0, "question": "Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\nYou can return the answer in any order.\n Example 1:\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\nExample 2:\nInput: nums = [3,2,4], target = 6\nOutput: [1,2]\nExample 3:\nInput: nums = [3,3], target = 6\nOutput: [0,1]\n Constraints:\n2 <= nums.length <= 104\n-109 <= nums[i] <= 109\n-109 <= target <= 109\nOnly one valid answer exists.\n Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?" }, { "post_href": "https://leetcode.com/problems/add-two-numbers/discuss/1835217/Python3-DUMMY-CARRY-(-**-)-Explained", "python_solutions": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n res = dummy = ListNode()\n carry = 0\n while l1 or l2:\n v1, v2 = 0, 0\n if l1: v1, l1 = l1.val, l1.next\n if l2: v2, l2 = l2.val, l2.next\n \n val = carry + v1 + v2\n res.next = ListNode(val%10)\n res, carry = res.next, val//10\n \n if carry:\n res.next = ListNode(carry)\n \n return dummy.next", "slug": "add-two-numbers", "post_title": "\u2714\ufe0f [Python3] DUMMY CARRY ( \u2022\u2304\u2022 \u0942 )\u2727, Explained", "user": "artod", "upvotes": 44, "views": 7100, "problem_title": "add two numbers", "number": 2, "acceptance": 0.3979999999999999, "difficulty": "Medium", "__index_level_0__": 46, "question": "You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n Example 1:\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [7,0,8]\nExplanation: 342 + 465 = 807.\nExample 2:\nInput: l1 = [0], l2 = [0]\nOutput: [0]\nExample 3:\nInput: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\nOutput: [8,9,9,9,0,0,0,1]\n Constraints:\nThe number of nodes in each linked list is in the range [1, 100].\n0 <= Node.val <= 9\nIt is guaranteed that the list represents a number that does not have leading zeros." }, { "post_href": "https://leetcode.com/problems/longest-substring-without-repeating-characters/discuss/742926/Simple-Explanation-or-Concise-or-Thinking-Process-and-Example", "python_solutions": "class Solution(object):\n def lengthOfLongestSubstring(self, s):\n \"\"\"\n :type s: str\n :rtype: int abcabcbb\n \"\"\"\n if len(s) == 0:\n return 0\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n if s[right] in seen:\n left = max(left,seen[s[right]]+1)\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n print(left, right, longest)\n return longest", "slug": "longest-substring-without-repeating-characters", "post_title": "Simple Explanation | Concise | Thinking Process & Example", "user": "ivankatrump", "upvotes": 290, "views": 13100, "problem_title": "longest substring without repeating characters", "number": 3, "acceptance": 0.3379999999999999, "difficulty": "Medium", "__index_level_0__": 77, "question": "Given a string s, find the length of the longest\nsubstring\nwithout repeating characters.\n Example 1:\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\nExample 2:\nInput: s = \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\nExample 3:\nInput: s = \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n Constraints:\n0 <= s.length <= 5 * 104\ns consists of English letters, digits, symbols and spaces." }, { "post_href": "https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/949705/Python3-two-pointer-greater9621-runtime-commented", "python_solutions": "class Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n\t # Get the lengths of both lists\n l1,l2 = len(nums1), len(nums2)\n\t\t# Determine the middle\n middle = (l1 + l2) / 2\n\t\t\n\t\t# EDGE CASE:\n\t\t# If we only have 1 value (e.g. [1], []), return nums1[0] if the length of\n\t\t# that list is greater than the length of l2, otherwise return nums2[1]\n\t\tif middle == 0.5: return float(nums1[0]) if l1 > l2 else float(nums2[0])\n\n\t\t# Initialize 2 pointers\n x = y = 0\n\t\t# Initialize 2 values to store the previous and current value (in case of an even\n\t\t# amount of values, we need to average 2 values)\n cur = prev = 0\n\t\t# Determine the amount of loops we need. If the middle is even, loop that amount + 1:\n\t\t# eg: [1, 2, 3, 4, 5, 6] 6 values, middle = 3, loops = 3+1\n\t\t# ^ ^ \n\t\t# | +-- cur\n\t\t# +----- prev\n \t\t# If the middle is odd, loop that amount + 0.5\n\t\t# eg: [1, 2, 3, 4, 5] 5 values, middle = 2.5, loops = 2.5+0.5\n\t\t# ^\n # +--- cur\n loops = middle+1 if middle % 1 == 0 else middle+0.5\n\n\t\t# Walk forward the amount of loops\n for _ in range(int(loops)):\n # Store the value of cur in prev\n\t\t\tprev = cur\n\t\t\t# If the x pointer is equal to the amount of elements of nums1 (l1 == len(nums1))\n if x == l1:\n\t\t\t # Store nums2[y] in cur, 'cause we hit the end of nums1\n cur = nums2[y]\n\t\t\t\t# Move the y pointer one ahead\n y += 1\n\t\t # If the y pointer is equal to the amount of elements of nums2 (l2 == len(nums2))\n elif y == l2:\n\t\t\t # Store nums1[x] in cur, 'cause we hit the end of nums2\n cur = nums1[x]\n\t\t\t\t# Move the x pointer one ahead\n x += 1\n\t\t # If the value in nums1 is bigger than the value in nums2\n elif nums1[x] > nums2[y]:\n\t\t\t # Store nums2[y] in cur, because it's the lowest value\n cur = nums2[y]\n\t\t\t\t# Move the y pointer one ahead\n y += 1\n\t\t\t# If the value in nums2 is bigger than the value in nums1\n else:\n\t\t\t\t# Store nums1[x] in, because it's the lowest value\n cur = nums1[x]\n\t\t\t\t# Move the x pointer one ahead\n x += 1\n \n\t\t# If middle is even\n if middle % 1 == 0.0:\n\t\t\t# Return the average of the cur + prev values (which will return a float)\n return (cur+prev)/2\n\t\t# If middle is odd\n else:\n\t\t\t# Return the cur value, as a float\n return float(cur)", "slug": "median-of-two-sorted-arrays", "post_title": "Python3 two pointer >96,21% runtime [commented]", "user": "tomhagen", "upvotes": 32, "views": 5100, "problem_title": "median of two sorted arrays", "number": 4, "acceptance": 0.353, "difficulty": "Hard", "__index_level_0__": 133, "question": "Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.\nThe overall run time complexity should be O(log (m+n)).\n Example 1:\nInput: nums1 = [1,3], nums2 = [2]\nOutput: 2.00000\nExplanation: merged array = [1,2,3] and median is 2.\nExample 2:\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 2.50000\nExplanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n Constraints:\nnums1.length == m\nnums2.length == n\n0 <= m <= 1000\n0 <= n <= 1000\n1 <= m + n <= 2000\n-106 <= nums1[i], nums2[i] <= 106" }, { "post_href": "https://leetcode.com/problems/longest-palindromic-substring/discuss/2156659/Python-Easy-O(1)-Space-approach", "python_solutions": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n n=len(s)\n def expand_pallindrome(i,j): \n while 0<=i<=j str:\n if numRows == 1:\n return s\n \n row_arr = [\"\"] * numRows\n row_idx = 1\n going_up = True\n\n for ch in s:\n row_arr[row_idx-1] += ch\n if row_idx == numRows:\n going_up = False\n elif row_idx == 1:\n going_up = True\n \n if going_up:\n row_idx += 1\n else:\n row_idx -= 1\n \n return \"\".join(row_arr)", "slug": "zigzag-conversion", "post_title": "Very simple and intuitive O(n) python solution with explanation", "user": "wmv3317", "upvotes": 96, "views": 3000, "problem_title": "zigzag conversion", "number": 6, "acceptance": 0.432, "difficulty": "Medium", "__index_level_0__": 230, "question": "The string \"PAYPALISHIRING\" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)\nP A H N\nA P L S I I G\nY I R\nAnd then read line by line: \"PAHNAPLSIIGYIR\"\nWrite the code that will take a string and make this conversion given a number of rows:\nstring convert(string s, int numRows);\n Example 1:\nInput: s = \"PAYPALISHIRING\", numRows = 3\nOutput: \"PAHNAPLSIIGYIR\"\nExample 2:\nInput: s = \"PAYPALISHIRING\", numRows = 4\nOutput: \"PINALSIGYAHRPI\"\nExplanation:\nP I N\nA L S I G\nY A H R\nP I\nExample 3:\nInput: s = \"A\", numRows = 1\nOutput: \"A\"\n Constraints:\n1 <= s.length <= 1000\ns consists of English letters (lower-case and upper-case), ',' and '.'.\n1 <= numRows <= 1000" }, { "post_href": "https://leetcode.com/problems/reverse-integer/discuss/1061403/Clean-pythonic-solution", "python_solutions": "class Solution:\n def reverse(self, x: int) -> int:\n retval = int(str(abs(x))[::-1])\n \n if(retval.bit_length()>31):\n return 0\n \n if x<0:\n return -1*retval\n else:\n return retval", "slug": "reverse-integer", "post_title": "Clean pythonic solution", "user": "njain07", "upvotes": 20, "views": 3300, "problem_title": "reverse integer", "number": 7, "acceptance": 0.273, "difficulty": "Medium", "__index_level_0__": 277, "question": "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.\nAssume the environment does not allow you to store 64-bit integers (signed or unsigned).\n Example 1:\nInput: x = 123\nOutput: 321\nExample 2:\nInput: x = -123\nOutput: -321\nExample 3:\nInput: x = 120\nOutput: 21\n Constraints:\n-231 <= x <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/string-to-integer-atoi/discuss/1510014/Python-Simple-Solution-without-Strip-beats-95", "python_solutions": "class Solution:\n def myAtoi(self, s: str) -> int:\n \n if not s:\n return 0\n sign = 1\n integer = 0\n i = 0\n while i < len(s) and s[i] == ' ':\n i+=1 #skipping leading white space\n if i < len(s) and (s[i] == '-' or s[i] == '+'):\n if s[i] == '-':\n sign = -1\n i+=1\n while(i < len(s) and s[i].isdigit()):\n integer = integer * 10 + int(s[i])\n i+=1\n \n integer = sign*integer\n ans = self.limit(integer)\n return ans\n \n def limit(self, num):\n if num > pow(2, 31) -1:\n return pow(2, 31) -1\n if num < -1*pow(2, 31):\n return -1*pow(2, 31)\n return num", "slug": "string-to-integer-atoi", "post_title": "Python Simple Solution without Strip beats 95%", "user": "emerald19", "upvotes": 7, "views": 790, "problem_title": "string to integer (atoi)", "number": 8, "acceptance": 0.166, "difficulty": "Medium", "__index_level_0__": 331, "question": "Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.\nThe algorithm for myAtoi(string s) is as follows:\nWhitespace: Ignore any leading whitespace (\" \").\nSignedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity is neither present.\nConversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.\nRounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1.\nReturn the integer as the final result.\n Example 1:\nInput: s = \"42\"\nOutput: 42\nExplanation:\nThe underlined characters are what is read in and the caret is the current reader position.\nStep 1: \"42\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"42\" (\"42\" is read in)\n ^\nExample 2:\nInput: s = \" -042\"\nOutput: -42\nExplanation:\nStep 1: \" -042\" (leading whitespace is read and ignored)\n ^\nStep 2: \" -042\" ('-' is read, so the result should be negative)\n ^\nStep 3: \" -042\" (\"042\" is read in, leading zeros ignored in the result)\n ^\nExample 3:\nInput: s = \"1337c0d3\"\nOutput: 1337\nExplanation:\nStep 1: \"1337c0d3\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"1337c0d3\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"1337c0d3\" (\"1337\" is read in; reading stops because the next character is a non-digit)\n ^\nExample 4:\nInput: s = \"0-1\"\nOutput: 0\nExplanation:\nStep 1: \"0-1\" (no characters read because there is no leading whitespace)\n ^\nStep 2: \"0-1\" (no characters read because there is neither a '-' nor '+')\n ^\nStep 3: \"0-1\" (\"0\" is read in; reading stops because the next character is a non-digit)\n ^\nExample 5:\nInput: s = \"words and 987\"\nOutput: 0\nExplanation:\nReading stops at the first non-digit character 'w'.\n Constraints:\n0 <= s.length <= 200\ns consists of English letters (lower-case and upper-case), digits (0-9), ' ', '+', '-', and '.'." }, { "post_href": "https://leetcode.com/problems/palindrome-number/discuss/2797115/Easy-Python-Solution-with-O(1)-space", "python_solutions": "class Solution:\n def isPalindrome(self, x: int) -> bool:\n if x < 0:\n return False\n \n res = 0\n temp = x\n \n while temp:\n temp, n = divmod(temp, 10)\n res = (res * 10) + n\n \n return res == x", "slug": "palindrome-number", "post_title": "Easy Python Solution with O(1) space", "user": "tragob", "upvotes": 11, "views": 1900, "problem_title": "palindrome number", "number": 9, "acceptance": 0.53, "difficulty": "Easy", "__index_level_0__": 382, "question": "Given an integer x, return true if x is a\npalindrome\n, and false otherwise.\n Example 1:\nInput: x = 121\nOutput: true\nExplanation: 121 reads as 121 from left to right and from right to left.\nExample 2:\nInput: x = -121\nOutput: false\nExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\nExample 3:\nInput: x = 10\nOutput: false\nExplanation: Reads 01 from right to left. Therefore it is not a palindrome.\n Constraints:\n-231 <= x <= 231 - 1\n Follow up: Could you solve it without converting the integer to a string?" }, { "post_href": "https://leetcode.com/problems/regular-expression-matching/discuss/2383634/Fastest-Solution-Explained0ms100-O(n)time-complexity-O(n)space-complexity", "python_solutions": "class Solution:\n def isMatch(self, s, p):\n n = len(s)\n m = len(p)\n dp = [[False for _ in range (m+1)] for _ in range (n+1)]\n dp[0][0] = True\n for c in range(1,m+1):\n if p[c-1] == '*' and c > 1:\n dp[0][c] = dp[0][c-2]\n for r in range(1,n+1):\n for c in range(1,m+1):\n if p[c-1] == s[r-1] or p[c-1] == '.':\n dp[r][c] = dp[r-1][c-1]\n elif c > 1 and p[c-1] == '*':\n if p[c-2] =='.' or s[r-1]==p[c-2]:\n dp[r][c] =dp[r][c-2] or dp[r-1][c]\n else:\n dp[r][c] = dp[r][c-2]\n return dp[n][m]", "slug": "regular-expression-matching", "post_title": "[Fastest Solution Explained][0ms][100%] O(n)time complexity O(n)space complexity", "user": "cucerdariancatalin", "upvotes": 10, "views": 1300, "problem_title": "regular expression matching", "number": 10, "acceptance": 0.282, "difficulty": "Hard", "__index_level_0__": 425, "question": "Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:\n'.' Matches any single character.\n'*' Matches zero or more of the preceding element.\nThe matching should cover the entire input string (not partial).\n Example 1:\nInput: s = \"aa\", p = \"a\"\nOutput: false\nExplanation: \"a\" does not match the entire string \"aa\".\nExample 2:\nInput: s = \"aa\", p = \"a*\"\nOutput: true\nExplanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\nExample 3:\nInput: s = \"ab\", p = \".*\"\nOutput: true\nExplanation: \".*\" means \"zero or more (*) of any character (.)\".\n Constraints:\n1 <= s.length <= 20\n1 <= p.length <= 20\ns contains only lowercase English letters.\np contains only lowercase English letters, '.', and '*'.\nIt is guaranteed for each appearance of the character '*', there will be a previous valid character to match." }, { "post_href": "https://leetcode.com/problems/container-with-most-water/discuss/1915108/Python3-GREEDY-TWO-POINTERS-~(~)-Explained", "python_solutions": "class Solution:\n def maxArea(self, height: List[int]) -> int:\n l, r, area = 0, len(height) - 1, 0\n while l < r:\n area = max(area, (r - l) * min(height[l], height[r]))\n if height[l] < height[r]:\n\t\t\t\tl += 1\n else:\n\t\t\t\tr -= 1\n\t\t\t\t\n return area", "slug": "container-with-most-water", "post_title": "\u2714\ufe0f [Python3] GREEDY TWO POINTERS ~(\u02d8\u25be\u02d8~), Explained", "user": "artod", "upvotes": 133, "views": 9600, "problem_title": "container with most water", "number": 11, "acceptance": 0.5429999999999999, "difficulty": "Medium", "__index_level_0__": 446, "question": "You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).\nFind two lines that together with the x-axis form a container, such that the container contains the most water.\nReturn the maximum amount of water a container can store.\nNotice that you may not slant the container.\n Example 1:\nInput: height = [1,8,6,2,5,4,8,3,7]\nOutput: 49\nExplanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.\nExample 2:\nInput: height = [1,1]\nOutput: 1\n Constraints:\nn == height.length\n2 <= n <= 105\n0 <= height[i] <= 104" }, { "post_href": "https://leetcode.com/problems/integer-to-roman/discuss/2724200/Python's-Simple-and-Easy-to-Understand-Solution-or-99-Faster", "python_solutions": "class Solution:\n def intToRoman(self, num: int) -> str:\n # Creating Dictionary for Lookup\n num_map = {\n 1: \"I\",\n 5: \"V\", 4: \"IV\",\n 10: \"X\", 9: \"IX\",\n 50: \"L\", 40: \"XL\",\n 100: \"C\", 90: \"XC\",\n 500: \"D\", 400: \"CD\",\n 1000: \"M\", 900: \"CM\",\n }\n \n # Result Variable\n r = ''\n \n \n for n in [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]:\n # If n in list then add the roman value to result variable\n while n <= num:\n r += num_map[n]\n num-=n\n return r", "slug": "integer-to-roman", "post_title": "\u2714\ufe0f Python's Simple and Easy to Understand Solution | 99% Faster \ud83d\udd25", "user": "pniraj657", "upvotes": 53, "views": 2600, "problem_title": "integer to roman", "number": 12, "acceptance": 0.615, "difficulty": "Medium", "__index_level_0__": 496, "question": "Seven different symbols represent Roman numerals with the following values:\nSymbol Value\nI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000\nRoman numerals are formed by appending the conversions of decimal place values from highest to lowest. Converting a decimal place value into a Roman numeral has the following rules:\nIf the value does not start with 4 or 9, select the symbol of the maximal value that can be subtracted from the input, append that symbol to the result, subtract its value, and convert the remainder to a Roman numeral.\nIf the value starts with 4 or 9 use the subtractive form representing one symbol subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).\nOnly powers of 10 (I, X, C, M) can be appended consecutively at most 3 times to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple times. If you need to append a symbol 4 times use the subtractive form.\nGiven an integer, convert it to a Roman numeral.\n Example 1:\nInput: num = 3749\nOutput: \"MMMDCCXLIX\"\nExplanation:\n3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)\n 700 = DCC as 500 (D) + 100 (C) + 100 (C)\n 40 = XL as 10 (X) less of 50 (L)\n 9 = IX as 1 (I) less of 10 (X)\nNote: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places\nExample 2:\nInput: num = 58\nOutput: \"LVIII\"\nExplanation:\n50 = L\n 8 = VIII\nExample 3:\nInput: num = 1994\nOutput: \"MCMXCIV\"\nExplanation:\n1000 = M\n 900 = CM\n 90 = XC\n 4 = IV\n Constraints:\n1 <= num <= 3999" }, { "post_href": "https://leetcode.com/problems/roman-to-integer/discuss/264743/Clean-Python-beats-99.78.", "python_solutions": "class Solution:\n def romanToInt(self, s: str) -> int:\n translations = {\n \"I\": 1,\n \"V\": 5,\n \"X\": 10,\n \"L\": 50,\n \"C\": 100,\n \"D\": 500,\n \"M\": 1000\n }\n number = 0\n s = s.replace(\"IV\", \"IIII\").replace(\"IX\", \"VIIII\")\n s = s.replace(\"XL\", \"XXXX\").replace(\"XC\", \"LXXXX\")\n s = s.replace(\"CD\", \"CCCC\").replace(\"CM\", \"DCCCC\")\n for char in s:\n number += translations[char]\n return number", "slug": "roman-to-integer", "post_title": "Clean Python, beats 99.78%.", "user": "hgrsd", "upvotes": 1200, "views": 60900, "problem_title": "roman to integer", "number": 13, "acceptance": 0.5820000000000001, "difficulty": "Easy", "__index_level_0__": 548, "question": "Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.\nSymbol Value\nI 1\nV 5\nX 10\nL 50\nC 100\nD 500\nM 1000\nFor example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.\nRoman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:\nI can be placed before V (5) and X (10) to make 4 and 9. \nX can be placed before L (50) and C (100) to make 40 and 90. \nC can be placed before D (500) and M (1000) to make 400 and 900.\nGiven a roman numeral, convert it to an integer.\n Example 1:\nInput: s = \"III\"\nOutput: 3\nExplanation: III = 3.\nExample 2:\nInput: s = \"LVIII\"\nOutput: 58\nExplanation: L = 50, V= 5, III = 3.\nExample 3:\nInput: s = \"MCMXCIV\"\nOutput: 1994\nExplanation: M = 1000, CM = 900, XC = 90 and IV = 4.\n Constraints:\n1 <= s.length <= 15\ns contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').\nIt is guaranteed that s is a valid roman numeral in the range [1, 3999]." }, { "post_href": "https://leetcode.com/problems/longest-common-prefix/discuss/1351149/Python-and-startswith", "python_solutions": "class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n \n pre = strs[0]\n \n for i in strs:\n while not i.startswith(pre):\n pre = pre[:-1]\n \n return pre", "slug": "longest-common-prefix", "post_title": "Python & startswith", "user": "lokeshsenthilkumar", "upvotes": 72, "views": 4500, "problem_title": "longest common prefix", "number": 14, "acceptance": 0.408, "difficulty": "Easy", "__index_level_0__": 595, "question": "Write a function to find the longest common prefix string amongst an array of strings.\nIf there is no common prefix, return an empty string \"\".\n Example 1:\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\nExample 2:\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\nExplanation: There is no common prefix among the input strings.\n Constraints:\n1 <= strs.length <= 200\n0 <= strs[i].length <= 200\nstrs[i] consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/2790811/Python-solution", "python_solutions": "class Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n levels = []\n \n def order(node, level):\n if level >= len(levels):\n levels.append([])\n \n if node:\n levels[level].append(node.val)\n \n if node.left:\n order(node.left, level + 1)\n \n if node.right:\n order(node.right, level + 1)\n \n if not root:\n return []\n \n order(root, 0)\n return levels", "slug": "binary-tree-level-order-traversal", "post_title": "Python solution", "user": "maomao1010", "upvotes": 0, "views": 3, "problem_title": "binary tree level order traversal", "number": 102, "acceptance": 0.634, "difficulty": "Medium", "__index_level_0__": 613, "question": "Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[9,20],[15,7]]\nExample 2:\nInput: root = [1]\nOutput: [[1]]\nExample 3:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 2000].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/discuss/2098804/Python3-Clean-Solution-using-Queue-Level-Order-Traversal", "python_solutions": "class Solution:\n def zigzagLevelOrder(self, root):\n \n res = []\n if not root: return res\n zigzag = True\n \n q = collections.deque()\n q.append(root)\n \n while q:\n n = len(q)\n nodesOfThisLevel = []\n \n for i in range(n):\n node = q.popleft()\n nodesOfThisLevel.append(node.val)\n \n if node.left: q.append(node.left)\n if node.right: q.append(node.right)\n \n if zigzag:\n res.append(nodesOfThisLevel)\n zigzag = False\n else:\n res.append(nodesOfThisLevel[::-1])\n zigzag = True\n \n return res\n \n# Time: O(N)\n# Space: O(N)", "slug": "binary-tree-zigzag-level-order-traversal", "post_title": "[Python3] Clean Solution using Queue Level Order Traversal", "user": "samirpaul1", "upvotes": 7, "views": 240, "problem_title": "binary tree zigzag level order traversal", "number": 103, "acceptance": 0.552, "difficulty": "Medium", "__index_level_0__": 614, "question": "Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[3],[20,9],[15,7]]\nExample 2:\nInput: root = [1]\nOutput: [[1]]\nExample 3:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 2000].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/359949/Python-recursive-and-iterative-solution", "python_solutions": "class Solution:\n def maxDepth(self, root: TreeNode) -> int:\n if not root:\n return 0\n return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1", "slug": "maximum-depth-of-binary-tree", "post_title": "Python recursive and iterative solution", "user": "amchoukir", "upvotes": 219, "views": 18300, "problem_title": "maximum depth of binary tree", "number": 104, "acceptance": 0.732, "difficulty": "Easy", "__index_level_0__": 630, "question": "Given the root of a binary tree, return its maximum depth.\nA binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: 3\nExample 2:\nInput: root = [1,null,2]\nOutput: 2\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/689647/Python3-stack-O(N)", "python_solutions": "class Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n loc = {x : i for i, x in enumerate(inorder)}\n root = None\n stack = []\n for x in preorder: \n if not root: root = node = TreeNode(x)\n elif loc[x] < loc[node.val]: \n stack.append(node)\n node.left = node = TreeNode(x)\n else: \n while stack and loc[stack[-1].val] < loc[x]: node = stack.pop() # backtracking\n node.right = node = TreeNode(x)\n return root", "slug": "construct-binary-tree-from-preorder-and-inorder-traversal", "post_title": "[Python3] stack O(N)", "user": "ye15", "upvotes": 7, "views": 371, "problem_title": "construct binary tree from preorder and inorder traversal", "number": 105, "acceptance": 0.609, "difficulty": "Medium", "__index_level_0__": 671, "question": "Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.\n Example 1:\nInput: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\nOutput: [3,9,20,null,null,15,7]\nExample 2:\nInput: preorder = [-1], inorder = [-1]\nOutput: [-1]\n Constraints:\n1 <= preorder.length <= 3000\ninorder.length == preorder.length\n-3000 <= preorder[i], inorder[i] <= 3000\npreorder and inorder consist of unique values.\nEach value of inorder also appears in preorder.\npreorder is guaranteed to be the preorder traversal of the tree.\ninorder is guaranteed to be the inorder traversal of the tree." }, { "post_href": "https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/2098606/Python3-O(n)-Time-O(1)-Space-Solution-faster-than-95", "python_solutions": "class Solution:\n def buildTree(self, inorder, postorder):\n inorderIndexDict = {ch : i for i, ch in enumerate(inorder)}\n self.rootIndex = len(postorder) - 1\n \n def solve(l, r):\n if l > r: return None\n \n root = TreeNode(postorder[self.rootIndex]) \n self.rootIndex -= 1\n \n i = inorderIndexDict[root.val]\n \n # As we a approaching from end and all right side nodes of i in inorder are\n # from right sub-tree so first call solve for right then left.\n root.right = solve(i+1, r)\n root.left = solve(l, i-1)\n \n return root\n \n return solve(0, len(inorder)-1)\n \n \n# Time: O(N)\n# Space: O(1)", "slug": "construct-binary-tree-from-inorder-and-postorder-traversal", "post_title": "[Python3] O(n) Time, O(1) Space Solution faster than 95%", "user": "samirpaul1", "upvotes": 3, "views": 159, "problem_title": "construct binary tree from inorder and postorder traversal", "number": 106, "acceptance": 0.575, "difficulty": "Medium", "__index_level_0__": 707, "question": "Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.\n Example 1:\nInput: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\nOutput: [3,9,20,null,null,15,7]\nExample 2:\nInput: inorder = [-1], postorder = [-1]\nOutput: [-1]\n Constraints:\n1 <= inorder.length <= 3000\npostorder.length == inorder.length\n-3000 <= inorder[i], postorder[i] <= 3000\ninorder and postorder consist of unique values.\nEach value of postorder also appears in inorder.\ninorder is guaranteed to be the inorder traversal of the tree.\npostorder is guaranteed to be the postorder traversal of the tree." }, { "post_href": "https://leetcode.com/problems/binary-tree-level-order-traversal-ii/discuss/359962/Python-recursive-and-iterative", "python_solutions": "class Solution:\n def helper(self, result, depth, node):\n if not node:\n return\n \n if len(result) < depth:\n result.append([])\n \n result[depth-1].append(node.val)\n self.helper(result, depth+1, node.left)\n self.helper(result, depth+1, node.right)\n \n def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n \n result = []\n depth = 1\n self.helper(result, depth, root)\n result.reverse()\n return result", "slug": "binary-tree-level-order-traversal-ii", "post_title": "Python recursive and iterative", "user": "amchoukir", "upvotes": 4, "views": 519, "problem_title": "binary tree level order traversal ii", "number": 107, "acceptance": 0.604, "difficulty": "Medium", "__index_level_0__": 717, "question": "Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[15,7],[9,20],[3]]\nExample 2:\nInput: root = [1]\nOutput: [[1]]\nExample 3:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 2000].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/discuss/2428167/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-(Java-C%2B%2B-Python-JS-C-Python3)", "python_solutions": "class Solution(object):\n def sortedArrayToBST(self, nums):\n # Base condition...\n if len(nums) == 0:\n return None\n # set the middle node...\n mid = len(nums)//2\n # Initialise root node with value same as nums[mid]\n root = TreeNode(nums[mid])\n # Assign left subtrees as the same function called on left subranges...\n root.left = self.sortedArrayToBST(nums[:mid])\n # Assign right subtrees as the same function called on right subranges...\n root.right = self.sortedArrayToBST(nums[mid+1:])\n # Return the root node...\n return root", "slug": "convert-sorted-array-to-binary-search-tree", "post_title": "Easy || 0 ms || 100% || Fully Explained || (Java, C++, Python, JS, C, Python3)", "user": "PratikSen07", "upvotes": 19, "views": 900, "problem_title": "convert sorted array to binary search tree", "number": 108, "acceptance": 0.6920000000000001, "difficulty": "Easy", "__index_level_0__": 735, "question": "Given an integer array nums where the elements are sorted in ascending order, convert it to a\nheight-balanced\nbinary search tree.\n Example 1:\nInput: nums = [-10,-3,0,5,9]\nOutput: [0,-3,9,-10,null,5]\nExplanation: [0,-10,5,null,-3,null,9] is also accepted:\nExample 2:\nInput: nums = [1,3]\nOutput: [3,1]\nExplanation: [1,null,3] and [3,1] are both height-balanced BSTs.\n Constraints:\n1 <= nums.length <= 104\n-104 <= nums[i] <= 104\nnums is sorted in a strictly increasing order." }, { "post_href": "https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/discuss/2767308/Python-beats-86-(recursive-solution)", "python_solutions": "class Solution:\n l = 'left'\n r = 'right'\n \n def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:\n if not head: return None\n \n nums = []\n while head:\n nums.append(head.val)\n head = head.next\n \n mid = len(nums) // 2\n treeNode = TreeNode(nums[mid])\n \n self.binarySearchTree(nums[:mid], self.l, treeNode)\n self.binarySearchTree(nums[(mid + 1):], self.r, treeNode)\n \n return treeNode\n \n \n def binarySearchTree(self, nums, direction, treeNode):\n if len(nums) <= 0: return\n \n mid = len(nums) // 2\n left, right = nums[:mid], nums[(mid + 1):]\n \n if direction == self.l:\n treeNode.left = TreeNode(nums[mid])\n self.binarySearchTree(left, self.l, treeNode.left)\n self.binarySearchTree(right, self.r, treeNode.left)\n else:\n treeNode.right = TreeNode(nums[mid])\n self.binarySearchTree(left, self.l, treeNode.right)\n self.binarySearchTree(right, self.r, treeNode.right)", "slug": "convert-sorted-list-to-binary-search-tree", "post_title": "Python beats 86% (recursive solution)", "user": "farruhzokirov00", "upvotes": 2, "views": 150, "problem_title": "convert sorted list to binary search tree", "number": 109, "acceptance": 0.574, "difficulty": "Medium", "__index_level_0__": 759, "question": "Given the head of a singly linked list where elements are sorted in ascending order, convert it to a\nheight-balanced\nbinary search tree.\n Example 1:\nInput: head = [-10,-3,0,5,9]\nOutput: [0,-3,9,-10,null,5]\nExplanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.\nExample 2:\nInput: head = []\nOutput: []\n Constraints:\nThe number of nodes in head is in the range [0, 2 * 104].\n-105 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/balanced-binary-tree/discuss/2428871/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JavaScript-Python3)", "python_solutions": "class Solution(object):\n def isBalanced(self, root):\n return (self.Height(root) >= 0)\n def Height(self, root):\n if root is None: return 0\n leftheight, rightheight = self.Height(root.left), self.Height(root.right)\n if leftheight < 0 or rightheight < 0 or abs(leftheight - rightheight) > 1: return -1\n return max(leftheight, rightheight) + 1", "slug": "balanced-binary-tree", "post_title": "Very Easy || 100% || Fully Explained (C++, Java, Python, JavaScript, Python3)", "user": "PratikSen07", "upvotes": 83, "views": 6700, "problem_title": "balanced binary tree", "number": 110, "acceptance": 0.483, "difficulty": "Easy", "__index_level_0__": 780, "question": "Given a binary tree, determine if it is\nheight-balanced\n.\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: true\nExample 2:\nInput: root = [1,2,2,3,3,null,null,4,4]\nOutput: false\nExample 3:\nInput: root = []\nOutput: true\n Constraints:\nThe number of nodes in the tree is in the range [0, 5000].\n-104 <= Node.val <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-depth-of-binary-tree/discuss/2429057/Very-Easy-oror-100-oror-Fully-Explained-(C%2B%2B-Java-Python-JS-C-Python3)", "python_solutions": "class Solution(object):\n def minDepth(self, root):\n # Base case...\n # If the subtree is empty i.e. root is NULL, return depth as 0...\n if root is None: return 0\n # Initialize the depth of two subtrees...\n leftDepth = self.minDepth(root.left)\n rightDepth = self.minDepth(root.right)\n # If the both subtrees are empty...\n if root.left is None and root.right is None:\n return 1\n # If the left subtree is empty, return the depth of right subtree after adding 1 to it...\n if root.left is None:\n return 1 + rightDepth\n # If the right subtree is empty, return the depth of left subtree after adding 1 to it...\n if root.right is None:\n return 1 + leftDepth\n # When the two child function return its depth...\n # Pick the minimum out of these two subtrees and return this value after adding 1 to it...\n return min(leftDepth, rightDepth) + 1; # Adding 1 is the current node which is the parent of the two subtrees...", "slug": "minimum-depth-of-binary-tree", "post_title": "Very Easy || 100% || Fully Explained (C++, Java, Python, JS, C, Python3)", "user": "PratikSen07", "upvotes": 32, "views": 2200, "problem_title": "minimum depth of binary tree", "number": 111, "acceptance": 0.437, "difficulty": "Easy", "__index_level_0__": 804, "question": "Given a binary tree, find its minimum depth.\nThe minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\nNote: A leaf is a node with no children.\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: 2\nExample 2:\nInput: root = [2,null,3,null,4,null,5,null,6]\nOutput: 5\n Constraints:\nThe number of nodes in the tree is in the range [0, 105].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/path-sum/discuss/2658792/Python-Elegant-and-Short-or-DFS", "python_solutions": "class Solution:\n \"\"\"\n Time: O(n)\n Memory: O(n)\n \"\"\"\n\n def hasPathSum(self, root: Optional[TreeNode], target: int) -> bool:\n if root is None:\n return False\n if root.left is None and root.right is None:\n return target == root.val\n return self.hasPathSum( root.left, target - root.val) or \\\n self.hasPathSum(root.right, target - root.val)", "slug": "path-sum", "post_title": "Python Elegant & Short | DFS", "user": "Kyrylo-Ktl", "upvotes": 10, "views": 422, "problem_title": "path sum", "number": 112, "acceptance": 0.477, "difficulty": "Easy", "__index_level_0__": 837, "question": "Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.\nA leaf is a node with no children.\n Example 1:\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\nOutput: true\nExplanation: The root-to-leaf path with the target sum is shown.\nExample 2:\nInput: root = [1,2,3], targetSum = 5\nOutput: false\nExplanation: There two root-to-leaf paths in the tree:\n(1 --> 2): The sum is 3.\n(1 --> 3): The sum is 4.\nThere is no root-to-leaf path with sum = 5.\nExample 3:\nInput: root = [], targetSum = 0\nOutput: false\nExplanation: Since the tree is empty, there are no root-to-leaf paths.\n Constraints:\nThe number of nodes in the tree is in the range [0, 5000].\n-1000 <= Node.val <= 1000\n-1000 <= targetSum <= 1000" }, { "post_href": "https://leetcode.com/problems/path-sum-ii/discuss/484120/Python-3-(beats-~100)-(nine-lines)-(DFS)", "python_solutions": "class Solution:\n def pathSum(self, R: TreeNode, S: int) -> List[List[int]]:\n A, P = [], []\n def dfs(N):\n if N == None: return\n P.append(N.val)\n if (N.left,N.right) == (None,None) and sum(P) == S: A.append(list(P))\n else: dfs(N.left), dfs(N.right)\n P.pop()\n dfs(R)\n return A\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "path-sum-ii", "post_title": "Python 3 (beats ~100%) (nine lines) (DFS)", "user": "junaidmansuri", "upvotes": 9, "views": 2200, "problem_title": "path sum ii", "number": 113, "acceptance": 0.5670000000000001, "difficulty": "Medium", "__index_level_0__": 871, "question": "Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.\nA root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.\n Example 1:\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: [[5,4,11,2],[5,8,4,5]]\nExplanation: There are two paths whose sum equals targetSum:\n5 + 4 + 11 + 2 = 22\n5 + 8 + 4 + 5 = 22\nExample 2:\nInput: root = [1,2,3], targetSum = 5\nOutput: []\nExample 3:\nInput: root = [1,2], targetSum = 0\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 5000].\n-1000 <= Node.val <= 1000\n-1000 <= targetSum <= 1000" }, { "post_href": "https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/2340445/Python-or-intuitive-explained-or-O(1)-space-ignoring-recursion-stack-or-O(n)-time", "python_solutions": "class Solution:\n def __init__(self):\n self.prev = None\n \n def flatten(self, root: Optional[TreeNode]) -> None:\n \n if not root: return \n self.flatten(root.right)\n self.flatten(root.left)\n root.right = self.prev\n root.left = None\n self.prev = root", "slug": "flatten-binary-tree-to-linked-list", "post_title": "Python | intuitive, explained | O(1) space ignoring recursion stack | O(n) time", "user": "mync", "upvotes": 7, "views": 223, "problem_title": "flatten binary tree to linked list", "number": 114, "acceptance": 0.612, "difficulty": "Medium", "__index_level_0__": 899, "question": "Given the root of a binary tree, flatten the tree into a \"linked list\":\nThe \"linked list\" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.\nThe \"linked list\" should be in the same order as a pre-order traversal of the binary tree.\n Example 1:\nInput: root = [1,2,5,3,4,null,6]\nOutput: [1,null,2,null,3,null,4,null,5,null,6]\nExample 2:\nInput: root = []\nOutput: []\nExample 3:\nInput: root = [0]\nOutput: [0]\n Constraints:\nThe number of nodes in the tree is in the range [0, 2000].\n-100 <= Node.val <= 100\n Follow up: Can you flatten the tree in-place (with O(1) extra space)?" }, { "post_href": "https://leetcode.com/problems/distinct-subsequences/discuss/1472969/Python-Bottom-up-DP-Explained", "python_solutions": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n m = len(s)\n n = len(t)\n dp = [[0] * (n+1) for _ in range(m+1)]\n \n for i in range(m+1):\n dp[i][0] = 1\n \n \"\"\"redundant, as we have initialised dp table with full of zeros\"\"\"\n# for i in range(1, n+1): \n# dp[0][i] = 0\n \n for i in range(1, m+1):\n for j in range(1, n+1):\n dp[i][j] += dp[i-1][j] \t\t\t#if current character is skipped\n if s[i-1] == t[j-1]:\n dp[i][j] += dp[i-1][j-1]\t#if current character is used\n \n return dp[-1][-1]", "slug": "distinct-subsequences", "post_title": "Python - Bottom up DP - Explained", "user": "ajith6198", "upvotes": 6, "views": 475, "problem_title": "distinct subsequences", "number": 115, "acceptance": 0.439, "difficulty": "Hard", "__index_level_0__": 924, "question": "Given two strings s and t, return the number of distinct subsequences of s which equals t.\nThe test cases are generated so that the answer fits on a 32-bit signed integer.\n Example 1:\nInput: s = \"rabbbit\", t = \"rabbit\"\nOutput: 3\nExplanation:\nAs shown below, there are 3 ways you can generate \"rabbit\" from s.\nrabbbit\nrabbbit\nrabbbit\nExample 2:\nInput: s = \"babgbag\", t = \"bag\"\nOutput: 5\nExplanation:\nAs shown below, there are 5 ways you can generate \"bag\" from s.\nbabgbag\nbabgbag\nbabgbag\nbabgbag\nbabgbag\n Constraints:\n1 <= s.length, t.length <= 1000\ns and t consist of English letters." }, { "post_href": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/719347/Python-Solution-O(1)-and-O(n)-memory.", "python_solutions": "class Solution:\n def connect(self, root: 'Node') -> 'Node':\n # edge case check\n if not root:\n return None\n \n # initialize the queue with root node (for level order traversal)\n queue = collections.deque([root])\n \n # start the traversal\n while queue:\n size = len(queue) # get number of nodes on the current level\n for i in range(size):\n node = queue.popleft() # pop the node\n \n # An important check so that we do not wire the node to the node on the next level.\n if i < size-1:\n node.next = queue[0] # because the right node of the popped node would be the next in the queue. \n \n if node.left:\n queue.append(node.left) \n if node.right:\n queue.append(node.right) \n \n return root", "slug": "populating-next-right-pointers-in-each-node", "post_title": "Python Solution O(1) and O(n) memory.", "user": "darshan_22", "upvotes": 10, "views": 534, "problem_title": "populating next right pointers in each node", "number": 116, "acceptance": 0.596, "difficulty": "Medium", "__index_level_0__": 956, "question": "You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\nInitially, all next pointers are set to NULL.\n Example 1:\nInput: root = [1,2,3,4,5,6,7]\nOutput: [1,#,2,3,#,4,5,6,7,#]\nExplanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\nExample 2:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 212 - 1].\n-1000 <= Node.val <= 1000\n Follow-up:\nYou may only use constant extra space.\nThe recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem." }, { "post_href": "https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/2033286/Python-Easy%3A-BFS-and-O(1)-Space-with-Explanation", "python_solutions": "class Solution:\n def connect(self, root: 'Node') -> 'Node':\n if not root:\n return None\n q = deque()\n q.append(root)\n dummy=Node(-999) # to initialize with a not null prev\n while q:\n length=len(q) # find level length\n \n prev=dummy\n for _ in range(length): # iterate through all nodes in the same level\n popped=q.popleft()\n if popped.left:\n q.append(popped.left)\n prev.next=popped.left\n prev=prev.next\n if popped.right:\n q.append(popped.right)\n prev.next=popped.right\n prev=prev.next \n \n return root", "slug": "populating-next-right-pointers-in-each-node-ii", "post_title": "Python Easy: BFS and O(1) Space with Explanation", "user": "constantine786", "upvotes": 39, "views": 3000, "problem_title": "populating next right pointers in each node ii", "number": 117, "acceptance": 0.498, "difficulty": "Medium", "__index_level_0__": 996, "question": "Given a binary tree\nstruct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n}\nPopulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.\nInitially, all next pointers are set to NULL.\n Example 1:\nInput: root = [1,2,3,4,5,null,7]\nOutput: [1,#,2,3,#,4,5,7,#]\nExplanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.\nExample 2:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 6000].\n-100 <= Node.val <= 100\n Follow-up:\nYou may only use constant extra space.\nThe recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem." }, { "post_href": "https://leetcode.com/problems/pascals-triangle/discuss/1490520/Python3-easy-code-faster-than-96.67", "python_solutions": "class Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n l=[0]*numRows\n for i in range(numRows):\n l[i]=[0]*(i+1)\n l[i][0]=1\n l[i][i]=1\n for j in range(1,i):\n l[i][j]=l[i-1][j-1]+l[i-1][j]\n return l", "slug": "pascals-triangle", "post_title": "Python3 easy code- faster than 96.67%", "user": "Rosh_65", "upvotes": 44, "views": 3600, "problem_title": "pascals triangle", "number": 118, "acceptance": 0.6940000000000001, "difficulty": "Easy", "__index_level_0__": 1033, "question": "Given an integer numRows, return the first numRows of Pascal's triangle.\nIn Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n Example 1:\nInput: numRows = 5\nOutput: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\nExample 2:\nInput: numRows = 1\nOutput: [[1]]\n Constraints:\n1 <= numRows <= 30" }, { "post_href": "https://leetcode.com/problems/pascals-triangle-ii/discuss/467945/Pythonic-O(-k-)-space-sol.-based-on-math-formula-90%2B", "python_solutions": "class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n \n if rowIndex == 0:\n # Base case\n return [1]\n \n elif rowIndex == 1:\n # Base case\n return [1, 1]\n \n else:\n # General case:\n last_row = self.getRow( rowIndex-1 )\n size = len(last_row)\n return [ last_row[0] ] + [ last_row[idx] + last_row[idx+1] for idx in range( size-1) ] + [ last_row[-1] ]", "slug": "pascals-triangle-ii", "post_title": "Pythonic O( k ) space sol. based on math formula, 90%+", "user": "brianchiang_tw", "upvotes": 15, "views": 1800, "problem_title": "pascals triangle ii", "number": 119, "acceptance": 0.598, "difficulty": "Easy", "__index_level_0__": 1084, "question": "Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.\nIn Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n Example 1:\nInput: rowIndex = 3\nOutput: [1,3,3,1]\nExample 2:\nInput: rowIndex = 0\nOutput: [1]\nExample 3:\nInput: rowIndex = 1\nOutput: [1,1]\n Constraints:\n0 <= rowIndex <= 33\n Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?" }, { "post_href": "https://leetcode.com/problems/triangle/discuss/2144882/Python-In-place-DP-with-Explanation", "python_solutions": "class Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n for i in range(1, len(triangle)): # for each row in triangle (skipping the first),\n for j in range(i+1): # loop through each element in the row\n triangle[i][j] += min(triangle[i-1][j-(j==i)], # minimum sum from coordinate (x-1, y)\n triangle[i-1][j-(j>0)]) # minimum sum from coordinate (x-1, y-1)\n return min(triangle[-1]) # obtain minimum sum from last row", "slug": "triangle", "post_title": "[Python] In-place DP with Explanation", "user": "zayne-siew", "upvotes": 18, "views": 1400, "problem_title": "triangle", "number": 120, "acceptance": 0.54, "difficulty": "Medium", "__index_level_0__": 1132, "question": "Given a triangle array, return the minimum path sum from top to bottom.\nFor each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.\n Example 1:\nInput: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\nOutput: 11\nExplanation: The triangle looks like:\n 2\n 3 4\n 6 5 7\n4 1 8 3\nThe minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\nExample 2:\nInput: triangle = [[-10]]\nOutput: -10\n Constraints:\n1 <= triangle.length <= 200\ntriangle[0].length == 1\ntriangle[i].length == triangle[i - 1].length + 1\n-104 <= triangle[i][j] <= 104\n Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?" }, { "post_href": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock/discuss/1545423/Python-easy-to-understand-solution-with-explanation-%3A-Tracking-and-Dynamic-programming", "python_solutions": "class Solution(object):\n def maxProfit(self, prices):\n n = len(prices)\n dp = [0]*n # initializing the dp table\n dp[0] = [prices[0],0] # filling the the first dp table --> low_price = prices[0] max_profit=0\n min_price = max_profit = 0\n # Note that ---> indixing the dp table --> dp[i-1][0] stores minimum price and dp[i-1][1] stores maximum profit\n for i in range(1,n):\n min_price = min(dp[i-1][0], prices[i]) # min(previous_min_price, cur_min_price)\n max_profit = max(dp[i-1][1], prices[i]-dp[i-1][0]) # max(previoius_max_profit, current_profit)\n dp[i] =[min_price,max_profit]\n \n return dp[n-1][1]\n\t\t#Runtime: 1220 ms, \n\t\t#Memory Usage: 32.4 MB,", "slug": "best-time-to-buy-and-sell-stock", "post_title": "Python easy to understand solution with explanation : Tracking and Dynamic programming", "user": "Abeni", "upvotes": 58, "views": 3200, "problem_title": "best time to buy and sell stock", "number": 121, "acceptance": 0.544, "difficulty": "Easy", "__index_level_0__": 1190, "question": "You are given an array prices where prices[i] is the price of a given stock on the ith day.\nYou want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.\nReturn the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.\n Example 1:\nInput: prices = [7,1,5,3,6,4]\nOutput: 5\nExplanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\nNote that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.\nExample 2:\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transactions are done and the max profit = 0.\n Constraints:\n1 <= prices.length <= 105\n0 <= prices[i] <= 104" }, { "post_href": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/discuss/2040292/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022", "python_solutions": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \n @cache\n def trade(day_d):\n \n if day_d == 0:\n \n # Hold on day_#0 = buy stock at the price of day_#0\n # Not-hold on day_#0 = doing nothing on day_#0\n return -prices[day_d], 0\n \n prev_hold, prev_not_hold = trade(day_d-1)\n \n hold = max(prev_hold, prev_not_hold - prices[day_d] )\n not_hold = max(prev_not_hold, prev_hold + prices[day_d] )\n \n return hold, not_hold\n \n # --------------------------------------------------\n last_day= len(prices)-1\n \n # Max profit must come from not_hold state (i.e., no stock position) on last day\n return trade(last_day)[1]", "slug": "best-time-to-buy-and-sell-stock-ii", "post_title": "O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022", "user": "cucerdariancatalin", "upvotes": 12, "views": 605, "problem_title": "best time to buy and sell stock ii", "number": 122, "acceptance": 0.634, "difficulty": "Medium", "__index_level_0__": 1247, "question": "You are given an integer array prices where prices[i] is the price of a given stock on the ith day.\nOn each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.\nFind and return the maximum profit you can achieve.\n Example 1:\nInput: prices = [7,1,5,3,6,4]\nOutput: 7\nExplanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\nThen buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nTotal profit is 4 + 3 = 7.\nExample 2:\nInput: prices = [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nTotal profit is 4.\nExample 3:\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.\n Constraints:\n1 <= prices.length <= 3 * 104\n0 <= prices[i] <= 104" }, { "post_href": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/discuss/2040316/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022", "python_solutions": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n buy, sell = [inf]*2, [0]*2\n for x in prices:\n for i in range(2): \n if i: buy[i] = min(buy[i], x - sell[i-1])\n else: buy[i] = min(buy[i], x)\n sell[i] = max(sell[i], x - buy[i])\n return sell[1]", "slug": "best-time-to-buy-and-sell-stock-iii", "post_title": "O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022", "user": "cucerdariancatalin", "upvotes": 16, "views": 821, "problem_title": "best time to buy and sell stock iii", "number": 123, "acceptance": 0.449, "difficulty": "Hard", "__index_level_0__": 1306, "question": "You are given an array prices where prices[i] is the price of a given stock on the ith day.\nFind the maximum profit you can achieve. You may complete at most two transactions.\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\nInput: prices = [3,3,5,0,0,3,1,4]\nOutput: 6\nExplanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\nThen buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\nExample 2:\nInput: prices = [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\nNote 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.\nExample 3:\nInput: prices = [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n Constraints:\n1 <= prices.length <= 105\n0 <= prices[i] <= 105" }, { "post_href": "https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/2040330/O(n)timeBEATS-99.97-MEMORYSPEED-0ms-MAY-2022", "python_solutions": "class Solution:\n def __init__(self):\n self.maxSum = float('-inf')\n def maxPathSum(self, root: TreeNode) -> int:\n def traverse(root):\n if root:\n left = traverse(root.left)\n right = traverse(root.right)\n self.maxSum = max(self.maxSum,root.val, root.val + left, root.val + right, root.val + left + right)\n return max(root.val,root.val + left,root.val + right)\n else:\n return 0\n traverse(root)\n return self.maxSum", "slug": "binary-tree-maximum-path-sum", "post_title": "O(n)time/BEATS 99.97% MEMORY/SPEED 0ms MAY 2022", "user": "cucerdariancatalin", "upvotes": 17, "views": 1100, "problem_title": "binary tree maximum path sum", "number": 124, "acceptance": 0.385, "difficulty": "Hard", "__index_level_0__": 1335, "question": "A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.\nThe path sum of a path is the sum of the node's values in the path.\nGiven the root of a binary tree, return the maximum path sum of any non-empty path.\n Example 1:\nInput: root = [1,2,3]\nOutput: 6\nExplanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.\nExample 2:\nInput: root = [-10,9,20,null,null,15,7]\nOutput: 42\nExplanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.\n Constraints:\nThe number of nodes in the tree is in the range [1, 3 * 104].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/valid-palindrome/discuss/350929/Solution-in-Python-3-(beats-~100)-(two-lines)-(-O(1)-solution-as-well-)", "python_solutions": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n \ts = [i for i in s.lower() if i.isalnum()]\n \treturn s == s[::-1]", "slug": "valid-palindrome", "post_title": "Solution in Python 3 (beats ~100%) (two lines) ( O(1) solution as well )", "user": "junaidmansuri", "upvotes": 50, "views": 8600, "problem_title": "valid palindrome", "number": 125, "acceptance": 0.437, "difficulty": "Easy", "__index_level_0__": 1367, "question": "A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.\nGiven a string s, return true if it is a palindrome, or false otherwise.\n Example 1:\nInput: s = \"A man, a plan, a canal: Panama\"\nOutput: true\nExplanation: \"amanaplanacanalpanama\" is a palindrome.\nExample 2:\nInput: s = \"race a car\"\nOutput: false\nExplanation: \"raceacar\" is not a palindrome.\nExample 3:\nInput: s = \" \"\nOutput: true\nExplanation: s is an empty string \"\" after removing non-alphanumeric characters.\nSince an empty string reads the same forward and backward, it is a palindrome.\n Constraints:\n1 <= s.length <= 2 * 105\ns consists only of printable ASCII characters." }, { "post_href": "https://leetcode.com/problems/word-ladder-ii/discuss/2422401/46ms-Python-97-Faster-Working-Multiple-solutions-95-memory-efficient-solution", "python_solutions": "class Solution:\n\t\tdef findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n\t\t\td = defaultdict(list)\n\t\t\tfor word in wordList:\n\t\t\t\tfor i in range(len(word)):\n\t\t\t\t\td[word[:i]+\"*\"+word[i+1:]].append(word)\n\n\t\t\tif endWord not in wordList:\n\t\t\t\treturn []\n\n\t\t\tvisited1 = defaultdict(list)\n\t\t\tq1 = deque([beginWord])\n\t\t\tvisited1[beginWord] = []\n\n\t\t\tvisited2 = defaultdict(list)\n\t\t\tq2 = deque([endWord])\n\t\t\tvisited2[endWord] = []\n\n\t\t\tans = []\n\t\t\tdef dfs(v, visited, path, paths):\n\t\t\t\tpath.append(v)\n\t\t\t\tif not visited[v]:\n\t\t\t\t\tif visited is visited1:\n\t\t\t\t\t\tpaths.append(path[::-1])\n\t\t\t\t\telse:\n\t\t\t\t\t\tpaths.append(path[:])\n\t\t\t\tfor u in visited[v]:\n\t\t\t\t\tdfs(u, visited, path, paths)\n\t\t\t\tpath.pop()\n\n\t\t\tdef bfs(q, visited1, visited2, frombegin):\n\t\t\t\tlevel_visited = defaultdict(list)\n\t\t\t\tfor _ in range(len(q)):\n\t\t\t\t\tu = q.popleft()\n\n\t\t\t\t\tfor i in range(len(u)):\n\t\t\t\t\t\tfor v in d[u[:i]+\"*\"+u[i+1:]]:\n\t\t\t\t\t\t\tif v in visited2:\n\t\t\t\t\t\t\t\tpaths1 = []\n\t\t\t\t\t\t\t\tpaths2 = []\n\t\t\t\t\t\t\t\tdfs(u, visited1, [], paths1)\n\t\t\t\t\t\t\t\tdfs(v, visited2, [], paths2)\n\t\t\t\t\t\t\t\tif not frombegin:\n\t\t\t\t\t\t\t\t\tpaths1, paths2 = paths2, paths1\n\t\t\t\t\t\t\t\tfor a in paths1:\n\t\t\t\t\t\t\t\t\tfor b in paths2:\n\t\t\t\t\t\t\t\t\t\tans.append(a+b)\n\t\t\t\t\t\t\telif v not in visited1:\n\t\t\t\t\t\t\t\tif v not in level_visited:\n\t\t\t\t\t\t\t\t\tq.append(v)\n\t\t\t\t\t\t\t\tlevel_visited[v].append(u)\n\t\t\t\tvisited1.update(level_visited)\n\n\t\t\twhile q1 and q2 and not ans:\n\t\t\t\tif len(q1) <= len(q2):\n\t\t\t\t\tbfs(q1, visited1, visited2, True)\n\t\t\t\telse:\n\t\t\t\t\tbfs(q2, visited2, visited1, False)\n\n\t\t\treturn ans", "slug": "word-ladder-ii", "post_title": "46ms Python 97 Faster Working Multiple solutions 95% memory efficient solution", "user": "anuvabtest", "upvotes": 35, "views": 2800, "problem_title": "word ladder ii", "number": 126, "acceptance": 0.276, "difficulty": "Hard", "__index_level_0__": 1418, "question": "A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:\nEvery adjacent pair of words differs by a single letter.\nEvery si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.\nsk == endWord\nGiven 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 Example 1:\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput: [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\nExplanation: There are 2 shortest transformation sequences:\n\"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n\"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"\nExample 2:\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput: []\nExplanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n Constraints:\n1 <= beginWord.length <= 5\nendWord.length == beginWord.length\n1 <= wordList.length <= 500\nwordList[i].length == beginWord.length\nbeginWord, endWord, and wordList[i] consist of lowercase English letters.\nbeginWord != endWord\nAll the words in wordList are unique.\nThe sum of all shortest transformation sequences does not exceed 105." }, { "post_href": "https://leetcode.com/problems/word-ladder/discuss/1332551/Elegant-Python-Iterative-BFS", "python_solutions": "class Solution(object):\n def ladderLength(self, beginWord, endWord, wordList):\n\n graph = defaultdict(list)\n for word in wordList:\n for index in range(len(beginWord)):\n graph[word[:index] + \"_\" + word[index+1:]].append(word)\n\n queue = deque()\n queue.append((beginWord, 1))\n visited = set()\n while queue:\n current_node, current_level = queue.popleft()\n if current_node == endWord: return current_level\n for index in range(len(beginWord)):\n node = current_node[:index] + \"_\" + current_node[index+1:]\n for neighbour in graph[node]:\n if neighbour not in visited:\n queue.append((neighbour, current_level + 1))\n visited.add(neighbour)\n graph[node] = []\n \n return 0", "slug": "word-ladder", "post_title": "Elegant Python Iterative BFS", "user": "soma28", "upvotes": 4, "views": 366, "problem_title": "word ladder", "number": 127, "acceptance": 0.368, "difficulty": "Hard", "__index_level_0__": 1434, "question": "A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:\nEvery adjacent pair of words differs by a single letter.\nEvery si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.\nsk == endWord\nGiven 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 Example 1:\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\nOutput: 5\nExplanation: One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.\nExample 2:\nInput: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\nOutput: 0\nExplanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n Constraints:\n1 <= beginWord.length <= 10\nendWord.length == beginWord.length\n1 <= wordList.length <= 5000\nwordList[i].length == beginWord.length\nbeginWord, endWord, and wordList[i] consist of lowercase English letters.\nbeginWord != endWord\nAll the words in wordList are unique." }, { "post_href": "https://leetcode.com/problems/longest-consecutive-sequence/discuss/1109808/Python-Clean-Union-Find-with-explanation", "python_solutions": "class Node:\n def __init__(self, val):\n self.val = val\n self.parent = self\n self.size = 1\n \nclass UnionFind:\n \n def find(self, node):\n if node.parent != node:\n node.parent = self.find(node.parent)\n return node.parent\n \n def union(self, node1, node2):\n parent_1 = self.find(node1)\n parent_2 = self.find(node2)\n if parent_1 != parent_2:\n parent_2.parent = parent_1\n parent_1.size += parent_2.size\n return parent_1.size\n \n \n \nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n uf = UnionFind()\n nodes = {}\n max_size = 0\n for num in nums:\n if num not in nodes:\n node = Node(num)\n nodes[num] = node\n size = 1\n if num + 1 in nodes:\n size = uf.union(node, nodes[num+1])\n if num - 1 in nodes:\n size = uf.union(node, nodes[num-1])\n max_size = max(max_size, size)\n \n return max_size\n\t\t```", "slug": "longest-consecutive-sequence", "post_title": "[Python] Clean Union Find with explanation", "user": "l3arner", "upvotes": 21, "views": 1800, "problem_title": "longest consecutive sequence", "number": 128, "acceptance": 0.489, "difficulty": "Medium", "__index_level_0__": 1459, "question": "Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.\nYou must write an algorithm that runs in O(n) time.\n Example 1:\nInput: nums = [100,4,200,1,3,2]\nOutput: 4\nExplanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\nExample 2:\nInput: nums = [0,3,7,2,5,8,4,6,0,1]\nOutput: 9\n Constraints:\n0 <= nums.length <= 105\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/sum-root-to-leaf-numbers/discuss/1557540/Python-99-speed-99-memory", "python_solutions": "class Solution:\n def sumNumbers(self, root: Optional[TreeNode]) -> int:\n def helper(node, num):\n if node is None:\n return 0\n num = num * 10 + node.val\n if node.left is None and node.right is None:\n return num\n return helper(node.left, num) + helper(node.right, num)\n \n return helper(root, 0)", "slug": "sum-root-to-leaf-numbers", "post_title": "Python 99% speed, 99% memory", "user": "dereky4", "upvotes": 4, "views": 391, "problem_title": "sum root to leaf numbers", "number": 129, "acceptance": 0.588, "difficulty": "Medium", "__index_level_0__": 1509, "question": "You are given the root of a binary tree containing digits from 0 to 9 only.\nEach root-to-leaf path in the tree represents a number.\nFor example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.\nReturn the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.\nA leaf node is a node with no children.\n Example 1:\nInput: root = [1,2,3]\nOutput: 25\nExplanation:\nThe root-to-leaf path 1->2 represents the number 12.\nThe root-to-leaf path 1->3 represents the number 13.\nTherefore, sum = 12 + 13 = 25.\nExample 2:\nInput: root = [4,9,0,5,1]\nOutput: 1026\nExplanation:\nThe root-to-leaf path 4->9->5 represents the number 495.\nThe root-to-leaf path 4->9->1 represents the number 491.\nThe root-to-leaf path 4->0 represents the number 40.\nTherefore, sum = 495 + 491 + 40 = 1026.\n Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\n0 <= Node.val <= 9\nThe depth of the tree will not exceed 10." }, { "post_href": "https://leetcode.com/problems/surrounded-regions/discuss/558746/Python-DFS-Easy-solution-with-comments", "python_solutions": "class Solution:\n \n def dfs(self,board,i,j):\n \n if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]!='O':\n return\n board[i][j]='$' # converting to a dollar sign \n \n self.dfs(board,i+1,j)\n self.dfs(board,i-1,j)\n self.dfs(board,i,j+1)\n self.dfs(board,i,j-1)\n \n def solve(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n if len(board)==0:\n return None\n \n m=len(board)\n n=len(board[0])\n \n \n for i in range(m): # call dfs on all border 'O's and turn them to '$'\n for j in range(n):\n if i==0 or i==m-1:\n self.dfs(board,i,j)\n \n if j==0 or j==n-1:\n self.dfs(board,i,j)\n \n \n \n#all border O and others connected them were already converted to $ sign \n#so left out zeros are surely surrounded by 'X' . Turn all of them to 'X'\n for i in range(m): \n for j in range(n):\n if board[i][j]=='O':\n board[i][j]='X'\n \n# turn the border zeros and their adjacents to their initial form. ie $ -> O \n for i in range(m):\n for j in range(n):\n if board[i][j]=='$':\n board[i][j]='O'", "slug": "surrounded-regions", "post_title": "Python DFS Easy solution with comments", "user": "JoyRafatAshraf", "upvotes": 12, "views": 440, "problem_title": "surrounded regions", "number": 130, "acceptance": 0.361, "difficulty": "Medium", "__index_level_0__": 1541, "question": "Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n Example 1:\nInput: board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nOutput: [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\nExplanation: Notice that an 'O' should not be flipped if:\n- It is on the border, or\n- It is adjacent to an 'O' that should not be flipped.\nThe bottom 'O' is on the border, so it is not flipped.\nThe other three 'O' form a surrounded region, so they are flipped.\nExample 2:\nInput: board = [[\"X\"]]\nOutput: [[\"X\"]]\n Constraints:\nm == board.length\nn == board[i].length\n1 <= m, n <= 200\nboard[i][j] is 'X' or 'O'." }, { "post_href": "https://leetcode.com/problems/palindrome-partitioning/discuss/1667786/Python-Simple-Recursion-oror-Detailed-Explanation-oror-Easy-to-Understand", "python_solutions": "class Solution(object):\n @cache # the memory trick can save some time\n def partition(self, s):\n if not s: return [[]]\n ans = []\n for i in range(1, len(s) + 1):\n if s[:i] == s[:i][::-1]: # prefix is a palindrome\n for suf in self.partition(s[i:]): # process suffix recursively\n ans.append([s[:i]] + suf)\n return ans", "slug": "palindrome-partitioning", "post_title": "\u2705 [Python] Simple Recursion || Detailed Explanation || Easy to Understand", "user": "linfq", "upvotes": 209, "views": 9200, "problem_title": "palindrome partitioning", "number": 131, "acceptance": 0.626, "difficulty": "Medium", "__index_level_0__": 1593, "question": "Given a string s, partition s such that every\nsubstring\nof the partition is a\npalindrome\n. Return all possible palindrome partitioning of s.\n Example 1:\nInput: s = \"aab\"\nOutput: [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\nExample 2:\nInput: s = \"a\"\nOutput: [[\"a\"]]\n Constraints:\n1 <= s.length <= 16\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/palindrome-partitioning-ii/discuss/713271/Python3-dp-(top-down-and-bottom-up)", "python_solutions": "class Solution:\n def minCut(self, s: str) -> int:\n #pre-processing\n palin = dict()\n for k in range(len(s)):\n for i, j in (k, k), (k, k+1):\n while 0 <= i and j < len(s) and s[i] == s[j]: \n palin.setdefault(i, []).append(j)\n i, j = i-1, j+1\n \n #dp \n @lru_cache(None)\n def fn(i):\n \"\"\"Return minimum palindrome partitioning of s[i:]\"\"\"\n if i == len(s): return 0\n return min(1 + fn(ii+1) for ii in palin[i])\n \n return fn(0)-1", "slug": "palindrome-partitioning-ii", "post_title": "[Python3] dp (top-down & bottom-up)", "user": "ye15", "upvotes": 2, "views": 131, "problem_title": "palindrome partitioning ii", "number": 132, "acceptance": 0.337, "difficulty": "Hard", "__index_level_0__": 1633, "question": "Given a string s, partition s such that every\nsubstring\nof the partition is a\npalindrome\n.\nReturn the minimum cuts needed for a palindrome partitioning of s.\n Example 1:\nInput: s = \"aab\"\nOutput: 1\nExplanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\nExample 2:\nInput: s = \"a\"\nOutput: 0\nExample 3:\nInput: s = \"ab\"\nOutput: 1\n Constraints:\n1 <= s.length <= 2000\ns consists of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/clone-graph/discuss/1792858/Python3-ITERATIVE-BFS-(beats-98)-'less()greater''-Explained", "python_solutions": "class Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n if not node: return node\n \n q, clones = deque([node]), {node.val: Node(node.val, [])}\n while q:\n cur = q.popleft() \n cur_clone = clones[cur.val] \n\n for ngbr in cur.neighbors:\n if ngbr.val not in clones:\n clones[ngbr.val] = Node(ngbr.val, [])\n q.append(ngbr)\n \n cur_clone.neighbors.append(clones[ngbr.val])\n \n return clones[node.val]", "slug": "clone-graph", "post_title": "\u2714\ufe0f [Python3] ITERATIVE BFS (beats 98%) ,\uff64\u2019`<(\u275b\u30ee\u275b\u273f)>,\uff64\u2019`\u2019`,\uff64, Explained", "user": "artod", "upvotes": 181, "views": 15100, "problem_title": "clone graph", "number": 133, "acceptance": 0.509, "difficulty": "Medium", "__index_level_0__": 1641, "question": "Given a reference of a node in a connected undirected graph.\nReturn a deep copy (clone) of the graph.\nEach node in the graph contains a value (int) and a list (List[Node]) of its neighbors.\nclass Node {\n public int val;\n public List neighbors;\n}\n Test case format:\nFor simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.\nAn adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.\nThe given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.\n Example 1:\nInput: adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput: [[2,4],[1,3],[2,4],[1,3]]\nExplanation: There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\nExample 2:\nInput: adjList = [[]]\nOutput: [[]]\nExplanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.\nExample 3:\nInput: adjList = []\nOutput: []\nExplanation: This an empty graph, it does not have any nodes.\n Constraints:\nThe number of nodes in the graph is in the range [0, 100].\n1 <= Node.val <= 100\nNode.val is unique for each node.\nThere are no repeated edges and no self-loops in the graph.\nThe Graph is connected and all nodes can be visited starting from the given node." }, { "post_href": "https://leetcode.com/problems/gas-station/discuss/1276287/Simple-one-pass-python-solution", "python_solutions": "class Solution:\n\tdef canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n\t\t\n\t\t# base case\n\t\tif sum(gas) - sum(cost) < 0:\n\t\t\treturn -1\n\n\t\tgas_tank = 0 # gas available in car till now\n\t\tstart_index = 0 # Consider first gas station as starting point\n\n\t\tfor i in range(len(gas)):\n\n\t\t\tgas_tank += gas[i] - cost[i]\n\n\t\t\tif gas_tank < 0: # the car has deficit of petrol\n\t\t\t\tstart_index = i+1 # change the starting point\n\t\t\t\tgas_tank = 0 # make the current gas to 0, as we will be starting again from next station\n\n\t\treturn start_index", "slug": "gas-station", "post_title": "Simple one pass python solution", "user": "nandanabhishek", "upvotes": 9, "views": 796, "problem_title": "gas station", "number": 134, "acceptance": 0.451, "difficulty": "Medium", "__index_level_0__": 1676, "question": "There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].\nYou have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.\nGiven two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique\n Example 1:\nInput: gas = [1,2,3,4,5], cost = [3,4,5,1,2]\nOutput: 3\nExplanation:\nStart at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 4. Your tank = 4 - 1 + 5 = 8\nTravel to station 0. Your tank = 8 - 2 + 1 = 7\nTravel to station 1. Your tank = 7 - 3 + 2 = 6\nTravel to station 2. Your tank = 6 - 4 + 3 = 5\nTravel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\nTherefore, return 3 as the starting index.\nExample 2:\nInput: gas = [2,3,4], cost = [3,4,3]\nOutput: -1\nExplanation:\nYou can't start at station 0 or 1, as there is not enough gas to travel to the next station.\nLet's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\nTravel to station 0. Your tank = 4 - 3 + 2 = 3\nTravel to station 1. Your tank = 3 - 3 + 3 = 3\nYou cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\nTherefore, you can't travel around the circuit once no matter where you start.\n Constraints:\nn == gas.length == cost.length\n1 <= n <= 105\n0 <= gas[i], cost[i] <= 104" }, { "post_href": "https://leetcode.com/problems/candy/discuss/2234828/Python-oror-Two-pass-oror-explanation-oror-intuition-oror-greedy", "python_solutions": "class Solution:\n def candy(self, ratings: List[int]) -> int:\n n=len(ratings)\n temp = [1]*n\n \n for i in range(1,n):\n if(ratings[i]>ratings[i-1]):\n temp[i]=temp[i-1]+1\n if(n>1):\n if(ratings[0]>ratings[1]):\n temp[0]=2\n \n \n for i in range(n-2,-1,-1):\n if(ratings[i]>ratings[i+1] and temp[i]<=temp[i+1]):\n temp[i]=temp[i+1]+1\n\n \n return sum(temp)", "slug": "candy", "post_title": "Python || Two pass || explanation || intuition || greedy", "user": "palashbajpai214", "upvotes": 11, "views": 1200, "problem_title": "candy", "number": 135, "acceptance": 0.408, "difficulty": "Hard", "__index_level_0__": 1707, "question": "There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.\nYou are giving candies to these children subjected to the following requirements:\nEach child must have at least one candy.\nChildren with a higher rating get more candies than their neighbors.\nReturn the minimum number of candies you need to have to distribute the candies to the children.\n Example 1:\nInput: ratings = [1,0,2]\nOutput: 5\nExplanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\nExample 2:\nInput: ratings = [1,2,2]\nOutput: 4\nExplanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\nThe third child gets 1 candy because it satisfies the above two conditions.\n Constraints:\nn == ratings.length\n1 <= n <= 2 * 104\n0 <= ratings[i] <= 2 * 104" }, { "post_href": "https://leetcode.com/problems/single-number/discuss/2438883/Very-Easy-oror-0-ms-oror100oror-Fully-Explained-(Java-C%2B%2B-Python-JS-C-Python3)", "python_solutions": "class Solution(object):\n def singleNumber(self, nums):\n # Initialize the unique number...\n uniqNum = 0;\n # TRaverse all elements through the loop...\n for idx in nums:\n # Concept of XOR...\n uniqNum ^= idx;\n return uniqNum; # Return the unique number...", "slug": "single-number", "post_title": "Very Easy || 0 ms ||100%|| Fully Explained (Java, C++, Python, JS, C, Python3)", "user": "PratikSen07", "upvotes": 24, "views": 2100, "problem_title": "single number", "number": 136, "acceptance": 0.701, "difficulty": "Easy", "__index_level_0__": 1747, "question": "Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.\nYou must implement a solution with a linear runtime complexity and use only constant extra space.\n Example 1:\nInput: nums = [2,2,1]\nOutput: 1\nExample 2:\nInput: nums = [4,1,2,1,2]\nOutput: 4\nExample 3:\nInput: nums = [1]\nOutput: 1\n Constraints:\n1 <= nums.length <= 3 * 104\n-3 * 104 <= nums[i] <= 3 * 104\nEach element in the array appears twice except for one element which appears only once." }, { "post_href": "https://leetcode.com/problems/single-number-ii/discuss/1110333/3-python-solutions-with-different-approaches", "python_solutions": "class Solution(object):\n def singleNumber(self, nums):\n a, b = 0, 0\n for x in nums:\n a, b = (~x&a&~b)|(x&~a&b), ~a&(x^b)\n return b", "slug": "single-number-ii", "post_title": "3 python solutions with different approaches", "user": "mritunjoyhalder79", "upvotes": 9, "views": 796, "problem_title": "single number ii", "number": 137, "acceptance": 0.579, "difficulty": "Medium", "__index_level_0__": 1796, "question": "Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.\nYou must implement a solution with a linear runtime complexity and use only constant extra space.\n Example 1:\nInput: nums = [2,2,3,2]\nOutput: 3\nExample 2:\nInput: nums = [0,1,0,1,0,1,99]\nOutput: 99\n Constraints:\n1 <= nums.length <= 3 * 104\n-231 <= nums[i] <= 231 - 1\nEach element in nums appears exactly three times except for one element which appears once." }, { "post_href": "https://leetcode.com/problems/copy-list-with-random-pointer/discuss/1841010/Python3-JUST-TWO-STEPS-()-Explained", "python_solutions": "class Solution:\n def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':\n hm, zero = dict(), Node(0)\n \n cur, copy = head, zero\n while cur:\n copy.next = Node(cur.val)\n hm[cur] = copy.next\n cur, copy = cur.next, copy.next\n \n cur, copy = head, zero.next\n while cur:\n copy.random = hm[cur.random] if cur.random else None\n cur, copy = cur.next, copy.next\n \n return zero.next", "slug": "copy-list-with-random-pointer", "post_title": "\u2714\ufe0f [Python3] JUST TWO STEPS \u30fe(\u00b4\u25bd\uff40;)\u309d, Explained", "user": "artod", "upvotes": 43, "views": 1700, "problem_title": "copy list with random pointer", "number": 138, "acceptance": 0.506, "difficulty": "Medium", "__index_level_0__": 1827, "question": "A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.\nConstruct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.\nFor example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.\nReturn the head of the copied linked list.\nThe linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:\nval: an integer representing Node.val\nrandom_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.\nYour code will only be given the head of the original linked list.\n Example 1:\nInput: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\nOutput: [[7,null],[13,0],[11,4],[10,2],[1,0]]\nExample 2:\nInput: head = [[1,1],[2,1]]\nOutput: [[1,1],[2,1]]\nExample 3:\nInput: head = [[3,null],[3,0],[3,null]]\nOutput: [[3,null],[3,0],[3,null]]\n Constraints:\n0 <= n <= 1000\n-104 <= Node.val <= 104\nNode.random is null or is pointing to some node in the linked list." }, { "post_href": "https://leetcode.com/problems/word-break/discuss/748479/Python3-Solution-with-a-Detailed-Explanation-Word-Break", "python_solutions": "class Solution:\n def wordBreak(self, s, wordDict):\n\t\tdp = [False]*(len(s)+1)\n dp[0] = True\n \n for i in range(1, len(s)+1):\n for j in range(i):\n if dp[j] and s[j:i] in wordDict:\n\t\t\t\t\tdp[i] = True\n break\n \n return dp[-1]", "slug": "word-break", "post_title": "Python3 Solution with a Detailed Explanation - Word Break", "user": "peyman_np", "upvotes": 51, "views": 4600, "problem_title": "word break", "number": 139, "acceptance": 0.455, "difficulty": "Medium", "__index_level_0__": 1863, "question": "Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.\nNote that the same word in the dictionary may be reused multiple times in the segmentation.\n Example 1:\nInput: s = \"leetcode\", wordDict = [\"leet\",\"code\"]\nOutput: true\nExplanation: Return true because \"leetcode\" can be segmented as \"leet code\".\nExample 2:\nInput: s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]\nOutput: true\nExplanation: Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\nNote that you are allowed to reuse a dictionary word.\nExample 3:\nInput: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput: false\n Constraints:\n1 <= s.length <= 300\n1 <= wordDict.length <= 1000\n1 <= wordDict[i].length <= 20\ns and wordDict[i] consist of only lowercase English letters.\nAll the strings of wordDict are unique." }, { "post_href": "https://leetcode.com/problems/word-break-ii/discuss/744674/Diagrammatic-Python-Intuitive-Solution-with-Example", "python_solutions": "class Solution(object):\n def wordBreak(self, s, wordDict):\n \"\"\"\n :type s: str\n :type wordDict: List[str]\n :rtype: List[str]\n \"\"\"\n def wordsEndingIn(i):\n if i == len(s):\n return [\"\"]\n ans = []\n for j in range(i+1, len(s)+1):\n if s[i:j] in wordDict:\n for tail in wordsEndingIn(j):\n if tail != '':\n ans.append(s[i:j] + \" \" + tail) \n else:\n ans.append(s[i:j])\n return ans\n return wordsEndingIn(0)", "slug": "word-break-ii", "post_title": "Diagrammatic Python Intuitive Solution with Example", "user": "ivankatrump", "upvotes": 10, "views": 526, "problem_title": "word break ii", "number": 140, "acceptance": 0.446, "difficulty": "Hard", "__index_level_0__": 1916, "question": "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.\nNote that the same word in the dictionary may be reused multiple times in the segmentation.\n Example 1:\nInput: s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\nOutput: [\"cats and dog\",\"cat sand dog\"]\nExample 2:\nInput: s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\nOutput: [\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\nExplanation: Note that you are allowed to reuse a dictionary word.\nExample 3:\nInput: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\nOutput: []\n Constraints:\n1 <= s.length <= 20\n1 <= wordDict.length <= 1000\n1 <= wordDict[i].length <= 10\ns and wordDict[i] consist of only lowercase English letters.\nAll the strings of wordDict are unique.\nInput is generated in a way that the length of the answer doesn't exceed 105." }, { "post_href": "https://leetcode.com/problems/linked-list-cycle/discuss/1047819/Easy-in-Pythonor-O(1)-or-Beats-91", "python_solutions": "class Solution(object):\n def hasCycle(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: bool\n \"\"\"\n\t\tif head is None or head.next is None return False\n slow_ref = head\n fast_ref = head\n while fast_ref and fast_ref.next:\n slow_ref = slow_ref.next\n fast_ref = fast_ref.next.next\n if slow_ref == fast_ref:\n return True\n return False\n\t\t\n\tIf you get it please Upvote.", "slug": "linked-list-cycle", "post_title": "Easy in Python| O(1) | Beats 91%", "user": "vsahoo", "upvotes": 13, "views": 948, "problem_title": "linked list cycle", "number": 141, "acceptance": 0.47, "difficulty": "Easy", "__index_level_0__": 1966, "question": "Given head, the head of a linked list, determine if the linked list has a cycle in it.\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.\nReturn true if there is a cycle in the linked list. Otherwise, return false.\n Example 1:\nInput: head = [3,2,0,-4], pos = 1\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\nExample 2:\nInput: head = [1,2], pos = 0\nOutput: true\nExplanation: There is a cycle in the linked list, where the tail connects to the 0th node.\nExample 3:\nInput: head = [1], pos = -1\nOutput: false\nExplanation: There is no cycle in the linked list.\n Constraints:\nThe number of the nodes in the list is in the range [0, 104].\n-105 <= Node.val <= 105\npos is -1 or a valid index in the linked-list.\n Follow up: Can you solve it using O(1) (i.e. constant) memory?" }, { "post_href": "https://leetcode.com/problems/linked-list-cycle-ii/discuss/2184711/O(1)-Space-Python-solution-with-clear-explanation-faster-than-90-solutions", "python_solutions": "class Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n fast, slow = head, head\n while(fast and fast.next):\n fast = fast.next.next\n slow = slow.next\n if(fast == slow):\n slow = head\n while(slow is not fast):\n fast = fast.next\n slow = slow.next\n return slow\n return None", "slug": "linked-list-cycle-ii", "post_title": "O(1) Space Python solution with clear explanation faster than 90% solutions", "user": "saiamrit", "upvotes": 30, "views": 844, "problem_title": "linked list cycle ii", "number": 142, "acceptance": 0.465, "difficulty": "Medium", "__index_level_0__": 2010, "question": "Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.\nThere is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.\nDo not modify the linked list.\n Example 1:\nInput: head = [3,2,0,-4], pos = 1\nOutput: tail connects to node index 1\nExplanation: There is a cycle in the linked list, where tail connects to the second node.\nExample 2:\nInput: head = [1,2], pos = 0\nOutput: tail connects to node index 0\nExplanation: There is a cycle in the linked list, where tail connects to the first node.\nExample 3:\nInput: head = [1], pos = -1\nOutput: no cycle\nExplanation: There is no cycle in the linked list.\n Constraints:\nThe number of the nodes in the list is in the range [0, 104].\n-105 <= Node.val <= 105\npos is -1 or a valid index in the linked-list.\n Follow up: Can you solve it using O(1) (i.e. constant) memory?" }, { "post_href": "https://leetcode.com/problems/reorder-list/discuss/1640529/Python3-ONE-PASS-L(o)-Explained", "python_solutions": "class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n if not head.next or not head.next.next:\n return\n \n # search for the middle\n slow, fast = head, head\n while fast.next and fast.next.next:\n slow = slow.next\n fast = fast.next.next\n\n tail, cur = None, slow.next\n slow.next = None # detach list on the middle\n \n # reverse right part\n while cur:\n cur.next, tail, cur = tail, cur, cur.next\n \n\t\t# rearrange nodes as asked\n headCur, headNext = head, head.next\n tailCur, tailNext = tail, tail.next\n while True:\n headCur.next, tailCur.next = tailCur, headNext\n \n if not tailNext:\n return\n \n tailCur, headCur = tailNext, headNext\n tailNext, headNext = tailNext.next, headNext.next", "slug": "reorder-list", "post_title": "\u2714\ufe0f [Python3] ONE PASS, L(\u30fbo\u30fb)\u300d, Explained", "user": "artod", "upvotes": 5, "views": 482, "problem_title": "reorder list", "number": 143, "acceptance": 0.513, "difficulty": "Medium", "__index_level_0__": 2043, "question": "You are given the head of a singly linked-list. The list can be represented as:\nL0 \u2192 L1 \u2192 \u2026 \u2192 Ln - 1 \u2192 Ln\nReorder the list to be on the following form:\nL0 \u2192 Ln \u2192 L1 \u2192 Ln - 1 \u2192 L2 \u2192 Ln - 2 \u2192 \u2026\nYou may not modify the values in the list's nodes. Only nodes themselves may be changed.\n Example 1:\nInput: head = [1,2,3,4]\nOutput: [1,4,2,3]\nExample 2:\nInput: head = [1,2,3,4,5]\nOutput: [1,5,2,4,3]\n Constraints:\nThe number of nodes in the list is in the range [1, 5 * 104].\n1 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/binary-tree-preorder-traversal/discuss/1403244/3-Simple-Python-solutions", "python_solutions": "class Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n ans = []\n stack = [root]\n \n while stack:\n temp = stack.pop()\n \n if temp:\n ans.append(temp.val)\n stack.append(temp.right) #as we are using stack which works on LIFO, we need to push right tree first so that left will be popped out\n stack.append(temp.left)\n \n return ans", "slug": "binary-tree-preorder-traversal", "post_title": "3 Simple Python solutions", "user": "shraddhapp", "upvotes": 14, "views": 1100, "problem_title": "binary tree preorder traversal", "number": 144, "acceptance": 0.648, "difficulty": "Easy", "__index_level_0__": 2070, "question": "Given the root of a binary tree, return the preorder traversal of its nodes' values.\n Example 1:\nInput: root = [1,null,2,3]\nOutput: [1,2,3]\nExample 2:\nInput: root = []\nOutput: []\nExample 3:\nInput: root = [1]\nOutput: [1]\n Constraints:\nThe number of nodes in the tree is in the range [0, 100].\n-100 <= Node.val <= 100\n Follow up: Recursive solution is trivial, could you do it iteratively?" }, { "post_href": "https://leetcode.com/problems/binary-tree-postorder-traversal/discuss/2443702/Easy-oror-Recursive-and-Iterative-oror-100-oror-Explained-(Java-C%2B%2B-Python-Python3)", "python_solutions": "class Solution(object):\n def postorderTraversal(self, root):\n # Base case...\n if not root: return []\n # Create an array list to store the solution result...\n sol = []\n # Create an empty stack and push the root node...\n bag = [root]\n # Loop till stack is empty...\n while bag:\n # Pop a node from the stack...\n node = bag.pop()\n sol.append(node.val)\n # Push the left child of the popped node into the stack...\n if node.left:\n bag.append(node.left)\n # Append the right child of the popped node into the stack...\n if node.right:\n bag.append(node.right)\n return sol[::-1] # Return the solution list...", "slug": "binary-tree-postorder-traversal", "post_title": "Easy || Recursive & Iterative || 100% || Explained (Java, C++, Python, Python3)", "user": "PratikSen07", "upvotes": 16, "views": 1100, "problem_title": "binary tree postorder traversal", "number": 145, "acceptance": 0.6679999999999999, "difficulty": "Easy", "__index_level_0__": 2093, "question": "Given the root of a binary tree, return the postorder traversal of its nodes' values.\n Example 1:\nInput: root = [1,null,2,3]\nOutput: [3,2,1]\nExample 2:\nInput: root = []\nOutput: []\nExample 3:\nInput: root = [1]\nOutput: [1]\n Constraints:\nThe number of the nodes in the tree is in the range [0, 100].\n-100 <= Node.val <= 100\n Follow up: Recursive solution is trivial, could you do it iteratively?" }, { "post_href": "https://leetcode.com/problems/lru-cache/discuss/442751/Python3-hashmap-and-doubly-linked-list", "python_solutions": "class ListNode:\n def __init__(self, key=0, val=0, prev=None, next=None):\n self.key = key\n self.val = val\n self.prev = prev\n self.next = next\n \n\nclass LRUCache:\n\n def __init__(self, capacity: int):\n \"\"\"Initialize hash table & dll\"\"\"\n self.cpty = capacity\n self.htab = dict() #hash table \n self.head = ListNode() #doubly linked list\n self.tail = ListNode()\n self.head.next = self.tail\n self.tail.prev = self.head \n \n def _del(self, key: int) -> int: \n \"\"\"Delete given key from hash table & dll\"\"\"\n node = self.htab.pop(key)\n node.prev.next = node.next\n node.next.prev = node.prev\n return node.val\n\n def _ins(self, key: int, value: int) -> None: \n \"\"\"Insert at tail\"\"\"\n node = ListNode(key, value, self.tail.prev, self.tail)\n self.tail.prev.next = self.tail.prev = node\n self.htab[key] = node\n \n def get(self, key: int) -> int:\n if key not in self.htab: return -1\n value = self._del(key)\n self._ins(key, value)\n return value\n\n def put(self, key: int, value: int) -> None:\n if key in self.htab: self._del(key)\n self._ins(key, value)\n if len(self.htab) > self.cpty: \n self._del(self.head.next.key)\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)", "slug": "lru-cache", "post_title": "[Python3] hashmap & doubly-linked list", "user": "ye15", "upvotes": 8, "views": 457, "problem_title": "lru cache", "number": 146, "acceptance": 0.405, "difficulty": "Medium", "__index_level_0__": 2129, "question": "Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.\nImplement the LRUCache class:\nLRUCache(int capacity) Initialize the LRU cache with positive size capacity.\nint get(int key) Return the value of the key if the key exists, otherwise return -1.\nvoid put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.\nThe functions get and put must each run in O(1) average time complexity.\n Example 1:\nInput\n[\"LRUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]\nOutput\n[null, null, null, 1, null, -1, null, -1, 3, 4]\n\nExplanation\nLRUCache lRUCache = new LRUCache(2);\nlRUCache.put(1, 1); // cache is {1=1}\nlRUCache.put(2, 2); // cache is {1=1, 2=2}\nlRUCache.get(1); // return 1\nlRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\nlRUCache.get(2); // returns -1 (not found)\nlRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\nlRUCache.get(1); // return -1 (not found)\nlRUCache.get(3); // return 3\nlRUCache.get(4); // return 4\n Constraints:\n1 <= capacity <= 3000\n0 <= key <= 104\n0 <= value <= 105\nAt most 2 * 105 calls will be made to get and put." }, { "post_href": "https://leetcode.com/problems/insertion-sort-list/discuss/1176552/Python3-188ms-Solution-(explanation-with-visualization)", "python_solutions": "class Solution:\n def insertionSortList(self, head: ListNode) -> ListNode:\n \n # No need to sort for empty list or list of size 1\n if not head or not head.next:\n return head\n \n # Use dummy_head will help us to handle insertion before head easily\n dummy_head = ListNode(val=-5000, next=head)\n last_sorted = head # last node of the sorted part\n cur = head.next # cur is always the next node of last_sorted\n while cur:\n if cur.val >= last_sorted.val:\n last_sorted = last_sorted.next\n else:\n # Search for the position to insert\n prev = dummy_head\n while prev.next.val <= cur.val:\n prev = prev.next\n \n # Insert\n last_sorted.next = cur.next\n cur.next = prev.next\n prev.next = cur\n \n cur = last_sorted.next\n \n return dummy_head.next", "slug": "insertion-sort-list", "post_title": "[Python3] 188ms Solution (explanation with visualization)", "user": "EckoTan0804", "upvotes": 28, "views": 834, "problem_title": "insertion sort list", "number": 147, "acceptance": 0.503, "difficulty": "Medium", "__index_level_0__": 2176, "question": "Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.\nThe steps of the insertion sort algorithm:\nInsertion sort iterates, consuming one input element each repetition and growing a sorted output list.\nAt each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.\nIt repeats until no input elements remain.\nThe following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.\n Example 1:\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\nExample 2:\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\n Constraints:\nThe number of nodes in the list is in the range [1, 5000].\n-5000 <= Node.val <= 5000" }, { "post_href": "https://leetcode.com/problems/sort-list/discuss/1796085/Sort-List-or-Python-O(nlogn)-Solution-or-95-Faster", "python_solutions": "class Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not head or not head.next:\n return head\n \n # Split the list into two halfs\n left = head\n right = self.getMid(head)\n tmp = right.next\n right.next = None\n right = tmp\n \n left = self.sortList(left)\n right = self.sortList(right)\n \n return self.merge(left, right)\n \n def getMid(self, head):\n slow = head\n fast = head.next\n \n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n return slow\n \n # Merge the list\n def merge(self, list1, list2):\n newHead = tail = ListNode()\n while list1 and list2:\n if list1.val > list2.val:\n tail.next = list2\n list2 = list2.next\n else:\n tail.next = list1\n list1 = list1.next\n tail = tail.next\n \n if list1:\n tail.next = list1\n if list2:\n tail.next = list2\n \n return newHead.next", "slug": "sort-list", "post_title": "\u2714\ufe0f Sort List | Python O(nlogn) Solution | 95% Faster", "user": "pniraj657", "upvotes": 25, "views": 1900, "problem_title": "sort list", "number": 148, "acceptance": 0.5429999999999999, "difficulty": "Medium", "__index_level_0__": 2197, "question": "Given the head of a linked list, return the list after sorting it in ascending order.\n Example 1:\nInput: head = [4,2,1,3]\nOutput: [1,2,3,4]\nExample 2:\nInput: head = [-1,5,3,4,0]\nOutput: [-1,0,3,4,5]\nExample 3:\nInput: head = []\nOutput: []\n Constraints:\nThe number of nodes in the list is in the range [0, 5 * 104].\n-105 <= Node.val <= 105\n Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?" }, { "post_href": "https://leetcode.com/problems/max-points-on-a-line/discuss/1983010/Python-3-Using-Slopes-and-Hash-Tables-or-Clean-Python-solution", "python_solutions": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n if len(points) <= 2:\n return len(points)\n \n def find_slope(p1, p2):\n x1, y1 = p1\n x2, y2 = p2\n if x1-x2 == 0:\n return inf\n return (y1-y2)/(x1-x2)\n \n ans = 1\n for i, p1 in enumerate(points):\n slopes = defaultdict(int)\n for j, p2 in enumerate(points[i+1:]):\n slope = find_slope(p1, p2)\n slopes[slope] += 1\n ans = max(slopes[slope], ans)\n return ans+1", "slug": "max-points-on-a-line", "post_title": "[Python 3] Using Slopes and Hash Tables | Clean Python solution", "user": "hari19041", "upvotes": 33, "views": 1200, "problem_title": "max points on a line", "number": 149, "acceptance": 0.218, "difficulty": "Hard", "__index_level_0__": 2219, "question": "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 Example 1:\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 3\nExample 2:\nInput: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\nOutput: 4\n Constraints:\n1 <= points.length <= 300\npoints[i].length == 2\n-104 <= xi, yi <= 104\nAll the points are unique." }, { "post_href": "https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/1732651/Super-Simple-Python-stack-solution", "python_solutions": "class Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n \n def update(sign):\n n2,n1=stack.pop(),stack.pop()\n if sign==\"+\": return n1+n2\n if sign==\"-\": return n1-n2\n if sign==\"*\": return n1*n2\n if sign==\"/\": return int(n1/n2)\n\t\t\t\n stack=[]\n \n for n in tokens:\n if n.isdigit() or len(n)>1:\n stack.append(int(n))\n else:\n stack.append(update(n))\n return stack.pop()", "slug": "evaluate-reverse-polish-notation", "post_title": "Super Simple Python \ud83d\udc0d stack solution", "user": "InjySarhan", "upvotes": 6, "views": 380, "problem_title": "evaluate reverse polish notation", "number": 150, "acceptance": 0.441, "difficulty": "Medium", "__index_level_0__": 2242, "question": "You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.\nEvaluate the expression. Return an integer that represents the value of the expression.\nNote that:\nThe valid operators are '+', '-', '*', and '/'.\nEach operand may be an integer or another expression.\nThe division between two integers always truncates toward zero.\nThere will not be any division by zero.\nThe input represents a valid arithmetic expression in a reverse polish notation.\nThe answer and all the intermediate calculations can be represented in a 32-bit integer.\n Example 1:\nInput: tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\nOutput: 9\nExplanation: ((2 + 1) * 3) = 9\nExample 2:\nInput: tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\nOutput: 6\nExplanation: (4 + (13 / 5)) = 6\nExample 3:\nInput: tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\nOutput: 22\nExplanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5\n= ((10 * (6 / (12 * -11))) + 17) + 5\n= ((10 * (6 / -132)) + 17) + 5\n= ((10 * 0) + 17) + 5\n= (0 + 17) + 5\n= 17 + 5\n= 22\n Constraints:\n1 <= tokens.length <= 104\ntokens[i] is either an operator: \"+\", \"-\", \"*\", or \"/\", or an integer in the range [-200, 200]." }, { "post_href": "https://leetcode.com/problems/reverse-words-in-a-string/discuss/1632928/Intuitive-Two-Pointers-in-Python-without-strip()-or-split()", "python_solutions": "class Solution:\n def reverseWords(self, s: str) -> str:\n #Time: O(n) since we scan through the input, where n = len(s)\n #Space: O(n)\n words = []\n slow, fast = 0, 0\n \n #Use the first char to determine if we're starting on a \" \" or a word\n mode = 'blank' if s[0] == ' ' else 'word'\n \n while fast < len(s):\n #If we start on a word and our fast ptr lands on a white space\n #means that we have singled out a word\n if mode == 'word' and s[fast] == ' ':\n words.append(s[slow:fast])\n slow = fast #Make the slow ptr catch up\n mode = 'blank'\n \n #If we start on a white space and our fast ptr runs into a character\n #means we are at the start of a word \n elif mode == 'blank' and s[fast] != ' ':\n slow = fast #Make the slow ptr catch up\n mode = 'word'\n \n fast += 1 #Increment the fast pointer\n \n #Append the last word\n #Edge cases where the last chunk of string are white spaces\n if (lastWord := s[slow:fast]).isalnum():\n words.append(lastWord)\n \n return ' '.join(words[::-1])", "slug": "reverse-words-in-a-string", "post_title": "Intuitive Two Pointers in Python without strip() or split()", "user": "surin_lovejoy", "upvotes": 10, "views": 490, "problem_title": "reverse words in a string", "number": 151, "acceptance": 0.318, "difficulty": "Medium", "__index_level_0__": 2290, "question": "Given an input string s, reverse the order of the words.\nA word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.\nReturn a string of the words in reverse order concatenated by a single space.\nNote that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.\n Example 1:\nInput: s = \"the sky is blue\"\nOutput: \"blue is sky the\"\nExample 2:\nInput: s = \" hello world \"\nOutput: \"world hello\"\nExplanation: Your reversed string should not contain leading or trailing spaces.\nExample 3:\nInput: s = \"a good example\"\nOutput: \"example good a\"\nExplanation: You need to reduce multiple spaces between two words to a single space in the reversed string.\n Constraints:\n1 <= s.length <= 104\ns contains English letters (upper-case and lower-case), digits, and spaces ' '.\nThere is at least one word in s.\n Follow-up: If the string data type is mutable in your language, can you solve it in-place with O(1) extra space?" }, { "post_href": "https://leetcode.com/problems/maximum-product-subarray/discuss/1608907/Python3-DYNAMIC-PROGRAMMING-Explained", "python_solutions": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n curMax, curMin = 1, 1\n res = nums[0]\n \n for n in nums:\n vals = (n, n * curMax, n * curMin)\n curMax, curMin = max(vals), min(vals)\n\t\t\t\n res = max(res, curMax)\n \n return res", "slug": "maximum-product-subarray", "post_title": "\u2714\ufe0f[Python3] DYNAMIC PROGRAMMING, Explained", "user": "artod", "upvotes": 90, "views": 9700, "problem_title": "maximum product subarray", "number": 152, "acceptance": 0.349, "difficulty": "Medium", "__index_level_0__": 2340, "question": "Given an integer array nums, find a\nsubarray\nthat has the largest product, and return the product.\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n Example 1:\nInput: nums = [2,3,-2,4]\nOutput: 6\nExplanation: [2,3] has the largest product 6.\nExample 2:\nInput: nums = [-2,0,-1]\nOutput: 0\nExplanation: The result cannot be 2, because [-2,-1] is not a subarray.\n Constraints:\n1 <= nums.length <= 2 * 104\n-10 <= nums[i] <= 10\nThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer." }, { "post_href": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/2211586/Python3-simple-naive-solution-with-binary-search", "python_solutions": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n start = 0\n end = len(nums) - 1\n \n if(nums[start] <= nums[end]):\n return nums[0]\n \n while start <= end:\n mid = (start + end) // 2\n \n if(nums[mid] > nums[mid+1]):\n return nums[mid+1]\n \n if(nums[mid-1] > nums[mid]):\n return nums[mid]\n \n if(nums[mid] > nums[0]):\n start = mid + 1\n else:\n end = mid - 1\n \n return nums[start]", "slug": "find-minimum-in-rotated-sorted-array", "post_title": "\ud83d\udccc Python3 simple naive solution with binary search", "user": "Dark_wolf_jss", "upvotes": 6, "views": 105, "problem_title": "find minimum in rotated sorted array", "number": 153, "acceptance": 0.485, "difficulty": "Medium", "__index_level_0__": 2389, "question": "Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:\n[4,5,6,7,0,1,2] if it was rotated 4 times.\n[0,1,2,4,5,6,7] if it was rotated 7 times.\nNotice 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]].\nGiven the sorted rotated array nums of unique elements, return the minimum element of this array.\nYou must write an algorithm that runs in O(log n) time.\n Example 1:\nInput: nums = [3,4,5,1,2]\nOutput: 1\nExplanation: The original array was [1,2,3,4,5] rotated 3 times.\nExample 2:\nInput: nums = [4,5,6,7,0,1,2]\nOutput: 0\nExplanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.\nExample 3:\nInput: nums = [11,13,15,17]\nOutput: 11\nExplanation: The original array was [11,13,15,17] and it was rotated 4 times. \n Constraints:\nn == nums.length\n1 <= n <= 5000\n-5000 <= nums[i] <= 5000\nAll the integers of nums are unique.\nnums is sorted and rotated between 1 and n times." }, { "post_href": "https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/discuss/2087295/Binary-Search-oror-Explained-oror-PYTHON", "python_solutions": "class Solution:\n def findMin(self, a: List[int]) -> int:\n \n def solve(l,h):\n while la[h-1]:\n l=m+1\n \n elif a[m] None:\n self.stack.append(self.stackWithMinElements(\n x, min(x, self.getMin()) if len(self.stack)>0 else x))\n\n def pop(self) -> None:\n self.stack.pop()\n\n def top(self) -> int:\n return self.stack[-1].element\n\n def getMin(self) -> int:\n return self.stack[-1].minimum", "slug": "min-stack", "post_title": "Python 3 -> 91% faster using namedtuple", "user": "mybuddy29", "upvotes": 5, "views": 554, "problem_title": "min stack", "number": 155, "acceptance": 0.519, "difficulty": "Medium", "__index_level_0__": 2457, "question": "Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\nImplement the MinStack class:\nMinStack() initializes the stack object.\nvoid push(int val) pushes the element val onto the stack.\nvoid pop() removes the element on the top of the stack.\nint top() gets the top element of the stack.\nint getMin() retrieves the minimum element in the stack.\nYou must implement a solution with O(1) time complexity for each function.\n Example 1:\nInput\n[\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n[[],[-2],[0],[-3],[],[],[],[]]\n\nOutput\n[null,null,null,null,-3,null,0,-2]\n\nExplanation\nMinStack minStack = new MinStack();\nminStack.push(-2);\nminStack.push(0);\nminStack.push(-3);\nminStack.getMin(); // return -3\nminStack.pop();\nminStack.top(); // return 0\nminStack.getMin(); // return -2\n Constraints:\n-231 <= val <= 231 - 1\nMethods pop, top and getMin operations will always be called on non-empty stacks.\nAt most 3 * 104 calls will be made to push, pop, top, and getMin." }, { "post_href": "https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/2116127/Python-oror-Easy-2-approaches-oror-O(1)-space", "python_solutions": "class Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n first_set=set()\n curr=headA\n \n while curr:\n first_set.add(curr)\n curr=curr.next\n \n curr = headB\n while curr:\n if curr in first_set:\n return curr\n curr=curr.next\n\n return None", "slug": "intersection-of-two-linked-lists", "post_title": "Python || Easy 2 approaches || O(1) space", "user": "constantine786", "upvotes": 75, "views": 5200, "problem_title": "intersection of two linked lists", "number": 160, "acceptance": 0.534, "difficulty": "Easy", "__index_level_0__": 2513, "question": "Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.\nFor example, the following two linked lists begin to intersect at node c1:\nThe test cases are generated such that there are no cycles anywhere in the entire linked structure.\nNote that the linked lists must retain their original structure after the function returns.\nCustom Judge:\nThe inputs to the judge are given as follows (your program is not given these inputs):\nintersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.\nlistA - The first linked list.\nlistB - The second linked list.\nskipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.\nskipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.\nThe judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted.\n Example 1:\nInput: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\nOutput: Intersected at '8'\nExplanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.\n- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.\nExample 2:\nInput: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\nOutput: Intersected at '2'\nExplanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\nFrom the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.\nExample 3:\nInput: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\nOutput: No intersection\nExplanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.\nExplanation: The two lists do not intersect, so return null.\n Constraints:\nThe number of nodes of listA is in the m.\nThe number of nodes of listB is in the n.\n1 <= m, n <= 3 * 104\n1 <= Node.val <= 105\n0 <= skipA < m\n0 <= skipB < n\nintersectVal is 0 if listA and listB do not intersect.\nintersectVal == listA[skipA] == listB[skipB] if listA and listB intersect.\n Follow up: Could you write a solution that runs in O(m + n) time and use only O(1) memory?" }, { "post_href": "https://leetcode.com/problems/find-peak-element/discuss/1440424/Python-oror-Easy-Solution", "python_solutions": "class Solution:\n\tdef findPeakElement(self, lst: List[int]) -> int:\n\t\tstart, end = 0, len(lst) - 1\n\n\t\twhile start < end:\n\n\t\t\tmid = start + (end - start) // 2\n\n\t\t\tif lst[mid] > lst[mid + 1]:\n\t\t\t\tend = mid\n\t\t\telse:\n\t\t\t\tstart = mid + 1\n\n\t\treturn start", "slug": "find-peak-element", "post_title": "Python || Easy Solution", "user": "naveenrathore", "upvotes": 8, "views": 619, "problem_title": "find peak element", "number": 162, "acceptance": 0.462, "difficulty": "Medium", "__index_level_0__": 2545, "question": "A peak element is an element that is strictly greater than its neighbors.\nGiven a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.\nYou may imagine that nums[-1] = nums[n] = -\u221e. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.\nYou must write an algorithm that runs in O(log n) time.\n Example 1:\nInput: nums = [1,2,3,1]\nOutput: 2\nExplanation: 3 is a peak element and your function should return the index number 2.\nExample 2:\nInput: nums = [1,2,1,3,5,6,4]\nOutput: 5\nExplanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.\n Constraints:\n1 <= nums.length <= 1000\n-231 <= nums[i] <= 231 - 1\nnums[i] != nums[i + 1] for all valid i." }, { "post_href": "https://leetcode.com/problems/maximum-gap/discuss/727709/Python3-group-data-into-buckets", "python_solutions": "class Solution:\n def maximumGap(self, nums: List[int]) -> int:\n if len(nums) == 0: return 0 #edge case \n mn, mx = min(nums), max(nums)\n step = max(1, (mx - mn)//(len(nums)-1)) #n-1 holes \n size = (mx - mn)//step + 1\n buckets = [[inf, -inf] for _ in range(size)]\n \n for num in nums: \n i = (num - mn)//step\n x, xx = buckets[i]\n buckets[i] = min(x, num), max(xx, num)\n \n ans = 0\n prev = mn\n for i in range(size):\n x, xx = buckets[i]\n if x < inf:\n ans = max(ans, x - prev)\n prev = xx \n return ans", "slug": "maximum-gap", "post_title": "[Python3] group data into buckets", "user": "ye15", "upvotes": 6, "views": 291, "problem_title": "maximum gap", "number": 164, "acceptance": 0.428, "difficulty": "Hard", "__index_level_0__": 2589, "question": "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.\nYou must write an algorithm that runs in linear time and uses linear extra space.\n Example 1:\nInput: nums = [3,6,9,1]\nOutput: 3\nExplanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\nExample 2:\nInput: nums = [10]\nOutput: 0\nExplanation: The array contains less than 2 elements, therefore return 0.\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/compare-version-numbers/discuss/1797594/Python3-SOLUTION-Explained", "python_solutions": "class Solution:\n def compareVersion(self, v1: str, v2: str) -> int:\n v1, v2 = list(map(int, v1.split('.'))), list(map(int, v2.split('.'))) \n for rev1, rev2 in zip_longest(v1, v2, fillvalue=0):\n if rev1 == rev2:\n continue\n\n return -1 if rev1 < rev2 else 1 \n\n return 0", "slug": "compare-version-numbers", "post_title": "\u2714\ufe0f [Python3] SOLUTION, Explained", "user": "artod", "upvotes": 47, "views": 3400, "problem_title": "compare version numbers", "number": 165, "acceptance": 0.354, "difficulty": "Medium", "__index_level_0__": 2610, "question": "Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots '.'. The value of the revision is its integer conversion ignoring leading zeros.\nTo compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.\nReturn the following:\nIf version1 < version2, return -1.\nIf version1 > version2, return 1.\nOtherwise, return 0.\n Example 1:\nInput: version1 = \"1.2\", version2 = \"1.10\"\nOutput: -1\nExplanation:\nversion1's second revision is \"2\" and version2's second revision is \"10\": 2 < 10, so version1 < version2.\nExample 2:\nInput: version1 = \"1.01\", version2 = \"1.001\"\nOutput: 0\nExplanation:\nIgnoring leading zeroes, both \"01\" and \"001\" represent the same integer \"1\".\nExample 3:\nInput: version1 = \"1.0\", version2 = \"1.0.0.0\"\nOutput: 0\nExplanation:\nversion1 has less revisions, which means every missing revision are treated as \"0\".\n Constraints:\n1 <= version1.length, version2.length <= 500\nversion1 and version2 only contain digits and '.'.\nversion1 and version2 are valid version numbers.\nAll the given revisions in version1 and version2 can be stored in a 32-bit integer." }, { "post_href": "https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/998707/Python-solution-with-detail-explanation", "python_solutions": "class Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n \n if numerator % denominator == 0: \n\t\t\treturn str(numerator // denominator)\n \n prefix = ''\n if (numerator > 0) != (denominator > 0):\n prefix = '-'\n \n # Operation must be on positive values\n if numerator < 0:\n numerator = - numerator\n if denominator < 0:\n denominator = - denominator\n\n digit, remainder = divmod(numerator, denominator)\n \n res = prefix + str(digit) + '.' # EVERYTHING BEFORE DECIMAL\n \n table = {}\n suffix = ''\n \n while remainder not in table.keys():\n \n # Store index of the reminder in the table\n table[remainder] = len(suffix)\n \n val, remainder = divmod(remainder*10, denominator)\n \n suffix += str(val)\n \n # No repeating\n if remainder == 0:\n return res + suffix\n \n indexOfRepeatingPart = table[remainder]\n \n decimalTillRepeatingPart = suffix[:indexOfRepeatingPart]\n \n repeatingPart = suffix[indexOfRepeatingPart:]\n\n return res + decimalTillRepeatingPart + '(' + repeatingPart + ')'\n\ns = Solution()\n\nprint(s.fractionToDecimal(2, 3))", "slug": "fraction-to-recurring-decimal", "post_title": "Python solution with detail explanation", "user": "imasterleet", "upvotes": 3, "views": 650, "problem_title": "fraction to recurring decimal", "number": 166, "acceptance": 0.241, "difficulty": "Medium", "__index_level_0__": 2647, "question": "Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.\nIf the fractional part is repeating, enclose the repeating part in parentheses.\nIf multiple answers are possible, return any of them.\nIt is guaranteed that the length of the answer string is less than 104 for all the given inputs.\n Example 1:\nInput: numerator = 1, denominator = 2\nOutput: \"0.5\"\nExample 2:\nInput: numerator = 2, denominator = 1\nOutput: \"2\"\nExample 3:\nInput: numerator = 4, denominator = 333\nOutput: \"0.(012)\"\n Constraints:\n-231 <= numerator, denominator <= 231 - 1\ndenominator != 0" }, { "post_href": "https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/2128459/Python-Easy-O(1)-Space", "python_solutions": "class Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n i = 0\n j = len(numbers) -1\n \n while i target:\n j-=1\n else:\n i+=1 \n \n return []", "slug": "two-sum-ii-input-array-is-sorted", "post_title": "Python Easy O(1) Space", "user": "constantine786", "upvotes": 51, "views": 3700, "problem_title": "two sum ii input array is sorted", "number": 167, "acceptance": 0.6, "difficulty": "Medium", "__index_level_0__": 2656, "question": "Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.\nReturn the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.\nThe tests are generated such that there is exactly one solution. You may not use the same element twice.\nYour solution must use only constant extra space.\n Example 1:\nInput: numbers = [2,7,11,15], target = 9\nOutput: [1,2]\nExplanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].\nExample 2:\nInput: numbers = [2,3,4], target = 6\nOutput: [1,3]\nExplanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].\nExample 3:\nInput: numbers = [-1,0], target = -1\nOutput: [1,2]\nExplanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].\n Constraints:\n2 <= numbers.length <= 3 * 104\n-1000 <= numbers[i] <= 1000\nnumbers is sorted in non-decreasing order.\n-1000 <= target <= 1000\nThe tests are generated such that there is exactly one solution." }, { "post_href": "https://leetcode.com/problems/excel-sheet-column-title/discuss/2448578/Easy-oror-0-ms-oror-100-oror-Fully-Explained-(Java-C%2B%2B-Python-Python3)", "python_solutions": "class Solution(object):\n def convertToTitle(self, columnNumber):\n # Create an empty string for storing the characters...\n output = \"\"\n # Run a while loop while columnNumber is positive...\n while columnNumber > 0:\n # Subtract 1 from columnNumber and get current character by doing modulo of columnNumber by 26...\n output = chr(ord('A') + (columnNumber - 1) % 26) + output\n # Divide columnNumber by 26...\n columnNumber = (columnNumber - 1) // 26\n # Return the output string.\n return output", "slug": "excel-sheet-column-title", "post_title": "Easy || 0 ms || 100% || Fully Explained (Java, C++, Python, Python3)", "user": "PratikSen07", "upvotes": 22, "views": 1300, "problem_title": "excel sheet column title", "number": 168, "acceptance": 0.348, "difficulty": "Easy", "__index_level_0__": 2709, "question": "Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.\nFor example:\nA -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...\n Example 1:\nInput: columnNumber = 1\nOutput: \"A\"\nExample 2:\nInput: columnNumber = 28\nOutput: \"AB\"\nExample 3:\nInput: columnNumber = 701\nOutput: \"ZY\"\n Constraints:\n1 <= columnNumber <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/majority-element/discuss/1788112/Python-easy-solution-O(n)-or-O(1)-or-explained", "python_solutions": "class Solution:\n def majorityElement(self, nums: List[int]) -> int:\n curr, count = nums[0], 1 # curr will store the current majority element, count will store the count of the majority\n for i in range(1,len(nums)):\n count += (1 if curr == nums[i] else -1) # if i is equal to current majority, they're in same team, hence added, else one current majority and i both will be dead\n if not count: # if count is 0 means King is de-throwned\n curr = nums[i+1] if i + 1 < len(nums) else None # the next element is the new King\n count = 0 # starting it with 0 because we can't increment the i of the for loop, the count will be 1 in next iteration, and again the battle continues after next iteration\n return curr", "slug": "majority-element", "post_title": "\u2705 Python easy solution O(n) | O(1) | explained", "user": "dhananjay79", "upvotes": 18, "views": 1700, "problem_title": "majority element", "number": 169, "acceptance": 0.639, "difficulty": "Easy", "__index_level_0__": 2746, "question": "Given an array nums of size n, return the majority element.\nThe majority element is the element that appears more than \u230an / 2\u230b times. You may assume that the majority element always exists in the array.\n Example 1:\nInput: nums = [3,2,3]\nOutput: 3\nExample 2:\nInput: nums = [2,2,1,1,1,2,2]\nOutput: 2\n Constraints:\nn == nums.length\n1 <= n <= 5 * 104\n-109 <= nums[i] <= 109\n Follow-up: Could you solve the problem in linear time and in O(1) space?" }, { "post_href": "https://leetcode.com/problems/excel-sheet-column-number/discuss/1790567/Python3-CLEAN-SOLUTION-()-Explained", "python_solutions": "class Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n ans, pos = 0, 0\n for letter in reversed(columnTitle):\n digit = ord(letter)-64\n ans += digit * 26**pos\n pos += 1\n \n return ans", "slug": "excel-sheet-column-number", "post_title": "\u2714\ufe0f [Python3] CLEAN SOLUTION (\u0e51\u275b\ua19a\u275b\u0e51), Explained", "user": "artod", "upvotes": 105, "views": 8500, "problem_title": "excel sheet column number", "number": 171, "acceptance": 0.614, "difficulty": "Easy", "__index_level_0__": 2793, "question": "Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.\nFor example:\nA -> 1\nB -> 2\nC -> 3\n...\nZ -> 26\nAA -> 27\nAB -> 28 \n...\n Example 1:\nInput: columnTitle = \"A\"\nOutput: 1\nExample 2:\nInput: columnTitle = \"AB\"\nOutput: 28\nExample 3:\nInput: columnTitle = \"ZY\"\nOutput: 701\n Constraints:\n1 <= columnTitle.length <= 7\ncolumnTitle consists only of uppercase English letters.\ncolumnTitle is in the range [\"A\", \"FXSHRXW\"]." }, { "post_href": "https://leetcode.com/problems/factorial-trailing-zeroes/discuss/1152167/Python3-O(log(n))-time-O(1)-space.-Explanation", "python_solutions": "class Solution:\n def trailingZeroes(self, n: int) -> int:\n quotient = n // 5\n return quotient + self.trailingZeroes(quotient) if quotient >= 5 else quotient", "slug": "factorial-trailing-zeroes", "post_title": "Python3 O(log(n)) time, O(1) space. Explanation", "user": "ryancodrai", "upvotes": 12, "views": 472, "problem_title": "factorial trailing zeroes", "number": 172, "acceptance": 0.418, "difficulty": "Medium", "__index_level_0__": 2851, "question": "Given an integer n, return the number of trailing zeroes in n!.\nNote that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.\n Example 1:\nInput: n = 3\nOutput: 0\nExplanation: 3! = 6, no trailing zero.\nExample 2:\nInput: n = 5\nOutput: 1\nExplanation: 5! = 120, one trailing zero.\nExample 3:\nInput: n = 0\nOutput: 0\n Constraints:\n0 <= n <= 104\n Follow up: Could you write a solution that works in logarithmic time complexity?" }, { "post_href": "https://leetcode.com/problems/binary-search-tree-iterator/discuss/1965156/Python-TC-O(1)-SC-O(h)-Generator-Solution", "python_solutions": "class BSTIterator:\n def __init__(self, root: Optional[TreeNode]):\n self.iter = self._inorder(root)\n self.nxt = next(self.iter, None)\n \n def _inorder(self, node: Optional[TreeNode]) -> Generator[int, None, None]:\n if node:\n yield from self._inorder(node.left)\n yield node.val\n yield from self._inorder(node.right)\n\n def next(self) -> int:\n res, self.nxt = self.nxt, next(self.iter, None)\n return res\n\n def hasNext(self) -> bool:\n return self.nxt is not None", "slug": "binary-search-tree-iterator", "post_title": "[Python] TC O(1) SC O(h) Generator Solution", "user": "zayne-siew", "upvotes": 34, "views": 2300, "problem_title": "binary search tree iterator", "number": 173, "acceptance": 0.6920000000000001, "difficulty": "Medium", "__index_level_0__": 2878, "question": "Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):\nBSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.\nboolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.\nint next() Moves the pointer to the right, then returns the number at the pointer.\nNotice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.\nYou may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.\n Example 1:\nInput\n[\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\nOutput\n[null, 3, 7, true, 9, true, 15, true, 20, false]\n\nExplanation\nBSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\nbSTIterator.next(); // return 3\nbSTIterator.next(); // return 7\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 9\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 15\nbSTIterator.hasNext(); // return True\nbSTIterator.next(); // return 20\nbSTIterator.hasNext(); // return False\n Constraints:\nThe number of nodes in the tree is in the range [1, 105].\n0 <= Node.val <= 106\nAt most 105 calls will be made to hasNext, and next.\n Follow up:\nCould you implement next() and hasNext() to run in average O(1) time and use O(h) memory, where h is the height of the tree?" }, { "post_href": "https://leetcode.com/problems/dungeon-game/discuss/699433/Python3-dp", "python_solutions": "class Solution:\n def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n m, n = len(dungeon), len(dungeon[0])\n \n @cache\n def fn(i, j):\n \"\"\"Return min health at (i,j).\"\"\"\n if i == m or j == n: return inf\n if i == m-1 and j == n-1: return max(1, 1 - dungeon[i][j])\n return max(1, min(fn(i+1, j), fn(i, j+1)) - dungeon[i][j])\n \n return fn(0, 0)", "slug": "dungeon-game", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 1, "views": 45, "problem_title": "dungeon game", "number": 174, "acceptance": 0.373, "difficulty": "Hard", "__index_level_0__": 2911, "question": "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.\nThe 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.\nSome 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).\nTo reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\nReturn the knight's minimum initial health so that he can rescue the princess.\nNote 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 Example 1:\nInput: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\nOutput: 7\nExplanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.\nExample 2:\nInput: dungeon = [[0]]\nOutput: 1\n Constraints:\nm == dungeon.length\nn == dungeon[i].length\n1 <= m, n <= 200\n-1000 <= dungeon[i][j] <= 1000" }, { "post_href": "https://leetcode.com/problems/largest-number/discuss/1391073/python-easy-custom-sort-solution!!!!!!!", "python_solutions": "class Solution:\n def largestNumber(self, nums: List[int]) -> str:\n nums = sorted(nums,key=lambda x:x / (10 ** len(str(x)) - 1 ), reverse=True)\n str_nums = [str(num) for num in nums]\n res = ''.join(str_nums)\n res = str(int(res))\n return res", "slug": "largest-number", "post_title": "python easy custom sort solution!!!!!!!", "user": "user0665m", "upvotes": 9, "views": 900, "problem_title": "largest number", "number": 179, "acceptance": 0.341, "difficulty": "Medium", "__index_level_0__": 2928, "question": "Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.\nSince the result may be very large, so you need to return a string instead of an integer.\n Example 1:\nInput: nums = [10,2]\nOutput: \"210\"\nExample 2:\nInput: nums = [3,30,34,5,9]\nOutput: \"9534330\"\n Constraints:\n1 <= nums.length <= 100\n0 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/repeated-dna-sequences/discuss/2223482/Simple-Python-Solution-oror-O(n)-Time-oror-O(n)-Space-oror-Sliding-Window", "python_solutions": "class Solution:\n def findRepeatedDnaSequences(self, s: str) -> List[str]:\n \n res, d = [], {}\n for i in range(len(s)):\n \n if s[i:i+10] not in d: d[s[i:i+10]] = 0\n elif s[i:i+10] not in res: res.append(s[i:i+10])\n \n return res\n\t\t\n\t\t# An Upvote will be encouraging", "slug": "repeated-dna-sequences", "post_title": "Simple Python Solution || O(n) Time || O(n) Space || Sliding Window", "user": "rajkumarerrakutti", "upvotes": 2, "views": 121, "problem_title": "repeated dna sequences", "number": 187, "acceptance": 0.4629999999999999, "difficulty": "Medium", "__index_level_0__": 2949, "question": "The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.\nFor example, \"ACGAATTCCG\" is a DNA sequence.\nWhen studying DNA, it is useful to identify repeated sequences within the DNA.\nGiven a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.\n Example 1:\nInput: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nOutput: [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\nExample 2:\nInput: s = \"AAAAAAAAAAAAA\"\nOutput: [\"AAAAAAAAAA\"]\n Constraints:\n1 <= s.length <= 105\ns[i] is either 'A', 'C', 'G', or 'T'." }, { "post_href": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/2555699/LeetCode-The-Hard-Way-7-Lines-or-Line-By-Line-Explanation", "python_solutions": "class Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n # no transaction, no profit\n if k == 0: return 0\n # dp[k][0] = min cost you need to spend at most k transactions\n # dp[k][1] = max profit you can achieve at most k transactions\n dp = [[1000, 0] for _ in range(k + 1)]\n for price in prices:\n for i in range(1, k + 1):\n # price - dp[i - 1][1] is how much you need to spend\n # i.e use the profit you earned from previous transaction to buy the stock\n # we want to minimize it\n dp[i][0] = min(dp[i][0], price - dp[i - 1][1])\n # price - dp[i][0] is how much you can achieve from previous min cost\n # we want to maximize it\n dp[i][1] = max(dp[i][1], price - dp[i][0])\n # return max profit at most k transactions\n\t\t# or you can write `return dp[-1][1]`\n return dp[k][1]", "slug": "best-time-to-buy-and-sell-stock-iv", "post_title": "\ud83d\udd25 [LeetCode The Hard Way] \ud83d\udd25 7 Lines | Line By Line Explanation", "user": "wingkwong", "upvotes": 62, "views": 3600, "problem_title": "best time to buy and sell stock iv", "number": 188, "acceptance": 0.381, "difficulty": "Hard", "__index_level_0__": 2969, "question": "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.\nFind the maximum profit you can achieve. You may complete at most k transactions: i.e. you may buy at most k times and sell at most k times.\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\nInput: k = 2, prices = [2,4,1]\nOutput: 2\nExplanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\nExample 2:\nInput: k = 2, prices = [3,2,6,5,0,3]\nOutput: 7\nExplanation: 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 Constraints:\n1 <= k <= 100\n1 <= prices.length <= 1000\n0 <= prices[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/rotate-array/discuss/1419527/Python-or-Two-Pointers-solution", "python_solutions": "class Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n \n def twopt(arr, i, j):\n while (i < j):\n arr[i], arr[j] = arr[j], arr[i]\n i += 1\n j -= 1\n return arr\n \n if k > len(nums):\n k %= len(nums)\n \n if (k > 0):\n twopt(nums, 0, len(nums) - 1) # rotate entire array\n twopt(nums, 0, k - 1) # rotate array upto k elements\n twopt(nums, k, len(nums) - 1) # rotate array from k to end of array", "slug": "rotate-array", "post_title": "Python | Two-Pointers solution", "user": "Shreya19595", "upvotes": 31, "views": 3900, "problem_title": "rotate array", "number": 189, "acceptance": 0.392, "difficulty": "Medium", "__index_level_0__": 3000, "question": "Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.\n Example 1:\nInput: nums = [1,2,3,4,5,6,7], k = 3\nOutput: [5,6,7,1,2,3,4]\nExplanation:\nrotate 1 steps to the right: [7,1,2,3,4,5,6]\nrotate 2 steps to the right: [6,7,1,2,3,4,5]\nrotate 3 steps to the right: [5,6,7,1,2,3,4]\nExample 2:\nInput: nums = [-1,-100,3,99], k = 2\nOutput: [3,99,-1,-100]\nExplanation: \nrotate 1 steps to the right: [99,-1,-100,3]\nrotate 2 steps to the right: [3,99,-1,-100]\n Constraints:\n1 <= nums.length <= 105\n-231 <= nums[i] <= 231 - 1\n0 <= k <= 105\n Follow up:\nTry to come up with as many solutions as you can. There are at least three different ways to solve this problem.\nCould you do it in-place with O(1) extra space?" }, { "post_href": "https://leetcode.com/problems/reverse-bits/discuss/1791099/Python-3-(40ms)-or-Real-BIT-Manipulation-Solution", "python_solutions": "class Solution:\n def reverseBits(self, n: int) -> int:\n res = 0\n for _ in range(32):\n res = (res<<1) + (n&1)\n n>>=1\n return res", "slug": "reverse-bits", "post_title": "Python 3 (40ms) | Real BIT Manipulation Solution", "user": "MrShobhit", "upvotes": 22, "views": 1800, "problem_title": "reverse bits", "number": 190, "acceptance": 0.525, "difficulty": "Easy", "__index_level_0__": 3053, "question": "Reverse bits of a given 32 bits unsigned integer.\nNote:\nNote that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.\nIn Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.\n Example 1:\nInput: n = 00000010100101000001111010011100\nOutput: 964176192 (00111001011110000010100101000000)\nExplanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.\nExample 2:\nInput: n = 11111111111111111111111111111101\nOutput: 3221225471 (10111111111111111111111111111111)\nExplanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.\n Constraints:\nThe input must be a binary string of length 32\n Follow up: If this function is called many times, how would you optimize it?" }, { "post_href": "https://leetcode.com/problems/number-of-1-bits/discuss/2074152/Easy-O(1)-Space-PythonC%2B%2B", "python_solutions": "class Solution:\n def hammingWeight(self, n: int) -> int: \n return sum((n & (1<= len(nums):\n return 0\n \n if start in self.cache:\n return self.cache[start]\n \n self.cache[start] = nums[start] + max(self.rob_rec(nums, start+2), self.rob_rec(nums, start+3))\n return self.cache[start]\n \n def rob(self, nums: List[int]) -> int:\n return max(self.rob_rec(nums, 0), self.rob_rec(nums, 1))", "slug": "house-robber", "post_title": "Python multiple solutions", "user": "amchoukir", "upvotes": 23, "views": 2500, "problem_title": "house robber", "number": 198, "acceptance": 0.488, "difficulty": "Medium", "__index_level_0__": 3149, "question": "You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\nGiven an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.\n Example 1:\nInput: nums = [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\nTotal amount you can rob = 1 + 3 = 4.\nExample 2:\nInput: nums = [2,7,9,3,1]\nOutput: 12\nExplanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\nTotal amount you can rob = 2 + 9 + 1 = 12.\n Constraints:\n1 <= nums.length <= 100\n0 <= nums[i] <= 400" }, { "post_href": "https://leetcode.com/problems/binary-tree-right-side-view/discuss/2266055/C%2B%2B-oror-PYTHON-oror-EXPLAINED-oror", "python_solutions": "class Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n \n def solve(root, lvl):\n \tif root:\n \t\tif len(res)==lvl:\n \t\t\tres.append(root.val)\n \t\tsolve(root.right, lvl + 1)\n \t\tsolve(root.left, lvl + 1)\n \treturn \n\n res = []\n solve(root,0)\n return res", "slug": "binary-tree-right-side-view", "post_title": "\u2714\ufe0f C++ || PYTHON || EXPLAINED || ; ]", "user": "karan_8082", "upvotes": 80, "views": 4400, "problem_title": "binary tree right side view", "number": 199, "acceptance": 0.612, "difficulty": "Medium", "__index_level_0__": 3210, "question": "Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.\n Example 1:\nInput: root = [1,2,3,null,5,null,4]\nOutput: [1,3,4]\nExample 2:\nInput: root = [1,null,3]\nOutput: [1,3]\nExample 3:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 100].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-islands/discuss/863366/Python-3-or-DFS-BFS-Union-Find-All-3-methods-or-Explanation", "python_solutions": "class Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n if not grid: return 0\n m, n = len(grid), len(grid[0])\n ans = 0\n def dfs(i, j):\n grid[i][j] = '2'\n for di, dj in (0, 1), (0, -1), (1, 0), (-1, 0):\n ii, jj = i+di, j+dj\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] == '1':\n dfs(ii, jj)\n for i in range(m):\n for j in range(n):\n if grid[i][j] == '1':\n dfs(i, j)\n ans += 1\n return ans", "slug": "number-of-islands", "post_title": "Python 3 | DFS, BFS, Union Find, All 3 methods | Explanation", "user": "idontknoooo", "upvotes": 50, "views": 5200, "problem_title": "number of islands", "number": 200, "acceptance": 0.564, "difficulty": "Medium", "__index_level_0__": 3235, "question": "Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.\nAn island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.\n Example 1:\nInput: grid = [\n [\"1\",\"1\",\"1\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"1\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"0\",\"0\"]\n]\nOutput: 1\nExample 2:\nInput: grid = [\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"1\",\"1\",\"0\",\"0\",\"0\"],\n [\"0\",\"0\",\"1\",\"0\",\"0\"],\n [\"0\",\"0\",\"0\",\"1\",\"1\"]\n]\nOutput: 3\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 300\ngrid[i][j] is '0' or '1'." }, { "post_href": "https://leetcode.com/problems/bitwise-and-of-numbers-range/discuss/469130/Python-iterative-sol.-based-on-bit-manipulation", "python_solutions": "class Solution:\n def rangeBitwiseAnd(self, m: int, n: int) -> int:\n \n shift = 0\n \n # find the common MSB bits.\n while m != n:\n \n m = m >> 1\n n = n >> 1\n \n shift += 1\n \n \n return m << shift", "slug": "bitwise-and-of-numbers-range", "post_title": "Python iterative sol. based on bit-manipulation", "user": "brianchiang_tw", "upvotes": 9, "views": 723, "problem_title": "bitwise and of numbers range", "number": 201, "acceptance": 0.423, "difficulty": "Medium", "__index_level_0__": 3287, "question": "Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.\n Example 1:\nInput: left = 5, right = 7\nOutput: 4\nExample 2:\nInput: left = 0, right = 0\nOutput: 0\nExample 3:\nInput: left = 1, right = 2147483647\nOutput: 0\n Constraints:\n0 <= left <= right <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/happy-number/discuss/2383810/Very-Easy-0-ms-100(Fully-Explained)(C%2B%2B-Java-Python-JS-C-Python3)", "python_solutions": "class Solution(object):\n def isHappy(self, n):\n hset = set()\n while n != 1:\n if n in hset: return False\n hset.add(n)\n n = sum([int(i) ** 2 for i in str(n)])\n else:\n return True", "slug": "happy-number", "post_title": "Very Easy 0 ms 100%(Fully Explained)(C++, Java, Python, JS, C, Python3)", "user": "PratikSen07", "upvotes": 18, "views": 1700, "problem_title": "happy number", "number": 202, "acceptance": 0.545, "difficulty": "Easy", "__index_level_0__": 3301, "question": "Write an algorithm to determine if a number n is happy.\nA happy number is a number defined by the following process:\nStarting with any positive integer, replace the number by the sum of the squares of its digits.\nRepeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.\nThose numbers for which this process ends in 1 are happy.\nReturn true if n is a happy number, and false if not.\n Example 1:\nInput: n = 19\nOutput: true\nExplanation:\n12 + 92 = 82\n82 + 22 = 68\n62 + 82 = 100\n12 + 02 + 02 = 1\nExample 2:\nInput: n = 2\nOutput: false\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/remove-linked-list-elements/discuss/158651/Simple-Python-solution-with-explanation-(single-pointer-dummy-head).", "python_solutions": "class Solution:\n def removeElements(self, head, val):\n \"\"\"\n :type head: ListNode\n :type val: int\n :rtype: ListNode\n \"\"\"\n \n dummy_head = ListNode(-1)\n dummy_head.next = head\n \n current_node = dummy_head\n while current_node.next != None:\n if current_node.next.val == val:\n current_node.next = current_node.next.next\n else:\n current_node = current_node.next\n \n return dummy_head.next", "slug": "remove-linked-list-elements", "post_title": "Simple Python solution with explanation (single pointer, dummy head).", "user": "Hai_dee", "upvotes": 429, "views": 28900, "problem_title": "remove linked list elements", "number": 203, "acceptance": 0.449, "difficulty": "Easy", "__index_level_0__": 3349, "question": "Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.\n Example 1:\nInput: head = [1,2,6,3,4,5,6], val = 6\nOutput: [1,2,3,4,5]\nExample 2:\nInput: head = [], val = 1\nOutput: []\nExample 3:\nInput: head = [7,7,7,7], val = 7\nOutput: []\n Constraints:\nThe number of nodes in the list is in the range [0, 104].\n1 <= Node.val <= 50\n0 <= val <= 50" }, { "post_href": "https://leetcode.com/problems/count-primes/discuss/1267254/Python-3-solution-97.7-faster", "python_solutions": "class Solution:\n def countPrimes(self, n: int) -> int:\n \n if n<2:\n return 0\n \n #initialize a list of length n\n prime=[1]*n\n\t\t#mark 0th and 1st index as 0\n prime[0]=prime[1]=0\n \n\t\t#we will check for multiple from range 2 to sqrt(n)\n for i in range(2,int(sqrt(n))+1):\n if prime[i] == 1:\n\t\t\t#mark all multiple of prime number as 0\n prime[i*i:n:i] = [0] * ((n-1-i*i)//i + 1)\n #return total count of prime \n return sum(prime)", "slug": "count-primes", "post_title": "Python 3 solution 97.7% faster", "user": "ritesh98", "upvotes": 11, "views": 1700, "problem_title": "count primes", "number": 204, "acceptance": 0.331, "difficulty": "Medium", "__index_level_0__": 3375, "question": "Given an integer n, return the number of prime numbers that are strictly less than n.\n Example 1:\nInput: n = 10\nOutput: 4\nExplanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\nExample 2:\nInput: n = 0\nOutput: 0\nExample 3:\nInput: n = 1\nOutput: 0\n Constraints:\n0 <= n <= 5 * 106" }, { "post_href": "https://leetcode.com/problems/isomorphic-strings/discuss/2472118/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashMap)", "python_solutions": "class Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return [*map(s.index, s)] == [*map(t.index, t)]", "slug": "isomorphic-strings", "post_title": "Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashMap)", "user": "PratikSen07", "upvotes": 44, "views": 5500, "problem_title": "isomorphic strings", "number": 205, "acceptance": 0.426, "difficulty": "Easy", "__index_level_0__": 3395, "question": "Given two strings s and t, determine if they are isomorphic.\nTwo strings s and t are isomorphic if the characters in s can be replaced to get t.\nAll occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.\n Example 1:\nInput: s = \"egg\", t = \"add\"\nOutput: true\nExample 2:\nInput: s = \"foo\", t = \"bar\"\nOutput: false\nExample 3:\nInput: s = \"paper\", t = \"title\"\nOutput: true\n Constraints:\n1 <= s.length <= 5 * 104\nt.length == s.length\ns and t consist of any valid ascii character." }, { "post_href": "https://leetcode.com/problems/reverse-linked-list/discuss/2458632/Easy-oror-0-ms-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Recursive-and-Iterative)", "python_solutions": "class Solution(object):\n def reverseList(self, head):\n # Initialize prev pointer as NULL...\n prev = None\n # Initialize the curr pointer as the head...\n curr = head\n # Run a loop till curr points to NULL...\n while curr:\n # Initialize next pointer as the next pointer of curr...\n next = curr.next\n # Now assign the prev pointer to curr\u2019s next pointer.\n curr.next = prev\n # Assign curr to prev, next to curr...\n prev = curr\n curr = next\n return prev # Return the prev pointer to get the reverse linked list...", "slug": "reverse-linked-list", "post_title": "Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Recursive & Iterative)", "user": "PratikSen07", "upvotes": 92, "views": 6800, "problem_title": "reverse linked list", "number": 206, "acceptance": 0.726, "difficulty": "Easy", "__index_level_0__": 3451, "question": "Given the head of a singly linked list, reverse the list, and return the reversed list.\n Example 1:\nInput: head = [1,2,3,4,5]\nOutput: [5,4,3,2,1]\nExample 2:\nInput: head = [1,2]\nOutput: [2,1]\nExample 3:\nInput: head = []\nOutput: []\n Constraints:\nThe number of nodes in the list is the range [0, 5000].\n-5000 <= Node.val <= 5000\n Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?" }, { "post_href": "https://leetcode.com/problems/course-schedule/discuss/1627381/Simple-and-Easy-Topological-Sorting-code-beats-97.63-python-submissions", "python_solutions": "class Solution:\n\tdef canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n\t\tgraph=defaultdict(list)\n\t\tindegree={}\n\n\t\t#initialising dictionary\n\t\tfor i in range(numCourses):\n\t\t\tindegree[i]=0\t\n\n\t\t#filling graph and indegree dictionaries\n\t\tfor child,parent in prerequisites:\n\t\t\tgraph[parent].append(child)\n\t\t\tindegree[child]+=1\n\n\t\tqueue=deque()\n\t\tfor key,value in indegree.items():\n\t\t\tif value==0:\n\t\t\t\tqueue.append(key)\n\n\t\tcourseSequence=[]\n\t\twhile queue:\n\t\t\tcourse=queue.popleft()\n\t\t\tcourseSequence.append(course)\n\t\t\tfor neighbour in graph[course]:\n\t\t\t\tindegree[neighbour]-=1\n\t\t\t\tif indegree[neighbour]==0:\n\t\t\t\t\tqueue.append(neighbour)\n\n\t\treturn len(courseSequence)==numCourses:", "slug": "course-schedule", "post_title": "Simple and Easy Topological Sorting code, beats 97.63% python submissions", "user": "RaghavGupta22", "upvotes": 11, "views": 1400, "problem_title": "course schedule", "number": 207, "acceptance": 0.4539999999999999, "difficulty": "Medium", "__index_level_0__": 3483, "question": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.\nFor example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\nReturn true if you can finish all courses. Otherwise, return false.\n Example 1:\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: true\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0. So it is possible.\nExample 2:\nInput: numCourses = 2, prerequisites = [[1,0],[0,1]]\nOutput: false\nExplanation: There are a total of 2 courses to take. \nTo take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.\n Constraints:\n1 <= numCourses <= 2000\n0 <= prerequisites.length <= 5000\nprerequisites[i].length == 2\n0 <= ai, bi < numCourses\nAll the pairs prerequisites[i] are unique." }, { "post_href": "https://leetcode.com/problems/minimum-size-subarray-sum/discuss/1774062/Python-Explanation-of-sliding-window-using-comments", "python_solutions": "class Solution:\n def minSubArrayLen(self, target: int, nums: List[int]) -> int:\n \n left = 0 # keep track of left pointer\n rsum = 0 # keep the running sum\n res = None # Answer we will return\n \n # Iterate through the array, the index will be your right pointer\n for right in range(len(nums)):\n \n # Add the current value to the running sum\n rsum += nums[right]\n \n # Once you reach a value at or equal to the target you\n # can use a while loop to start subtracting the values from left\n # to right so that you can produce the minimum size subarray\n while rsum >= target:\n \n # The result is either the current result you have, \n # or the count of numbers from the current left position \n # to the rightmost position. You need it to be right + 1 \n # because index starts at 0 (if you based the right as the \n # last index it would be 4 or len(nums) - 1)\n \n # If res is None we compare it against the max float, \n # saves us from having an if/else\n res = min(res or float('inf'), right + 1 - left)\n \n # Subtract the number to see if we can continue subtracting based\n # on the while loop case and increment the left pointer\n rsum -= nums[left]\n left += 1\n\n return res or 0", "slug": "minimum-size-subarray-sum", "post_title": "Python - Explanation of sliding window using comments", "user": "iamricks", "upvotes": 8, "views": 376, "problem_title": "minimum size subarray sum", "number": 209, "acceptance": 0.445, "difficulty": "Medium", "__index_level_0__": 3530, "question": "Given an array of positive integers nums and a positive integer target, return the minimal length of a\nsubarray\nwhose sum is greater than or equal to target. If there is no such subarray, return 0 instead.\n Example 1:\nInput: target = 7, nums = [2,3,1,2,4,3]\nOutput: 2\nExplanation: The subarray [4,3] has the minimal length under the problem constraint.\nExample 2:\nInput: target = 4, nums = [1,4,4]\nOutput: 1\nExample 3:\nInput: target = 11, nums = [1,1,1,1,1,1,1,1]\nOutput: 0\n Constraints:\n1 <= target <= 109\n1 <= nums.length <= 105\n1 <= nums[i] <= 104\n Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n))." }, { "post_href": "https://leetcode.com/problems/course-schedule-ii/discuss/1327646/Elegant-Python-DFS", "python_solutions": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n \n # Handle edge case.\n if not prerequisites: return [course for course in range(numCourses)]\n \n # 'parents' maps each course to a list of its pre\n\t\t# -requisites.\n parents = {course: [] for course in range(numCourses)}\n for course, prerequisite in prerequisites:\n parents[course].append(prerequisite)\n \n topological_order = []\n visited, current_path = [False]*numCourses, [False]*numCourses\n \n # Returns False if the digraph rooted at 'course'\n\t\t# is acyclic, else, appends courses to 'topological\n # _order' in topological order and returns True.\n def dfs(course):\n if current_path[course]: return False\n if visited[course]: return True\n visited[course], current_path[course] = True, True\n if parents[course]:\n for parent in parents[course]:\n if not dfs(parent): return False\n topological_order.append(course)\n current_path[course] = False\n return True\n \n for course in range(numCourses):\n if not dfs(course): return []\n \n return topological_order", "slug": "course-schedule-ii", "post_title": "Elegant Python DFS", "user": "soma28", "upvotes": 4, "views": 467, "problem_title": "course schedule ii", "number": 210, "acceptance": 0.481, "difficulty": "Medium", "__index_level_0__": 3580, "question": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.\nFor example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\nReturn the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.\n Example 1:\nInput: numCourses = 2, prerequisites = [[1,0]]\nOutput: [0,1]\nExplanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1].\nExample 2:\nInput: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\nOutput: [0,2,1,3]\nExplanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.\nSo one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].\nExample 3:\nInput: numCourses = 1, prerequisites = []\nOutput: [0]\n Constraints:\n1 <= numCourses <= 2000\n0 <= prerequisites.length <= numCourses * (numCourses - 1)\nprerequisites[i].length == 2\n0 <= ai, bi < numCourses\nai != bi\nAll the pairs [ai, bi] are distinct." }, { "post_href": "https://leetcode.com/problems/word-search-ii/discuss/2351408/python3-solution-oror-99-more-faster-oror-39-ms", "python_solutions": "class Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n m = len(board)\n n = len(board[0])\n res = []\n\n d = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n\n ref = set()\n for i in range(m):\n for j in range(n-1):\n ref.add(board[i][j] + board[i][j+1])\n for j in range(n):\n for i in range(m-1):\n ref.add(board[i][j] + board[i+1][j])\n\n for word in words:\n f = True\n for i in range(len(word)-1):\n if word[i:i+2] not in ref and word[i+1] + word[i] not in ref:\n f = False\n break\n if not f:\n continue\n if self.findWord(word, m, n, board, d):\n res.append(word)\n return res\n \n def findWord(self, word, m, n, board, d) -> bool:\n if word[:4] == word[0] * 4:\n word = ''.join([c for c in reversed(word)])\n starts = []\n stack = []\n visited = set()\n for i in range(m):\n for j in range(n):\n if board[i][j] == word[0]:\n if len(word) == 1:\n return True\n starts.append((i, j))\n for start in starts:\n stack.append(start)\n visited.add((start, ))\n l = 1\n while stack != [] and l < len(word):\n x, y = stack[-1]\n for dxy in d:\n nx, ny = x + dxy[0], y + dxy[1]\n if 0 <= nx < m and 0 <= ny < n:\n if board[nx][ny] == word[l]:\n if (nx, ny) not in stack and tuple(stack) + ((nx, ny),) not in visited:\n stack.append((nx, ny))\n visited.add(tuple(stack))\n l += 1\n if l == len(word):\n return True\n break\n else:\n stack.pop()\n l -= 1\n else:\n return False", "slug": "word-search-ii", "post_title": "python3 solution || 99% more faster || 39 ms", "user": "vimla_kushwaha", "upvotes": 3, "views": 301, "problem_title": "word search ii", "number": 212, "acceptance": 0.368, "difficulty": "Hard", "__index_level_0__": 3627, "question": "Given an m x n board of characters and a list of strings words, return all words on the board.\nEach 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 Example 1:\nInput: board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\nOutput: [\"eat\",\"oath\"]\nExample 2:\nInput: board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\nOutput: []\n Constraints:\nm == board.length\nn == board[i].length\n1 <= m, n <= 12\nboard[i][j] is a lowercase English letter.\n1 <= words.length <= 3 * 104\n1 <= words[i].length <= 10\nwords[i] consists of lowercase English letters.\nAll the strings of words are unique." }, { "post_href": "https://leetcode.com/problems/house-robber-ii/discuss/2158878/Do-house-robber-twice", "python_solutions": "class Solution:\n def rob(self, nums: List[int]) -> int:\n \n if len(nums) == 1:\n return nums[0]\n \n dp = {}\n def getResult(a,i):\n if i>=len(a):\n return 0\n if i in dp:\n return dp[i]\n \n sum = 0\n if i str:\n \n end = 0\n \n # if the string itself is a palindrome return it\n if(s == s[::-1]):\n return s\n \n # Otherwise find the end index of the longest palindrome that starts\n # from the first character of the string\n \n for i in range(len(s)+1):\n if(s[:i]==s[:i][::-1]):\n end=i-1\n \n # return the string with the remaining characters other than\n # the palindrome reversed and added at the beginning\n \n return (s[end+1:][::-1])+s", "slug": "shortest-palindrome", "post_title": "No DP; No DS; Intuitive with comments || Python", "user": "a-myth", "upvotes": 2, "views": 124, "problem_title": "shortest palindrome", "number": 214, "acceptance": 0.322, "difficulty": "Hard", "__index_level_0__": 3694, "question": "You are given a string s. You can convert s to a\npalindrome\nby adding characters in front of it.\nReturn the shortest palindrome you can find by performing this transformation.\n Example 1:\nInput: s = \"aacecaaa\"\nOutput: \"aaacecaaa\"\nExample 2:\nInput: s = \"abcd\"\nOutput: \"dcbabcd\"\n Constraints:\n0 <= s.length <= 5 * 104\ns consists of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/2180509/Python-Easy-O(logn)-Space-approach-or-One-liner", "python_solutions": "class Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int: \n n = len(nums)\n \n def partition(l, r, pivot):\n pivot_elem=nums[pivot]\n nums[r],nums[pivot]=nums[pivot],nums[r]\n \n index=l\n for i in range(l, r):\n if nums[i]pivot_index:\n return quick_select(pivot_index+1, r, kth_index)\n else:\n return quick_select(l,pivot_index-1, kth_index)\n \n return quick_select(0, n - 1, n - k)", "slug": "kth-largest-element-in-an-array", "post_title": "Python Easy O(logn) Space approach | One liner", "user": "constantine786", "upvotes": 24, "views": 3300, "problem_title": "kth largest element in an array", "number": 215, "acceptance": 0.6579999999999999, "difficulty": "Medium", "__index_level_0__": 3711, "question": "Given an integer array nums and an integer k, return the kth largest element in the array.\nNote that it is the kth largest element in the sorted order, not the kth distinct element.\nCan you solve it without sorting?\n Example 1:\nInput: nums = [3,2,1,5,6,4], k = 2\nOutput: 5\nExample 2:\nInput: nums = [3,2,3,1,2,4,5,5,6], k = 4\nOutput: 4\n Constraints:\n1 <= k <= nums.length <= 105\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/combination-sum-iii/discuss/1312030/Elegant-Python-Iterative-or-Recursive", "python_solutions": "class Solution:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n \n current_combination, combinations = [], []\n integer, combination_sum = 1, 0\n queue = [(integer, current_combination, combination_sum)]\n while queue:\n integer, current_combination, combination_sum = queue.pop()\n if combination_sum == n and len(current_combination) == k: combinations.append(current_combination)\n else:\n for i in range(integer, 10):\n if combination_sum + i > n: break\n queue.append((i+1, current_combination + [i], combination_sum + i))\n \n return combinations", "slug": "combination-sum-iii", "post_title": "Elegant Python Iterative | Recursive", "user": "soma28", "upvotes": 5, "views": 175, "problem_title": "combination sum iii", "number": 216, "acceptance": 0.672, "difficulty": "Medium", "__index_level_0__": 3761, "question": "Find all valid combinations of k numbers that sum up to n such that the following conditions are true:\nOnly numbers 1 through 9 are used.\nEach number is used at most once.\nReturn a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.\n Example 1:\nInput: k = 3, n = 7\nOutput: [[1,2,4]]\nExplanation:\n1 + 2 + 4 = 7\nThere are no other valid combinations.\nExample 2:\nInput: k = 3, n = 9\nOutput: [[1,2,6],[1,3,5],[2,3,4]]\nExplanation:\n1 + 2 + 6 = 9\n1 + 3 + 5 = 9\n2 + 3 + 4 = 9\nThere are no other valid combinations.\nExample 3:\nInput: k = 4, n = 1\nOutput: []\nExplanation: There are no valid combinations.\nUsing 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.\n Constraints:\n2 <= k <= 9\n1 <= n <= 60" }, { "post_href": "https://leetcode.com/problems/contains-duplicate/discuss/1496268/Python-98-speed-faster", "python_solutions": "class Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n return len(set(nums)) != len(nums)", "slug": "contains-duplicate", "post_title": "Python // 98% speed faster", "user": "fabioo29", "upvotes": 11, "views": 1900, "problem_title": "contains duplicate", "number": 217, "acceptance": 0.613, "difficulty": "Easy", "__index_level_0__": 3811, "question": "Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.\n Example 1:\nInput: nums = [1,2,3,1]\nOutput: true\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: false\nExample 3:\nInput: nums = [1,1,1,3,3,4,3,2,4,2]\nOutput: true\n Constraints:\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/the-skyline-problem/discuss/2640697/Python-oror-Easily-Understood-oror-Faster-oror-with-maximum-heap-explained", "python_solutions": "class Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n # for the same x, (x, -H) should be in front of (x, 0)\n # For Example 2, we should process (2, -3) then (2, 0), as there's no height change\n x_height_right_tuples = sorted([(L, -H, R) for L, R, H in buildings] + [(R, 0, \"doesn't matter\") for _, R, _ in buildings]) \n # (0, float('inf')) is always in max_heap, so max_heap[0] is always valid\n result, max_heap = [[0, 0]], [(0, float('inf'))]\n for x, negative_height, R in x_height_right_tuples:\n while x >= max_heap[0][1]:\n # reduce max height up to date, i.e. only consider max height in the right side of line x\n heapq.heappop(max_heap)\n if negative_height:\n # Consider each height, as it may be the potential max height\n heapq.heappush(max_heap, (negative_height, R))\n curr_max_height = -max_heap[0][0]\n if result[-1][1] != curr_max_height:\n result.append([x, curr_max_height])\n return result[1:]", "slug": "the-skyline-problem", "post_title": "\ud83d\udd25 Python || Easily Understood \u2705 || Faster || with maximum heap explained", "user": "rajukommula", "upvotes": 12, "views": 1100, "problem_title": "the skyline problem", "number": 218, "acceptance": 0.416, "difficulty": "Hard", "__index_level_0__": 3856, "question": "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.\nThe geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:\nlefti is the x coordinate of the left edge of the ith building.\nrighti is the x coordinate of the right edge of the ith building.\nheighti is the height of the ith building.\nYou may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.\nThe 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.\nNote: 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 Example 1:\nInput: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\nOutput: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\nExplanation:\nFigure A shows the buildings of the input.\nFigure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\nExample 2:\nInput: buildings = [[0,2,3],[2,5,3]]\nOutput: [[0,3],[5,0]]\n Constraints:\n1 <= buildings.length <= 104\n0 <= lefti < righti <= 231 - 1\n1 <= heighti <= 231 - 1\nbuildings is sorted by lefti in non-decreasing order." }, { "post_href": "https://leetcode.com/problems/contains-duplicate-ii/discuss/2463150/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Javascript-Python3-(Using-HashSet)", "python_solutions": "class Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n # Create hset for storing previous of k elements...\n hset = {}\n # Traverse for all elements of the given array in a for loop...\n for idx in range(len(nums)):\n # If duplicate element is present at distance less than equal to k, return true...\n if nums[idx] in hset and abs(idx - hset[nums[idx]]) <= k:\n return True\n hset[nums[idx]] = idx\n # If no duplicate element is found then return false...\n return False", "slug": "contains-duplicate-ii", "post_title": "Very Easy || 100% || Fully Explained || Java, C++, Python, Javascript, Python3 (Using HashSet)", "user": "PratikSen07", "upvotes": 45, "views": 3400, "problem_title": "contains duplicate ii", "number": 219, "acceptance": 0.423, "difficulty": "Easy", "__index_level_0__": 3870, "question": "Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.\n Example 1:\nInput: nums = [1,2,3,1], k = 3\nOutput: true\nExample 2:\nInput: nums = [1,0,1,1], k = 1\nOutput: true\nExample 3:\nInput: nums = [1,2,3,1,2,3], k = 2\nOutput: false\n Constraints:\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109\n0 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/contains-duplicate-iii/discuss/825267/Python3-summarizing-Contain-Duplicates-I-II-III", "python_solutions": "class Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n seen = set()\n for x in nums:\n if x in seen: return True \n seen.add(x)\n return False", "slug": "contains-duplicate-iii", "post_title": "[Python3] summarizing Contain Duplicates I, II, III", "user": "ye15", "upvotes": 22, "views": 689, "problem_title": "contains duplicate iii", "number": 220, "acceptance": 0.22, "difficulty": "Hard", "__index_level_0__": 3921, "question": "You are given an integer array nums and two integers indexDiff and valueDiff.\nFind a pair of indices (i, j) such that:\ni != j,\nabs(i - j) <= indexDiff.\nabs(nums[i] - nums[j]) <= valueDiff, and\nReturn true if such pair exists or false otherwise.\n Example 1:\nInput: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0\nOutput: true\nExplanation: We can choose (i, j) = (0, 3).\nWe satisfy the three conditions:\ni != j --> 0 != 3\nabs(i - j) <= indexDiff --> abs(0 - 3) <= 3\nabs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0\nExample 2:\nInput: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3\nOutput: false\nExplanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.\n Constraints:\n2 <= nums.length <= 105\n-109 <= nums[i] <= 109\n1 <= indexDiff <= nums.length\n0 <= valueDiff <= 109" }, { "post_href": "https://leetcode.com/problems/maximal-square/discuss/1632285/Python-1D-Array-DP-Optimisation-Process-Explained", "python_solutions": "class Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n result = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n curr = 0 # current length of the square at (i, j)\n flag = True # indicates if there still exists a valid square\n while flag:\n for k in range(curr+1):\n # check outer border of elements for '1's.\n \"\"\"\n eg curr = 2, ie a valid 2x2 square exists\n 'O' is valid, check 'X':\n X X X\n X O O\n X O O\n \"\"\"\n if i < curr or j < curr or \\\n matrix[i-curr][j-k] == '0' or \\\n matrix[i-k][j-curr] == '0':\n flag = False\n break\n curr += flag\n if curr > result: # new maximum length of square obtained\n result = curr\n return result*result # area = length x length", "slug": "maximal-square", "post_title": "[Python] 1D-Array DP - Optimisation Process Explained", "user": "zayne-siew", "upvotes": 9, "views": 610, "problem_title": "maximal square", "number": 221, "acceptance": 0.446, "difficulty": "Medium", "__index_level_0__": 3932, "question": "Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.\n Example 1:\nInput: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\nOutput: 4\nExample 2:\nInput: matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\nOutput: 1\nExample 3:\nInput: matrix = [[\"0\"]]\nOutput: 0\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 300\nmatrix[i][j] is '0' or '1'." }, { "post_href": "https://leetcode.com/problems/count-complete-tree-nodes/discuss/701577/PythonPython3-Count-Complete-Tree-Nodes", "python_solutions": "class Solution:\n def countNodes(self, root: TreeNode) -> int:\n if not root: return 0\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)", "slug": "count-complete-tree-nodes", "post_title": "[Python/Python3] Count Complete Tree Nodes", "user": "newborncoder", "upvotes": 4, "views": 336, "problem_title": "count complete tree nodes", "number": 222, "acceptance": 0.598, "difficulty": "Medium", "__index_level_0__": 3976, "question": "Given the root of a complete binary tree, return the number of the nodes in the tree.\nAccording to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\nDesign an algorithm that runs in less than O(n) time complexity.\n Example 1:\nInput: root = [1,2,3,4,5,6]\nOutput: 6\nExample 2:\nInput: root = []\nOutput: 0\nExample 3:\nInput: root = [1]\nOutput: 1\n Constraints:\nThe number of nodes in the tree is in the range [0, 5 * 104].\n0 <= Node.val <= 5 * 104\nThe tree is guaranteed to be complete." }, { "post_href": "https://leetcode.com/problems/rectangle-area/discuss/2822409/Fastest-python-solution", "python_solutions": "class Solution:\n def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n coxl=max(ax1,bx1)\n coxr=min(ax2,bx2)\n coyl=max(ay1,by1)\n coyr=min(ay2,by2)\n dx=coxr-coxl\n dy=coyr-coyl\n comm=0\n if dx>0 and dy>0:\n comm=dx*dy\n a=abs(ax2-ax1)*abs(ay2-ay1)\n b=abs(bx2-bx1)*abs(by2-by1)\n area=a+b-comm\n return area", "slug": "rectangle-area", "post_title": "Fastest python solution", "user": "shubham_1307", "upvotes": 9, "views": 569, "problem_title": "rectangle area", "number": 223, "acceptance": 0.449, "difficulty": "Medium", "__index_level_0__": 4004, "question": "Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.\nThe first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).\nThe second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).\n Example 1:\nInput: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\nOutput: 45\nExample 2:\nInput: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\nOutput: 16\n Constraints:\n-104 <= ax1 <= ax2 <= 104\n-104 <= ay1 <= ay2 <= 104\n-104 <= bx1 <= bx2 <= 104\n-104 <= by1 <= by2 <= 104" }, { "post_href": "https://leetcode.com/problems/basic-calculator/discuss/2832718/Python-(Faster-than-98)-or-O(N)-stack-solution", "python_solutions": "class Solution:\n def calculate(self, s: str) -> int:\n output, curr, sign, stack = 0, 0, 1, []\n for c in s:\n if c.isdigit():\n curr = (curr * 10) + int(c)\n \n elif c in '+-':\n output += curr * sign\n curr = 0\n if c == '+':\n sign = 1\n\n else:\n sign = -1\n \n elif c == '(':\n stack.append(output)\n stack.append(sign)\n sign = 1\n output = 0\n \n elif c == ')':\n output += curr * sign\n output *= stack.pop() #sign\n output += stack.pop() #last output\n curr = 0\n\n return output + (curr * sign)", "slug": "basic-calculator", "post_title": "Python (Faster than 98%) | O(N) stack solution", "user": "KevinJM17", "upvotes": 2, "views": 81, "problem_title": "basic calculator", "number": 224, "acceptance": 0.423, "difficulty": "Hard", "__index_level_0__": 4054, "question": "Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n Example 1:\nInput: s = \"1 + 1\"\nOutput: 2\nExample 2:\nInput: s = \" 2-1 + 2 \"\nOutput: 3\nExample 3:\nInput: s = \"(1+(4+5+2)-3)+(6+8)\"\nOutput: 23\n Constraints:\n1 <= s.length <= 3 * 105\ns consists of digits, '+', '-', '(', ')', and ' '.\ns represents a valid expression.\n'+' is not used as a unary operation (i.e., \"+1\" and \"+(2 + 3)\" is invalid).\n'-' could be used as a unary operation (i.e., \"-1\" and \"-(2 + 3)\" is valid).\nThere will be no two consecutive operators in the input.\nEvery number and running calculation will fit in a signed 32-bit integer." }, { "post_href": "https://leetcode.com/problems/invert-binary-tree/discuss/2463600/Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-oror-Recursive-and-Iterative", "python_solutions": "class Solution(object):\n def invertTree(self, root):\n # Base case...\n if root == None:\n return root\n # swapping process...\n root.left, root.right = root.right, root.left\n # Call the function recursively for the left subtree...\n self.invertTree(root.left)\n # Call the function recursively for the right subtree...\n self.invertTree(root.right)\n return root # Return the root...", "slug": "invert-binary-tree", "post_title": "Easy || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 || Recursive & Iterative", "user": "PratikSen07", "upvotes": 54, "views": 3300, "problem_title": "invert binary tree", "number": 226, "acceptance": 0.7340000000000001, "difficulty": "Easy", "__index_level_0__": 4091, "question": "Given the root of a binary tree, invert the tree, and return its root.\n Example 1:\nInput: root = [4,2,7,1,3,6,9]\nOutput: [4,7,2,9,6,3,1]\nExample 2:\nInput: root = [2,1,3]\nOutput: [2,3,1]\nExample 3:\nInput: root = []\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 100].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/basic-calculator-ii/discuss/1209116/python-without-any-stack-and-beat-99", "python_solutions": "class Solution:\n def calculate(self, s: str) -> int:\n curr_res = 0\n res = 0\n num = 0\n op = \"+\" # keep the last operator we have seen\n \n\t\t# append a \"+\" sign at the end because we can catch the very last item\n for ch in s + \"+\":\n if ch.isdigit():\n num = 10 * num + int(ch)\n\n # if we have a symbol, we would start to calculate the previous part.\n # note that we have to catch the last chracter since there will no sign afterwards to trigger calculation\n if ch in (\"+\", \"-\", \"*\", \"/\"):\n if op == \"+\":\n curr_res += num\n elif op == \"-\":\n curr_res -= num\n elif op == \"*\":\n curr_res *= num\n elif op == \"/\":\n # in python if there is a negative number, we should alway use int() instead of //\n curr_res = int(curr_res / num)\n \n # if the chracter is \"+\" or \"-\", we do not need to worry about\n # the priority so that we can add the curr_res to the eventual res\n if ch in (\"+\", \"-\"):\n res += curr_res\n curr_res = 0\n \n op = ch\n num = 0\n \n return res", "slug": "basic-calculator-ii", "post_title": "python - without any stack and beat 99%", "user": "ZAbird", "upvotes": 14, "views": 1300, "problem_title": "basic calculator ii", "number": 227, "acceptance": 0.423, "difficulty": "Medium", "__index_level_0__": 4123, "question": "Given a string s which represents an expression, evaluate this expression and return its value. \nThe integer division should truncate toward zero.\nYou may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].\nNote: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n Example 1:\nInput: s = \"3+2*2\"\nOutput: 7\nExample 2:\nInput: s = \" 3/2 \"\nOutput: 1\nExample 3:\nInput: s = \" 3+5 / 2 \"\nOutput: 5\n Constraints:\n1 <= s.length <= 3 * 105\ns consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.\ns represents a valid expression.\nAll the integers in the expression are non-negative integers in the range [0, 231 - 1].\nThe answer is guaranteed to fit in a 32-bit integer." }, { "post_href": "https://leetcode.com/problems/summary-ranges/discuss/1805476/Python-Simple-Python-Solution-Using-Iterative-Approach-oror-O(n)", "python_solutions": "class Solution:\n\tdef summaryRanges(self, nums: List[int]) -> List[str]:\n\n\t\tstart = 0\n\t\tend = 0\n\n\t\tresult = []\n\n\t\twhile start < len(nums) and end'+str(nums[end]))\n\t\t\t\t\tstart = end + 1\n\t\t\t\t\tend = end + 1\n\n\t\treturn result", "slug": "summary-ranges", "post_title": "[ Python ] \u2714\u2714 Simple Python Solution Using Iterative Approach || O(n) \ud83d\udd25\u270c", "user": "ASHOK_KUMAR_MEGHVANSHI", "upvotes": 28, "views": 2300, "problem_title": "summary ranges", "number": 228, "acceptance": 0.469, "difficulty": "Easy", "__index_level_0__": 4149, "question": "You are given a sorted unique integer array nums.\nA range [a,b] is the set of all integers from a to b (inclusive).\nReturn the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.\nEach range [a,b] in the list should be output as:\n\"a->b\" if a != b\n\"a\" if a == b\n Example 1:\nInput: nums = [0,1,2,4,5,7]\nOutput: [\"0->2\",\"4->5\",\"7\"]\nExplanation: The ranges are:\n[0,2] --> \"0->2\"\n[4,5] --> \"4->5\"\n[7,7] --> \"7\"\nExample 2:\nInput: nums = [0,2,3,4,6,8,9]\nOutput: [\"0\",\"2->4\",\"6\",\"8->9\"]\nExplanation: The ranges are:\n[0,0] --> \"0\"\n[2,4] --> \"2->4\"\n[6,6] --> \"6\"\n[8,9] --> \"8->9\"\n Constraints:\n0 <= nums.length <= 20\n-231 <= nums[i] <= 231 - 1\nAll the values of nums are unique.\nnums is sorted in ascending order." }, { "post_href": "https://leetcode.com/problems/majority-element-ii/discuss/1483430/Python-95-faster-in-speed", "python_solutions": "class Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n return [x for x in set(nums) if nums.count(x) > len(nums)/3]", "slug": "majority-element-ii", "post_title": "Python // 95% faster in speed", "user": "fabioo29", "upvotes": 3, "views": 394, "problem_title": "majority element ii", "number": 229, "acceptance": 0.442, "difficulty": "Medium", "__index_level_0__": 4197, "question": "Given an integer array of size n, find all elements that appear more than \u230a n/3 \u230b times.\n Example 1:\nInput: nums = [3,2,3]\nOutput: [3]\nExample 2:\nInput: nums = [1]\nOutput: [1]\nExample 3:\nInput: nums = [1,2]\nOutput: [1,2]\n Constraints:\n1 <= nums.length <= 5 * 104\n-109 <= nums[i] <= 109\n Follow up: Could you solve the problem in linear time and in O(1) space?" }, { "post_href": "https://leetcode.com/problems/kth-smallest-element-in-a-bst/discuss/1960632/Inorder-%2B-Heap-In-Python", "python_solutions": "class Solution:\n import heapq\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n \n heap = []\n def inorder(r):\n if r:\n inorder(r.left)\n heapq.heappush(heap,-(r.val))\n if len(heap) > k:\n heapq.heappop(heap)\n inorder(r.right)\n inorder(root)\n \n return -heapq.heappop(heap)", "slug": "kth-smallest-element-in-a-bst", "post_title": "Inorder + Heap In Python", "user": "gamitejpratapsingh998", "upvotes": 2, "views": 83, "problem_title": "kth smallest element in a bst", "number": 230, "acceptance": 0.695, "difficulty": "Medium", "__index_level_0__": 4248, "question": "Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.\n Example 1:\nInput: root = [3,1,4,null,2], k = 1\nOutput: 1\nExample 2:\nInput: root = [5,3,6,2,4,null,null,1], k = 3\nOutput: 3\n Constraints:\nThe number of nodes in the tree is n.\n1 <= k <= n <= 104\n0 <= Node.val <= 104\n Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?" }, { "post_href": "https://leetcode.com/problems/power-of-two/discuss/948641/Python-O(1)-Solution", "python_solutions": "class Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n return n>0 and n&(n-1)==0", "slug": "power-of-two", "post_title": "Python O(1) Solution", "user": "lokeshsenthilkumar", "upvotes": 37, "views": 2400, "problem_title": "power of two", "number": 231, "acceptance": 0.457, "difficulty": "Easy", "__index_level_0__": 4273, "question": "Given an integer n, return true if it is a power of two. Otherwise, return false.\nAn integer n is a power of two, if there exists an integer x such that n == 2x.\n Example 1:\nInput: n = 1\nOutput: true\nExplanation: 20 = 1\nExample 2:\nInput: n = 16\nOutput: true\nExplanation: 24 = 16\nExample 3:\nInput: n = 3\nOutput: false\n Constraints:\n-231 <= n <= 231 - 1\n Follow up: Could you solve it without loops/recursion?" }, { "post_href": "https://leetcode.com/problems/number-of-digit-one/discuss/1655517/Python3-O(9)-Straight-Math-Solution", "python_solutions": "class Solution:\n def countDigitOne(self, n: int) -> int:\n \n #O(logn) mathematical solution\n #intervals of new 1s: 0-9, 10-99, 100-999, 1000,9999... \n #each interval yields 1,10,100,etc. new '1's respectively\n\t\t#first and foremost, we want to check how many of each interval repeats \n #conditions for FULL yield when curr%upper bound+1: 1 <=, 19 <=, 199 <=...\n #conditions for PARTIAL yielf when curr%upper bound+1: None, 10 <= < 19, 100 <= < 199, 1000 <= < 1999 ... \n \n ans = 0\n for i in range(len(str(n))):\n curr = 10**(i+1)\n hi,lo = int('1'+'9'*i), int('1'+'0'*i)\n ans += (n//curr) * 10**i\n if (pot:=n%curr) >= hi: ans += 10**i\n elif lo <= pot < hi: \n ans += pot - lo + 1\n return ans", "slug": "number-of-digit-one", "post_title": "Python3 O(9) Straight Math Solution", "user": "terrysu64", "upvotes": 1, "views": 341, "problem_title": "number of digit one", "number": 233, "acceptance": 0.342, "difficulty": "Hard", "__index_level_0__": 4333, "question": "Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.\n Example 1:\nInput: n = 13\nOutput: 6\nExample 2:\nInput: n = 0\nOutput: 0\n Constraints:\n0 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/palindrome-linked-list/discuss/2466200/Python-O(N)O(1)", "python_solutions": "class Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n def reverse(node):\n prev = None\n while node:\n next_node = node.next\n node.next = prev \n prev, node = node, next_node\n \n return prev\n \n slow = head\n fast = head.next\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n n1 = head\n n2 = reverse(slow.next)\n while n2:\n if n1.val != n2.val:\n return False\n \n n1 = n1.next\n n2 = n2.next\n \n return True", "slug": "palindrome-linked-list", "post_title": "Python, O(N)/O(1)", "user": "blue_sky5", "upvotes": 7, "views": 839, "problem_title": "palindrome linked list", "number": 234, "acceptance": 0.496, "difficulty": "Easy", "__index_level_0__": 4344, "question": "Given the head of a singly linked list, return true if it is a\npalindrome\nor false otherwise.\n Example 1:\nInput: head = [1,2,2,1]\nOutput: true\nExample 2:\nInput: head = [1,2]\nOutput: false\n Constraints:\nThe number of nodes in the list is in the range [1, 105].\n0 <= Node.val <= 9\n Follow up: Could you do it in O(n) time and O(1) space?" }, { "post_href": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/1394823/Explained-Easy-Iterative-Python-Solution", "python_solutions": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n \n while True:\n if root.val > p.val and root.val > q.val:\n root = root.left\n elif root.val < p.val and root.val < q.val:\n root = root.right\n else:\n return root", "slug": "lowest-common-ancestor-of-a-binary-search-tree", "post_title": "Explained Easy Iterative Python Solution", "user": "sevdariklejdi", "upvotes": 55, "views": 2000, "problem_title": "lowest common ancestor of a binary search tree", "number": 235, "acceptance": 0.604, "difficulty": "Medium", "__index_level_0__": 4377, "question": "Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.\nAccording to the definition of LCA on Wikipedia: \u201cThe lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).\u201d\n Example 1:\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\nOutput: 6\nExplanation: The LCA of nodes 2 and 8 is 6.\nExample 2:\nInput: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\nOutput: 2\nExplanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\nExample 3:\nInput: root = [2,1], p = 2, q = 1\nOutput: 2\n Constraints:\nThe number of nodes in the tree is in the range [2, 105].\n-109 <= Node.val <= 109\nAll Node.val are unique.\np != q\np and q will exist in the BST." }, { "post_href": "https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/2539410/python3-simple-Solution", "python_solutions": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n if root==None or root.val==p.val or root.val==q.val:\n return root\n left=self.lowestCommonAncestor(root.left,p,q)\n right=self.lowestCommonAncestor(root.right,p,q)\n if left!=None and right!=None:\n return root\n elif left!=None:\n return left\n else:\n return right", "slug": "lowest-common-ancestor-of-a-binary-tree", "post_title": "python3 simple Solution", "user": "pranjalmishra334", "upvotes": 4, "views": 251, "problem_title": "lowest common ancestor of a binary tree", "number": 236, "acceptance": 0.581, "difficulty": "Medium", "__index_level_0__": 4399, "question": "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\nAccording to the definition of LCA on Wikipedia: \u201cThe lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).\u201d\n Example 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\nOutput: 3\nExplanation: The LCA of nodes 5 and 1 is 3.\nExample 2:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\nOutput: 5\nExplanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\nExample 3:\nInput: root = [1,2], p = 1, q = 2\nOutput: 1\n Constraints:\nThe number of nodes in the tree is in the range [2, 105].\n-109 <= Node.val <= 109\nAll Node.val are unique.\np != q\np and q will exist in the tree." }, { "post_href": "https://leetcode.com/problems/delete-node-in-a-linked-list/discuss/1454184/95.96-faster-and-Simpler-solution-with-Explanation.", "python_solutions": "class Solution:\n def deleteNode(self, node):\n\n nextNode = node.next\n node.val = nextNode.val\n node.next = nextNode.next", "slug": "delete-node-in-a-linked-list", "post_title": "95.96% faster and Simpler solution with Explanation.", "user": "AmrinderKaur1", "upvotes": 6, "views": 870, "problem_title": "delete node in a linked list", "number": 237, "acceptance": 0.753, "difficulty": "Medium", "__index_level_0__": 4427, "question": "There is a singly-linked list head and we want to delete a node node in it.\nYou are given the node to be deleted node. You will not be given access to the first node of head.\nAll the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.\nDelete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:\nThe value of the given node should not exist in the linked list.\nThe number of nodes in the linked list should decrease by one.\nAll the values before node should be in the same order.\nAll the values after node should be in the same order.\nCustom testing:\nFor the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.\nWe will build the linked list and pass the node to your function.\nThe output will be the entire list after calling your function.\n Example 1:\nInput: head = [4,5,1,9], node = 5\nOutput: [4,1,9]\nExplanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.\nExample 2:\nInput: head = [4,5,1,9], node = 1\nOutput: [4,5,9]\nExplanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.\n Constraints:\nThe number of the nodes in the given list is in the range [2, 1000].\n-1000 <= Node.val <= 1000\nThe value of each node in the list is unique.\nThe node to be deleted is in the list and is not a tail node." }, { "post_href": "https://leetcode.com/problems/product-of-array-except-self/discuss/744951/Product-of-array-except-self-Python3-Solution-with-a-Detailed-Explanation", "python_solutions": "class Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n leftProducts = [0]*len(nums) # initialize left array \n rightProducts = [0]*len(nums) # initialize right array\n \n leftProducts[0] = 1 # the left most is 1\n rightProducts[-1] = 1 # the right most is 1\n res = [] # output\n \n for i in range(1, len(nums)):\n leftProducts[i] = leftProducts[i-1]*nums[i-1]\n rightProducts[len(nums) - i - 1] = rightProducts[len(nums) - i]*nums[len(nums) - i]\n \n for i in range(len(nums)):\n res.append(leftProducts[i]*rightProducts[i])\n \n return res", "slug": "product-of-array-except-self", "post_title": "Product of array except self - Python3 Solution with a Detailed Explanation", "user": "peyman_np", "upvotes": 12, "views": 1200, "problem_title": "product of array except self", "number": 238, "acceptance": 0.648, "difficulty": "Medium", "__index_level_0__": 4452, "question": "Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].\nThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\nYou must write an algorithm that runs in O(n) time and without using the division operation.\n Example 1:\nInput: nums = [1,2,3,4]\nOutput: [24,12,8,6]\nExample 2:\nInput: nums = [-1,1,0,-3,3]\nOutput: [0,0,9,0,0]\n Constraints:\n2 <= nums.length <= 105\n-30 <= nums[i] <= 30\nThe product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)" }, { "post_href": "https://leetcode.com/problems/sliding-window-maximum/discuss/1624633/Python-3-O(n)", "python_solutions": "class Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n res = []\n window = collections.deque()\n for i, num in enumerate(nums):\n while window and num >= nums[window[-1]]:\n window.pop()\n window.append(i)\n \n if i + 1 >= k:\n res.append(nums[window[0]])\n \n if i - window[0] + 1 == k:\n window.popleft()\n \n return res", "slug": "sliding-window-maximum", "post_title": "Python 3 O(n)", "user": "dereky4", "upvotes": 3, "views": 772, "problem_title": "sliding window maximum", "number": 239, "acceptance": 0.466, "difficulty": "Hard", "__index_level_0__": 4510, "question": "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.\nReturn the max sliding window.\n Example 1:\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [3,3,5,5,6,7]\nExplanation: \nWindow 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\nExample 2:\nInput: nums = [1], k = 1\nOutput: [1]\n Constraints:\n1 <= nums.length <= 105\n-104 <= nums[i] <= 104\n1 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/search-a-2d-matrix-ii/discuss/2324351/PYTHON-oror-EXPLAINED-oror", "python_solutions": "class Solution:\n def searchMatrix(self, mat: List[List[int]], target: int) -> bool:\n \n m=len(mat)\n n=len(mat[0])\n \n i=m-1\n j=0\n \n while i>=0 and j bool:\n tracker = collections.defaultdict(int)\n for x in s: tracker[x] += 1\n for x in t: tracker[x] -= 1\n return all(x == 0 for x in tracker.values())", "slug": "valid-anagram", "post_title": "Python 3 - O(n) - Faster than 98.39%, Memory usage less than 100%", "user": "mmbhatk", "upvotes": 69, "views": 18500, "problem_title": "valid anagram", "number": 242, "acceptance": 0.628, "difficulty": "Easy", "__index_level_0__": 4618, "question": "Given two strings s and t, return true if t is an anagram of s, and false otherwise.\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n Example 1:\nInput: s = \"anagram\", t = \"nagaram\"\nOutput: true\nExample 2:\nInput: s = \"rat\", t = \"car\"\nOutput: false\n Constraints:\n1 <= s.length, t.length <= 5 * 104\ns and t consist of lowercase English letters.\n Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?" }, { "post_href": "https://leetcode.com/problems/binary-tree-paths/discuss/484118/Python-3-(beats-~100)-(nine-lines)-(DFS)", "python_solutions": "class Solution:\n def binaryTreePaths(self, R: TreeNode) -> List[str]:\n A, P = [], []\n def dfs(N):\n if N == None: return\n P.append(N.val)\n if (N.left,N.right) == (None,None): A.append('->'.join(map(str,P)))\n else: dfs(N.left), dfs(N.right)\n P.pop()\n dfs(R)\n return A\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "binary-tree-paths", "post_title": "Python 3 (beats ~100%) (nine lines) (DFS)", "user": "junaidmansuri", "upvotes": 7, "views": 1100, "problem_title": "binary tree paths", "number": 257, "acceptance": 0.607, "difficulty": "Easy", "__index_level_0__": 4672, "question": "Given the root of a binary tree, return all root-to-leaf paths in any order.\nA leaf is a node with no children.\n Example 1:\nInput: root = [1,2,3,null,5]\nOutput: [\"1->2->5\",\"1->3\"]\nExample 2:\nInput: root = [1]\nOutput: [\"1\"]\n Constraints:\nThe number of nodes in the tree is in the range [1, 100].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/add-digits/discuss/2368005/Very-Easy-100-(Fully-Explained)(Java-C%2B%2B-Python-JS-C-Python3)", "python_solutions": "class Solution(object):\n def addDigits(self, num):\n while num > 9:\n num = num % 10 + num // 10\n return num", "slug": "add-digits", "post_title": "Very Easy 100% (Fully Explained)(Java, C++, Python, JS, C, Python3)", "user": "PratikSen07", "upvotes": 13, "views": 484, "problem_title": "add digits", "number": 258, "acceptance": 0.635, "difficulty": "Easy", "__index_level_0__": 4696, "question": "Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.\n Example 1:\nInput: num = 38\nOutput: 2\nExplanation: The process is\n38 --> 3 + 8 --> 11\n11 --> 1 + 1 --> 2 \nSince 2 has only one digit, return it.\nExample 2:\nInput: num = 0\nOutput: 0\n Constraints:\n0 <= num <= 231 - 1\n Follow up: Could you do it without any loop/recursion in O(1) runtime?" }, { "post_href": "https://leetcode.com/problems/single-number-iii/discuss/2828366/brute-force-with-dictnory", "python_solutions": "class Solution:\n\n def singleNumber(self, nums: List[int]) -> List[int]:\n dc=defaultdict(lambda:0)\n for a in(nums):\n dc[a]+=1\n ans=[]\n for a in dc:\n if(dc[a]==1):\n ans.append(a)\n return ans", "slug": "single-number-iii", "post_title": "brute force with dictnory", "user": "droj", "upvotes": 5, "views": 30, "problem_title": "single number iii", "number": 260, "acceptance": 0.675, "difficulty": "Medium", "__index_level_0__": 4754, "question": "Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.\nYou must write an algorithm that runs in linear runtime complexity and uses only constant extra space.\n Example 1:\nInput: nums = [1,2,1,3,2,5]\nOutput: [3,5]\nExplanation: [5, 3] is also a valid answer.\nExample 2:\nInput: nums = [-1,0]\nOutput: [-1,0]\nExample 3:\nInput: nums = [0,1]\nOutput: [1,0]\n Constraints:\n2 <= nums.length <= 3 * 104\n-231 <= nums[i] <= 231 - 1\nEach integer in nums will appear twice, only two integers will appear once." }, { "post_href": "https://leetcode.com/problems/ugly-number/discuss/336227/Solution-in-Python-3-(beats-~99)-(five-lines)", "python_solutions": "class Solution:\n def isUgly(self, num: int) -> bool:\n if num == 0: return False\n while num % 5 == 0: num /= 5\n while num % 3 == 0: num /= 3\n while num % 2 == 0: num /= 2\n return num == 1\n\t\t\n\n- Junaid Mansuri", "slug": "ugly-number", "post_title": "Solution in Python 3 (beats ~99%) (five lines)", "user": "junaidmansuri", "upvotes": 18, "views": 2600, "problem_title": "ugly number", "number": 263, "acceptance": 0.426, "difficulty": "Easy", "__index_level_0__": 4785, "question": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\nGiven an integer n, return true if n is an ugly number.\n Example 1:\nInput: n = 6\nOutput: true\nExplanation: 6 = 2 \u00d7 3\nExample 2:\nInput: n = 1\nOutput: true\nExplanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\nExample 3:\nInput: n = 14\nOutput: false\nExplanation: 14 is not ugly since it includes the prime factor 7.\n Constraints:\n-231 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/ugly-number-ii/discuss/556314/Python-Simple-DP-9-Lines", "python_solutions": "class Solution:\n def nthUglyNumber(self, n: int) -> int:\n k = [0] * n\n t1 = t2 = t3 = 0\n k[0] = 1\n for i in range(1,n):\n k[i] = min(k[t1]*2,k[t2]*3,k[t3]*5)\n if(k[i] == k[t1]*2): t1 += 1\n if(k[i] == k[t2]*3): t2 += 1\n if(k[i] == k[t3]*5): t3 += 1\n return k[n-1]", "slug": "ugly-number-ii", "post_title": "[Python] Simple DP 9 Lines", "user": "mazz272727", "upvotes": 23, "views": 1100, "problem_title": "ugly number ii", "number": 264, "acceptance": 0.462, "difficulty": "Medium", "__index_level_0__": 4839, "question": "An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\nGiven an integer n, return the nth ugly number.\n Example 1:\nInput: n = 10\nOutput: 12\nExplanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.\nExample 2:\nInput: n = 1\nOutput: 1\nExplanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n Constraints:\n1 <= n <= 1690" }, { "post_href": "https://leetcode.com/problems/missing-number/discuss/2081185/Python-Easy-One-liners-with-Explanation", "python_solutions": "class Solution:\n def missingNumber(self, nums: List[int]) -> int:\n return (len(nums) * (len(nums) + 1))//2 - sum(nums)", "slug": "missing-number", "post_title": "\u2705 Python Easy One liners with Explanation", "user": "constantine786", "upvotes": 23, "views": 2000, "problem_title": "missing number", "number": 268, "acceptance": 0.617, "difficulty": "Easy", "__index_level_0__": 4860, "question": "Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.\n Example 1:\nInput: nums = [3,0,1]\nOutput: 2\nExplanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.\nExample 2:\nInput: nums = [0,1]\nOutput: 2\nExplanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.\nExample 3:\nInput: nums = [9,6,4,2,3,5,7,0,1]\nOutput: 8\nExplanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.\n Constraints:\nn == nums.length\n1 <= n <= 104\n0 <= nums[i] <= n\nAll the numbers of nums are unique.\n Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?" }, { "post_href": "https://leetcode.com/problems/integer-to-english-words/discuss/1990823/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022", "python_solutions": "class Solution:\n def numberToWords(self, num: int) -> str:\n mp = {1: \"One\", 11: \"Eleven\", 10: \"Ten\", \n 2: \"Two\", 12: \"Twelve\", 20: \"Twenty\", \n 3: \"Three\", 13: \"Thirteen\", 30: \"Thirty\", \n 4: \"Four\", 14: \"Fourteen\", 40: \"Forty\",\n 5: \"Five\", 15: \"Fifteen\", 50: \"Fifty\", \n 6: \"Six\", 16: \"Sixteen\", 60: \"Sixty\", \n 7: \"Seven\", 17: \"Seventeen\", 70: \"Seventy\", \n 8: \"Eight\", 18: \"Eighteen\", 80: \"Eighty\",\n 9: \"Nine\", 19: \"Nineteen\", 90: \"Ninety\"}\n \n def fn(n):\n \"\"\"Return English words of n (0-999) in array.\"\"\"\n if not n: return []\n elif n < 20: return [mp[n]]\n elif n < 100: return [mp[n//10*10]] + fn(n%10)\n else: return [mp[n//100], \"Hundred\"] + fn(n%100)\n \n ans = []\n for i, unit in zip((9, 6, 3, 0), (\"Billion\", \"Million\", \"Thousand\", \"\")): \n n, num = divmod(num, 10**i)\n ans.extend(fn(n))\n if n and unit: ans.append(unit)\n return \" \".join(ans) or \"Zero\"", "slug": "integer-to-english-words", "post_title": "[Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022", "user": "cucerdariancatalin", "upvotes": 8, "views": 677, "problem_title": "integer to english words", "number": 273, "acceptance": 0.299, "difficulty": "Hard", "__index_level_0__": 4927, "question": "Convert a non-negative integer num to its English words representation.\n Example 1:\nInput: num = 123\nOutput: \"One Hundred Twenty Three\"\nExample 2:\nInput: num = 12345\nOutput: \"Twelve Thousand Three Hundred Forty Five\"\nExample 3:\nInput: num = 1234567\nOutput: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n Constraints:\n0 <= num <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/h-index/discuss/785586/Python3-O(n)-without-sorting!", "python_solutions": "class Solution:\n def hIndex(self, citations: List[int]) -> int:\n tmp = [0] * (len(citations) + 1)\n\t\t\n for i in range(len(citations)):\n if citations[i] > len(citations):\n tmp[len(citations)] += 1\n else:\n tmp[citations[i]] += 1\n\n sum_ = 0\n for i in range(len(tmp) - 1, -1, -1):\n sum_ += tmp[i]\n if sum_ >= i:\n return i", "slug": "h-index", "post_title": "Python3 O(n) without sorting!", "user": "DebbieAlter", "upvotes": 5, "views": 489, "problem_title": "h index", "number": 274, "acceptance": 0.382, "difficulty": "Medium", "__index_level_0__": 4949, "question": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return the researcher's h-index.\nAccording to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.\n Example 1:\nInput: citations = [3,0,6,1,5]\nOutput: 3\nExplanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\nExample 2:\nInput: citations = [1,3,1]\nOutput: 1\n Constraints:\nn == citations.length\n1 <= n <= 5000\n0 <= citations[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/h-index-ii/discuss/2729382/Python3-Solution-or-Binary-Search-or-O(logn)", "python_solutions": "class Solution:\n def hIndex(self, A):\n n = len(A)\n l, r = 0, n - 1\n while l < r:\n m = (l + r + 1) // 2\n if A[m] > n - m: r = m - 1\n else: l = m\n return n - l - (A[l] < n - l)", "slug": "h-index-ii", "post_title": "\u2714 Python3 Solution | Binary Search | O(logn)", "user": "satyam2001", "upvotes": 2, "views": 109, "problem_title": "h index ii", "number": 275, "acceptance": 0.374, "difficulty": "Medium", "__index_level_0__": 4965, "question": "Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher's h-index.\nAccording to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.\nYou must write an algorithm that runs in logarithmic time.\n Example 1:\nInput: citations = [0,1,3,5,6]\nOutput: 3\nExplanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.\nSince the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.\nExample 2:\nInput: citations = [1,2,100]\nOutput: 2\n Constraints:\nn == citations.length\n1 <= n <= 105\n0 <= citations[i] <= 1000\ncitations is sorted in ascending order." }, { "post_href": "https://leetcode.com/problems/first-bad-version/discuss/2700688/Simple-Python-Solution-Using-Binary-Search", "python_solutions": "class Solution:\n def firstBadVersion(self, n: int) -> int:\n left = 1\n right = n\n result = 1\n \n while left<=right:\n mid = (left+right)//2\n if isBadVersion(mid) == False:\n left = mid+1\n else:\n right = mid-1\n result = mid\n \n return result", "slug": "first-bad-version", "post_title": "\u2714\ufe0f Simple Python Solution Using Binary Search \ud83d\udd25", "user": "pniraj657", "upvotes": 25, "views": 3400, "problem_title": "first bad version", "number": 278, "acceptance": 0.43, "difficulty": "Easy", "__index_level_0__": 4979, "question": "You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.\nSuppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.\nYou are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.\n Example 1:\nInput: n = 5, bad = 4\nOutput: 4\nExplanation:\ncall isBadVersion(3) -> false\ncall isBadVersion(5) -> true\ncall isBadVersion(4) -> true\nThen 4 is the first bad version.\nExample 2:\nInput: n = 1, bad = 1\nOutput: 1\n Constraints:\n1 <= bad <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/perfect-squares/discuss/376795/100-O(log-n)-Python3-Solution-Lagrange's-four-square-theorem", "python_solutions": "class Solution:\n def isSquare(self, n: int) -> bool:\n sq = int(math.sqrt(n))\n return sq*sq == n\n \n def numSquares(self, n: int) -> int:\n # Lagrange's four-square theorem\n if self.isSquare(n):\n return 1\n while (n & 3) == 0:\n n >>= 2\n if (n & 7) == 7:\n return 4\n sq = int(math.sqrt(n)) + 1\n for i in range(1,sq):\n if self.isSquare(n - i*i):\n return 2\n return 3", "slug": "perfect-squares", "post_title": "100% O(log n) Python3 Solution - Lagrange\u2019s four-square theorem", "user": "TCarmic", "upvotes": 12, "views": 1200, "problem_title": "perfect squares", "number": 279, "acceptance": 0.526, "difficulty": "Medium", "__index_level_0__": 4993, "question": "Given an integer n, return the least number of perfect square numbers that sum to n.\nA perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.\n Example 1:\nInput: n = 12\nOutput: 3\nExplanation: 12 = 4 + 4 + 4.\nExample 2:\nInput: n = 13\nOutput: 2\nExplanation: 13 = 4 + 9.\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/expression-add-operators/discuss/1031229/Python-Simple-heavily-commented-and-accepted-Recursive-Solution", "python_solutions": "class Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n exprs = []\n \n def recurse(idx, value, delta, exp):\n # base case here\n if idx == len(num):\n if value == target:\n exprs.append(\"\".join(exp))\n \n # the loop will create the current operand and recursively call\n # the next set of actions to be executed\n for i in range(idx, len(num)):\n # this is to avoid cases where the operand starts with a 0\n # we need to have a case with just the 0 but not something like\n # 05, so the condition will return early if we find such cases\n if num[idx] == '0' and i > idx:\n return\n \n curr = int(num[idx:i+1])\n curr_str = num[idx:i+1]\n \n # when we start the problem we dont have a preceding operator or operand\n if idx == 0:\n recurse(i+1, curr, curr, exp + [curr_str])\n else:\n # We need to do 3 different recursions for each operator\n # value stores the running value of the expression evaluated so far\n # the crux of the logic lies in how we use and pass delta\n # when the operation is '+' or '-' we don't care much about it and can just\n # add or subtract it from the value \n # when '*' is involved, we need to follow the precedence relation,\n # but we have already evaluated the previous operator. We know the\n # previous operation that was performed and how much it contributed to the value i.e., delta\n # so, we can revert that operation by subtracting delta from value and reapplying the multiplication\n recurse(i+1, value+curr, curr, exp + ['+', curr_str])\n recurse(i+1, value-curr, -curr, exp + ['-', curr_str])\n recurse(i+1, (value-delta)+curr*delta, curr*delta, exp + ['*', curr_str])\n \n recurse(0, 0, 0, [])\n return exprs", "slug": "expression-add-operators", "post_title": "[Python] Simple, heavily commented and accepted Recursive Solution", "user": "gokivego", "upvotes": 4, "views": 354, "problem_title": "expression add operators", "number": 282, "acceptance": 0.392, "difficulty": "Hard", "__index_level_0__": 5046, "question": "Given a string num that contains only digits and an integer target, return all possibilities to insert the binary operators '+', '-', and/or '*' between the digits of num so that the resultant expression evaluates to the target value.\nNote that operands in the returned expressions should not contain leading zeros.\n Example 1:\nInput: num = \"123\", target = 6\nOutput: [\"1*2*3\",\"1+2+3\"]\nExplanation: Both \"1*2*3\" and \"1+2+3\" evaluate to 6.\nExample 2:\nInput: num = \"232\", target = 8\nOutput: [\"2*3+2\",\"2+3*2\"]\nExplanation: Both \"2*3+2\" and \"2+3*2\" evaluate to 8.\nExample 3:\nInput: num = \"3456237490\", target = 9191\nOutput: []\nExplanation: There are no expressions that can be created from \"3456237490\" to evaluate to 9191.\n Constraints:\n1 <= num.length <= 10\nnum consists of only digits.\n-231 <= target <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/move-zeroes/discuss/404010/Python-easy-solution", "python_solutions": "class Solution(object):\n\tdef moveZeroes(self, nums):\n\t\ti=0\n\t\tn = len(nums)\n\t\twhile i int:\n slow = fast = ans = 0\n while True:\n slow = nums[slow]\n fast = nums[nums[fast]]\n if slow == fast:\n break\n while ans != slow:\n ans = nums[ans]\n slow = nums[slow]\n return ans", "slug": "find-the-duplicate-number", "post_title": "Proof of Floyd's cycle detection algorithm - Find the Duplicate Number", "user": "r0bertz", "upvotes": 20, "views": 2400, "problem_title": "find the duplicate number", "number": 287, "acceptance": 0.591, "difficulty": "Medium", "__index_level_0__": 5101, "question": "Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.\nThere is only one repeated number in nums, return this repeated number.\nYou must solve the problem without modifying the array nums and uses only constant extra space.\n Example 1:\nInput: nums = [1,3,4,2,2]\nOutput: 2\nExample 2:\nInput: nums = [3,1,3,4,2]\nOutput: 3\nExample 3:\nInput: nums = [3,3,3,3,3]\nOutput: 3\n Constraints:\n1 <= n <= 105\nnums.length == n + 1\n1 <= nums[i] <= n\nAll the integers in nums appear only once except for precisely one integer which appears two or more times.\n Follow up:\nHow can we prove that at least one duplicate number must exist in nums?\nCan you solve the problem in linear runtime complexity?" }, { "post_href": "https://leetcode.com/problems/game-of-life/discuss/468108/Use-the-tens-digit-as-a-counter-Python-O(1)-Space-O(mn)-Time", "python_solutions": "class Solution:\n def gameOfLife(self, board: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n \n def is_neighbor(board, i, j):\n return (0 <= i < len(board)) and (0 <= j < len(board[0])) and board[i][j] % 10 == 1\n \n directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n for d in directions:\n board[i][j] += 10 if is_neighbor(board, i + d[0], j + d[1]) else 0 # if adj cell is neighbor, add 10\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n neighbors = board[i][j] // 10 # count of neighbors\n is_live = board[i][j] % 10 == 1 # state is live or not\n if is_live: # live(1)\n if neighbors < 2: # Rule 1\n board[i][j] = 0\n elif neighbors > 3: # Rule 3\n board[i][j] = 0\n else: # Rule 2\n board[i][j] = 1\n else: # dead(0)\n if neighbors == 3: # Rule 4\n board[i][j] = 1\n else:\n board[i][j] = 0", "slug": "game-of-life", "post_title": "Use the tens digit as a counter, Python O(1) Space, O(mn) Time", "user": "Moooooon", "upvotes": 4, "views": 104, "problem_title": "game of life", "number": 289, "acceptance": 0.6679999999999999, "difficulty": "Medium", "__index_level_0__": 5156, "question": "According to Wikipedia's article: \"The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.\"\nThe board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):\nAny live cell with fewer than two live neighbors dies as if caused by under-population.\nAny live cell with two or three live neighbors lives on to the next generation.\nAny live cell with more than three live neighbors dies, as if by over-population.\nAny dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\nThe next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.\n Example 1:\nInput: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\nOutput: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\nExample 2:\nInput: board = [[1,1],[1,0]]\nOutput: [[1,1],[1,1]]\n Constraints:\nm == board.length\nn == board[i].length\n1 <= m, n <= 25\nboard[i][j] is 0 or 1.\n Follow up:\nCould you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.\nIn this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?" }, { "post_href": "https://leetcode.com/problems/word-pattern/discuss/1696590/Simple-Python-Solution-oror-Faster-than-99.34", "python_solutions": "class Solution:\n def wordPattern(self, pattern: str, s: str) -> bool:\n li = s.split(' ')\n di = {}\n if len(li) != len(pattern):\n return False\n \n for i, val in enumerate(pattern):\n if val in di and di[val] != li[i]:\n return False\n elif val not in di and li[i] in di.values():\n return False\n elif val not in di:\n di[val] = li[i]\n \n return True", "slug": "word-pattern", "post_title": "Simple Python Solution || Faster than 99.34%", "user": "KiranUpase", "upvotes": 4, "views": 509, "problem_title": "word pattern", "number": 290, "acceptance": 0.4039999999999999, "difficulty": "Easy", "__index_level_0__": 5202, "question": "Given a pattern and a string s, find if s follows the same pattern.\nHere follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.\n Example 1:\nInput: pattern = \"abba\", s = \"dog cat cat dog\"\nOutput: true\nExample 2:\nInput: pattern = \"abba\", s = \"dog cat cat fish\"\nOutput: false\nExample 3:\nInput: pattern = \"aaaa\", s = \"dog cat cat dog\"\nOutput: false\n Constraints:\n1 <= pattern.length <= 300\npattern contains only lower-case English letters.\n1 <= s.length <= 3000\ns contains only lowercase English letters and spaces ' '.\ns does not contain any leading or trailing spaces.\nAll the words in s are separated by a single space." }, { "post_href": "https://leetcode.com/problems/nim-game/discuss/1141120/Bottom-up-DP-python", "python_solutions": "class Solution:\n def canWinNim(self, n: int) -> bool: \n if n <= 3:\n return True\n new_size = n + 1\n memo = [False] * (new_size)\n \n for i in range(4): \n memo[i] = True\n \n for i in range(4,new_size):\n for j in range(1,4):\n if memo[i] == True:\n break\n if memo[i-j] == True:\n memo[i] = False\n else:\n memo[i] = True\n \n return memo[n]", "slug": "nim-game", "post_title": "Bottom-up DP python", "user": "lywc", "upvotes": 9, "views": 725, "problem_title": "nim game", "number": 292, "acceptance": 0.5589999999999999, "difficulty": "Easy", "__index_level_0__": 5249, "question": "You are playing the following Nim Game with your friend:\nInitially, there is a heap of stones on the table.\nYou and your friend will alternate taking turns, and you go first.\nOn each turn, the person whose turn it is will remove 1 to 3 stones from the heap.\nThe one who removes the last stone is the winner.\nGiven n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.\n Example 1:\nInput: n = 4\nOutput: false\nExplanation: These are the possible outcomes:\n1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\nIn all outcomes, your friend wins.\nExample 2:\nInput: n = 1\nOutput: true\nExample 3:\nInput: n = 2\nOutput: true\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/bulls-and-cows/discuss/563661/Fast-and-easy-to-understand-Python-solution-O(n)", "python_solutions": "class Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \n\t\t# The main idea is to understand that cow cases contain the bull cases\n\t\t\n\t\t# This loop will take care of \"bull\" cases\n bull=0\n for i in range(len(secret)):\n bull += int(secret[i] == guess[i])\n \n\t\t# This loop will take care of \"cow\" cases\n cows=0\n for c in set(secret):\n cows += min(secret.count(c), guess.count(c))\n \n return f\"{bull}A{cows-bull}B\"", "slug": "bulls-and-cows", "post_title": "Fast and easy to understand Python solution O(n)", "user": "mista2311", "upvotes": 14, "views": 983, "problem_title": "bulls and cows", "number": 299, "acceptance": 0.487, "difficulty": "Medium", "__index_level_0__": 5269, "question": "You are playing the Bulls and Cows game with your friend.\nYou write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:\nThe number of \"bulls\", which are digits in the guess that are in the correct position.\nThe number of \"cows\", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.\nGiven the secret number secret and your friend's guess guess, return the hint for your friend's guess.\nThe hint should be formatted as \"xAyB\", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.\n Example 1:\nInput: secret = \"1807\", guess = \"7810\"\nOutput: \"1A3B\"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n\"1807\"\n |\n\"7810\"\nExample 2:\nInput: secret = \"1123\", guess = \"0111\"\nOutput: \"1A1B\"\nExplanation: Bulls are connected with a '|' and cows are underlined:\n\"1123\" \"1123\"\n | or |\n\"0111\" \"0111\"\nNote that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull.\n Constraints:\n1 <= secret.length, guess.length <= 1000\nsecret.length == guess.length\nsecret and guess consist of digits only." }, { "post_href": "https://leetcode.com/problems/longest-increasing-subsequence/discuss/2395570/Python3-oror-7-lines-binSearch-cheating-wexplanation-oror-TM%3A-9482", "python_solutions": "class Solution: # Suppose, for example:\n # nums = [1,8,4,5,3,7],\n # for which the longest strictly increasing subsequence is arr = [1,4,5,7],\n # giving len(arr) = 4 as the answer\n #\n # Here's the plan:\n # 1) Initiate arr = [num[0]], which in this example means arr = [1]\n # \n # 2) Iterate through nums. 2a) If n in nums is greater than arr[-1], append n to arr. 2b) If \n # not, determine the furthest position in arr at which n could be placed so that arr\n # remains strictly increasing, and overwrite the element at that position in arr with n.\n\n # 3) Once completed, return the length of arr.\n\n # Here's the iteration for the example:\n\n # nums = [ _1_, 8,4,5,3,7] arr = [1] (initial step)\n # nums = [1, _8_, 4,5,3,7] arr = [1, 8] (8 > 1, so append 8)\n # nums = [1,8, _4_, 5,3,7] arr = [1, 4] (4 < 8, so overwrite 8)\n # nums = [1_8,4, _5_, 3,7] arr = [1, 4, 5] (5 > 4, so append 5)\n # nums = [1_8,4,5, _3_, 7] arr = [1, 3, 5] (3 < 5, so overwrite 4)\n # nums = [1_8,4,5,3, _7_ ] arr = [1, 3, 5, 7] (7 > 5, so append 7) \n\n # Notice that arr is not the sequence given above as the correct seq. The ordering for [1,3,5,7]\n # breaks the \"no changing the order\" rule. Cheating? Maybe... However len(arr) = 4 is the \n # correct answer. Overwriting 4 with 3 did not alter the sequence's length.\n \n def lengthOfLIS(self, nums: list[int]) -> int:\n\n arr = [nums.pop(0)] # <-- 1) initial step\n \n for n in nums: # <-- 2) iterate through nums\n \n if n > arr[-1]: # <-- 2a)\n arr.append(n)\n\n else: # <-- 2b)\n arr[bisect_left(arr, n)] = n \n\n return len(arr) # <-- 3) return the length of arr", "slug": "longest-increasing-subsequence", "post_title": "Python3 || 7 lines, binSearch, cheating, w/explanation || T/M: 94%/82%", "user": "warrenruud", "upvotes": 45, "views": 4100, "problem_title": "longest increasing subsequence", "number": 300, "acceptance": 0.516, "difficulty": "Medium", "__index_level_0__": 5303, "question": "Given an integer array nums, return the length of the longest strictly increasing\nsubsequence\n.\n Example 1:\nInput: nums = [10,9,2,5,3,7,101,18]\nOutput: 4\nExplanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\nExample 2:\nInput: nums = [0,1,0,3,2,3]\nOutput: 4\nExample 3:\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 1\n Constraints:\n1 <= nums.length <= 2500\n-104 <= nums[i] <= 104\n Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?" }, { "post_href": "https://leetcode.com/problems/remove-invalid-parentheses/discuss/1555755/Easy-to-understand-Python-solution", "python_solutions": "class Solution:\n def removeInvalidParentheses(self, s: str) -> List[str]:\n \n def valid(s):\n l,r=0,0\n for c in s:\n if c=='(':\n l+=1\n elif c==')':\n if l<=0:\n r+=1\n else:\n l-=1\n return not l and not r\n \n res=[]\n seen=set()\n level={s}\n while True:\n newLevel=set()\n for word in level:\n if valid(word):\n res.append(word)\n if res: return res\n \n for word in level:\n for i in range(len(word)):\n if word[i] in '()':\n newWord=word[:i]+word[i+1:]\n if newWord not in seen:\n seen.add(newWord)\n newLevel.add(newWord)\n \n level=newLevel\n \n return [\"\"]", "slug": "remove-invalid-parentheses", "post_title": "Easy to understand Python \ud83d\udc0d solution", "user": "InjySarhan", "upvotes": 3, "views": 375, "problem_title": "remove invalid parentheses", "number": 301, "acceptance": 0.471, "difficulty": "Hard", "__index_level_0__": 5356, "question": "Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.\nReturn a list of unique strings that are valid with the minimum number of removals. You may return the answer in any order.\n Example 1:\nInput: s = \"()())()\"\nOutput: [\"(())()\",\"()()()\"]\nExample 2:\nInput: s = \"(a)())()\"\nOutput: [\"(a())()\",\"(a)()()\"]\nExample 3:\nInput: s = \")(\"\nOutput: [\"\"]\n Constraints:\n1 <= s.length <= 25\ns consists of lowercase English letters and parentheses '(' and ')'.\nThere will be at most 20 parentheses in s." }, { "post_href": "https://leetcode.com/problems/additive-number/discuss/2764371/Python-solution-with-complete-explanation-and-code", "python_solutions": "class Solution:\n def isAdditiveNumber(self, s: str) -> bool:\n n = len(s)\n for i in range(1, n): # Choose the length of first number\n # If length of 1st number is > 1 and starts with 0 -- skip\n if i != 1 and s[0] == '0':\n continue\n for j in range(1, n): # Choose the length of second number\n # If length of 2nd number is > 1 and starts with 0 -- skip\n if j != 1 and s[i] == '0':\n continue\n\n # If the total length of 1st and 2nd number >= n -- skip\n if i + j >= n:\n break\n\n # Just use the brute force approach\n a = int(s[0: i])\n b = int(s[i: i+j])\n d = i+j\n while d < n:\n c = a + b\n t = str(c)\n if s[d: d + len(t)] != t:\n break\n d += len(t)\n a = b\n b = c\n if d == n:\n return True\n return False", "slug": "additive-number", "post_title": "Python solution with complete explanation and code", "user": "smit5300", "upvotes": 0, "views": 11, "problem_title": "additive number", "number": 306, "acceptance": 0.309, "difficulty": "Medium", "__index_level_0__": 5364, "question": "An additive number is a string whose digits can form an additive sequence.\nA valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.\nGiven a string containing only digits, return true if it is an additive number or false otherwise.\nNote: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.\n Example 1:\nInput: \"112358\"\nOutput: true\nExplanation: \nThe digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\nExample 2:\nInput: \"199100199\"\nOutput: true\nExplanation: \nThe additive sequence is: 1, 99, 100, 199. \n1 + 99 = 100, 99 + 100 = 199\n Constraints:\n1 <= num.length <= 35\nnum consists only of digits.\n Follow up: How would you handle overflow for very large input integers?" }, { "post_href": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/2132119/Python-or-Easy-DP-or", "python_solutions": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n n = len(prices)\n dp = [[0 for i in range(2)] for i in range(n+2)]\n \n dp[n][0] = dp[n][1] = 0\n \n ind = n-1\n while(ind>=0):\n\t\t\n for buy in range(2):\n if(buy):\n profit = max(-prices[ind] + dp[ind+1][0], 0 + dp[ind+1][1])\n\t\t\t\t\t\n else:\n profit = max(prices[ind] + dp[ind+2][1], 0 + dp[ind+1][0])\n \n dp[ind][buy] = profit\n\t\t\t\t\n ind -= 1 \n\t\t\t\n return dp[0][1]", "slug": "best-time-to-buy-and-sell-stock-with-cooldown", "post_title": "Python | Easy DP |", "user": "LittleMonster23", "upvotes": 4, "views": 166, "problem_title": "best time to buy and sell stock with cooldown", "number": 309, "acceptance": 0.546, "difficulty": "Medium", "__index_level_0__": 5369, "question": "You are given an array prices where prices[i] is the price of a given stock on the ith day.\nFind the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:\nAfter you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).\nNote: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\nInput: prices = [1,2,3,0,2]\nOutput: 3\nExplanation: transactions = [buy, sell, cooldown, buy, sell]\nExample 2:\nInput: prices = [1]\nOutput: 0\n Constraints:\n1 <= prices.length <= 5000\n0 <= prices[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/minimum-height-trees/discuss/1753794/Python-easy-to-read-and-understand-or-reverse-topological-sort", "python_solutions": "class Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n == 1:\n return [0]\n graph = {i:[] for i in range(n)}\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n \n leaves = []\n for node in graph:\n if len(graph[node]) == 1:\n leaves.append(node)\n \n while len(graph) > 2:\n new_leaves = []\n for leaf in leaves:\n nei = graph[leaf].pop()\n del graph[leaf]\n graph[nei].remove(leaf)\n if len(graph[nei]) == 1:\n new_leaves.append(nei)\n leaves = new_leaves\n \n return leaves", "slug": "minimum-height-trees", "post_title": "Python easy to read and understand | reverse topological sort", "user": "sanial2001", "upvotes": 7, "views": 336, "problem_title": "minimum height trees", "number": 310, "acceptance": 0.385, "difficulty": "Medium", "__index_level_0__": 5399, "question": "A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.\nGiven a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).\nReturn a list of all MHTs' root labels. You can return the answer in any order.\nThe height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.\n Example 1:\nInput: n = 4, edges = [[1,0],[1,2],[1,3]]\nOutput: [1]\nExplanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.\nExample 2:\nInput: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\nOutput: [3,4]\n Constraints:\n1 <= n <= 2 * 104\nedges.length == n - 1\n0 <= ai, bi < n\nai != bi\nAll the pairs (ai, bi) are distinct.\nThe given input is guaranteed to be a tree and there will be no repeated edges." }, { "post_href": "https://leetcode.com/problems/burst-balloons/discuss/1477014/Python3-or-Top-down-Approach", "python_solutions": "class Solution(object):\n def maxCoins(self, nums):\n n=len(nums)\n nums.insert(n,1)\n nums.insert(0,1)\n self.dp={}\n return self.dfs(1,nums,n)\n def dfs(self,strt,nums,end):\n ans=0\n if strt>end:\n return 0\n if (strt,end) in self.dp:\n return self.dp[(strt,end)]\n for i in range(strt,end+1):\n lmax=self.dfs(strt,nums,i-1)\n rmax=self.dfs(i+1,nums,end)\n curr_coins=nums[strt-1]*nums[i]*nums[end+1]+lmax+rmax\n ans=max(ans,curr_coins)\n self.dp[(strt,end)]=ans\n return self.dp[(strt,end)]", "slug": "burst-balloons", "post_title": "[Python3] | Top-down Approach", "user": "swapnilsingh421", "upvotes": 2, "views": 269, "problem_title": "burst balloons", "number": 312, "acceptance": 0.568, "difficulty": "Hard", "__index_level_0__": 5412, "question": "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.\nIf 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.\nReturn the maximum coins you can collect by bursting the balloons wisely.\n Example 1:\nInput: nums = [3,1,5,8]\nOutput: 167\nExplanation:\nnums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\ncoins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167\nExample 2:\nInput: nums = [1,5]\nOutput: 10\n Constraints:\nn == nums.length\n1 <= n <= 300\n0 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/super-ugly-number/discuss/2828266/heapq-did-the-job", "python_solutions": "class Solution:\n def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n hp=[1]\n dc={1}\n i=1\n while(n):\n mn=heapq.heappop(hp)\n if(n==1):\n return mn\n for p in primes:\n newno=mn*p\n if(newno in dc):\n continue\n heapq.heappush(hp,newno)\n dc.add(newno)\n n-=1", "slug": "super-ugly-number", "post_title": "heapq did the job", "user": "droj", "upvotes": 5, "views": 40, "problem_title": "super ugly number", "number": 313, "acceptance": 0.4579999999999999, "difficulty": "Medium", "__index_level_0__": 5421, "question": "A super ugly number is a positive integer whose prime factors are in the array primes.\nGiven an integer n and an array of integers primes, return the nth super ugly number.\nThe nth super ugly number is guaranteed to fit in a 32-bit signed integer.\n Example 1:\nInput: n = 12, primes = [2,7,13,19]\nOutput: 32\nExplanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 super ugly numbers given primes = [2,7,13,19].\nExample 2:\nInput: n = 1, primes = [2,3,5]\nOutput: 1\nExplanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].\n Constraints:\n1 <= n <= 105\n1 <= primes.length <= 100\n2 <= primes[i] <= 1000\nprimes[i] is guaranteed to be a prime number.\nAll the values of primes are unique and sorted in ascending order." }, { "post_href": "https://leetcode.com/problems/count-of-smaller-numbers-after-self/discuss/2320000/Python3.-oror-binSearch-6-lines-w-explanation-oror-TM%3A-9784", "python_solutions": "class Solution: # Here's the plan:\n # 1) Make arr, a sorted copy of the list nums.\n # 2) iterate through nums. For each element num in nums:\n # 2a) use a binary search to determine the count of elements\n # in the arr that are less than num.\n # 2b) append that count to the answer list\n # 2c) delete num from arr\n # 3) return the ans list \n # \n # For example, suppose nums = [5,2,6,1] Then arr = [1,2,5,6].\n # num = 5 => binsearch: arr = [1,2,/\\5,6], i = 2 => ans = [2,_,_,_], del 5\n # num = 2 => binsearch: arr = [1,/\\2,6], i = 1 => ans = [2,1,_,_], del 2\n # num = 6 => binsearch: arr = [1,/\\6], i = 1 => ans = [2,1,1,_], del 6\n # num = 1 => binsearch: arr = [/\\1], i = 0 => ans = [2,1,1,0], del 1\n\n def countSmaller(self, nums: List[int]) -> List[int]:\n arr, ans = sorted(nums), [] # <-- 1)\n \n for num in nums:\n i = bisect_left(arr,num) # <-- 2a)\n ans.append(i) # <-- 2b)\n del arr[i] # <-- 2c)\n \n return ans # <-- 3)", "slug": "count-of-smaller-numbers-after-self", "post_title": "Python3. || binSearch 6 lines, w/ explanation || T/M: 97%/84%", "user": "warrenruud", "upvotes": 27, "views": 3000, "problem_title": "count of smaller numbers after self", "number": 315, "acceptance": 0.428, "difficulty": "Hard", "__index_level_0__": 5429, "question": "Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].\n Example 1:\nInput: nums = [5,2,6,1]\nOutput: [2,1,1,0]\nExplanation:\nTo the right of 5 there are 2 smaller elements (2 and 1).\nTo the right of 2 there is only 1 smaller element (1).\nTo the right of 6 there is 1 smaller element (1).\nTo the right of 1 there is 0 smaller element.\nExample 2:\nInput: nums = [-1]\nOutput: [0]\nExample 3:\nInput: nums = [-1,-1]\nOutput: [0,0]\n Constraints:\n1 <= nums.length <= 105\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/remove-duplicate-letters/discuss/1687144/Python-3-Simple-solution-using-a-stack-and-greedy-approach-(32ms-14.4MB)", "python_solutions": "class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n stack = []\n \n for idx, character in enumerate(s):\n if not stack:\n stack.append(character)\n elif character in stack:\n continue\n else:\n while stack and (character < stack[-1]):\n if stack[-1] in s[idx + 1:]:\n _ = stack.pop()\n else:\n break\n \n stack.append(character)\n \n return ''.join(stack)", "slug": "remove-duplicate-letters", "post_title": "[Python 3] Simple solution using a stack and greedy approach (32ms, 14.4MB)", "user": "seankala", "upvotes": 5, "views": 498, "problem_title": "remove duplicate letters", "number": 316, "acceptance": 0.446, "difficulty": "Medium", "__index_level_0__": 5443, "question": "Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is\nthe smallest in lexicographical order\namong all possible results.\n Example 1:\nInput: s = \"bcabc\"\nOutput: \"abc\"\nExample 2:\nInput: s = \"cbacdcbc\"\nOutput: \"acdb\"\n Constraints:\n1 <= s.length <= 104\ns consists of lowercase English letters.\n Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" }, { "post_href": "https://leetcode.com/problems/maximum-product-of-word-lengths/discuss/2085316/Python-or-or-Easy-3-Approaches-explained", "python_solutions": "class Solution:\n def maxProduct(self, words: List[str]) -> int:\n n=len(words) \n char_set = [set(words[i]) for i in range(n)] # precompute hashset for each word \n max_val = 0\n for i in range(n):\n for j in range(i+1, n):\n if not (char_set[i] & char_set[j]): # if nothing common\n max_val=max(max_val, len(words[i]) * len(words[j]))\n \n return max_val", "slug": "maximum-product-of-word-lengths", "post_title": "\u2705 Python | | Easy 3 Approaches explained", "user": "constantine786", "upvotes": 57, "views": 3700, "problem_title": "maximum product of word lengths", "number": 318, "acceptance": 0.601, "difficulty": "Medium", "__index_level_0__": 5463, "question": "Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.\n Example 1:\nInput: words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\nOutput: 16\nExplanation: The two words can be \"abcw\", \"xtfn\".\nExample 2:\nInput: words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\nOutput: 4\nExplanation: The two words can be \"ab\", \"cd\".\nExample 3:\nInput: words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: 0\nExplanation: No such pair of words.\n Constraints:\n2 <= words.length <= 1000\n1 <= words[i].length <= 1000\nwords[i] consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/bulb-switcher/discuss/535399/PythonJSJavaC%2B%2B-sol-by-perfect-square.-w-Visualization", "python_solutions": "class Solution:\n def bulbSwitch(self, n: int) -> int:\n \n # Only those bulds with perferct square number index will keep \"ON\" at last.\n \n return int(n**0.5)", "slug": "bulb-switcher", "post_title": "Python/JS/Java/C++ sol by perfect square. [w/ Visualization]", "user": "brianchiang_tw", "upvotes": 20, "views": 1200, "problem_title": "bulb switcher", "number": 319, "acceptance": 0.481, "difficulty": "Medium", "__index_level_0__": 5507, "question": "There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.\nOn the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.\nReturn the number of bulbs that are on after n rounds.\n Example 1:\nInput: n = 3\nOutput: 1\nExplanation: At first, the three bulbs are [off, off, off].\nAfter the first round, the three bulbs are [on, on, on].\nAfter the second round, the three bulbs are [on, off, on].\nAfter the third round, the three bulbs are [on, off, off]. \nSo you should return 1 because there is only one bulb is on.\nExample 2:\nInput: n = 0\nOutput: 0\nExample 3:\nInput: n = 1\nOutput: 1\n Constraints:\n0 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/create-maximum-number/discuss/2167532/O(k(m%2Bn)).-Python-Solution-with-monotonically-decreasing-stack.-Commented-for-clarity.", "python_solutions": "class Solution:\n def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:\n def maximum_num_each_list(nums: List[int], k_i: int) -> List[int]:\n # monotonically decreasing stack\n s = []\n m = len(nums) - k_i\n for n in nums:\n while s and s[-1] < n and m > 0:\n s.pop()\n m -= 1\n s.append(n)\n s = s[:len(s)-m] # very important\n return s\n def greater(a, b, i , j): # get the number which is lexiographically greater\n while i< len(a) or j < len(b): \n if i == len(a): return False\n if j == len(b): return True\n if a[i] > b[j]: return True\n if a[i] < b[j]: return False\n i += 1 # we increment until each of their elements are same\n j += 1\n \n def merge(x_num, y_num):\n n = len(x_num)\n m = len(y_num)\n i = 0\n j = 0\n s = []\n while i < n or j < m:\n a = x_num[i] if i < n else float(\"-inf\") \n b = y_num[j] if j < m else float(\"-inf\") \n\n if a > b or greater(x_num, y_num, i , j):\n# greater(x_num, y_num, i , j): this function is meant for check which list has element lexicographically greater means it will iterate through both arrays incrementing both at the same time until one of them is greater than other.\n chosen = a\n i += 1\n else:\n chosen = b\n j += 1\n s.append(chosen)\n return s\n\n max_num_arr = []\n for i in range(k+1): # we check for all values of k and find the maximum number we can create for that value of k and we repeat this for all values of k and then at eacch time merge the numbers to check if arrive at optimal solution\n first = maximum_num_each_list(nums1, i)\n second = maximum_num_each_list(nums2, k-i)\n merged = merge(first, second)\n # these two conditions are required because list comparison in python only compares the elements even if one of their lengths is greater, so I had to add these conditions to compare elements only if length is equal.\n\t\t\t# Alternatively you can avoid this and convert them both to int and then compare, but I wanted to this as it is somewhat more efficient.\n if len(merged) == len(max_num_arr) and merged > max_num_arr:\n max_num_arr = merged\n elif len(merged) > len(max_num_arr):\n max_num_arr = merged\n return max_num_arr", "slug": "create-maximum-number", "post_title": "O(k(m+n)). Python Solution with monotonically decreasing stack. Commented for clarity.", "user": "saqibmubarak", "upvotes": 2, "views": 443, "problem_title": "create maximum number", "number": 321, "acceptance": 0.288, "difficulty": "Hard", "__index_level_0__": 5514, "question": "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.\nCreate 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.\nReturn an array of the k digits representing the answer.\n Example 1:\nInput: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\nOutput: [9,8,6,5,3]\nExample 2:\nInput: nums1 = [6,7], nums2 = [6,0,4], k = 5\nOutput: [6,7,6,0,4]\nExample 3:\nInput: nums1 = [3,9], nums2 = [8,9], k = 3\nOutput: [9,8,9]\n Constraints:\nm == nums1.length\nn == nums2.length\n1 <= m, n <= 500\n0 <= nums1[i], nums2[i] <= 9\n1 <= k <= m + n" }, { "post_href": "https://leetcode.com/problems/coin-change/discuss/2058537/Python-Easy-2-DP-approaches", "python_solutions": "class Solution:\n def coinChange(self, coins: List[int], amount: int) -> int: \n dp=[math.inf] * (amount+1)\n dp[0]=0\n \n for coin in coins:\n for i in range(coin, amount+1):\n if i-coin>=0:\n dp[i]=min(dp[i], dp[i-coin]+1)\n \n return -1 if dp[-1]==math.inf else dp[-1]", "slug": "coin-change", "post_title": "Python Easy 2 DP approaches", "user": "constantine786", "upvotes": 32, "views": 3800, "problem_title": "coin change", "number": 322, "acceptance": 0.416, "difficulty": "Medium", "__index_level_0__": 5519, "question": "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\nReturn the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\nYou may assume that you have an infinite number of each kind of coin.\n Example 1:\nInput: coins = [1,2,5], amount = 11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\nExample 2:\nInput: coins = [2], amount = 3\nOutput: -1\nExample 3:\nInput: coins = [1], amount = 0\nOutput: 0\n Constraints:\n1 <= coins.length <= 12\n1 <= coins[i] <= 231 - 1\n0 <= amount <= 104" }, { "post_href": "https://leetcode.com/problems/wiggle-sort-ii/discuss/1322709/Definitely-not-O(n)-but-did-it-iteratively-in-O(nlog(N))-time", "python_solutions": "class Solution:\n def wiggleSort(self, nums: List[int]) -> None:\n sortedList = sorted(nums)\n n = len(nums)\n if n%2==0:\n small = sortedList[:((n//2))][::-1]\n large = (sortedList[(n//2):])[::-1]\n for i in range(1,n,2):\n nums[i] = large[i//2]\n for i in range(0,n,2):\n nums[i] = small[i//2]\n else:\n small = sortedList[:1+((n//2))][::-1]\n large = (sortedList[1+(n//2):])[::-1]\n for i in range(1,n,2):\n nums[i] = large[i//2]\n for i in range(0,n,2):\n nums[i] = small[i//2]", "slug": "wiggle-sort-ii", "post_title": "Definitely not O(n) but did it iteratively in O(nlog(N)) time", "user": "prajwalPonnana004", "upvotes": 1, "views": 180, "problem_title": "wiggle sort ii", "number": 324, "acceptance": 0.33, "difficulty": "Medium", "__index_level_0__": 5579, "question": "Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....\nYou may assume the input array always has a valid answer.\n Example 1:\nInput: nums = [1,5,1,1,6,4]\nOutput: [1,6,1,5,1,4]\nExplanation: [1,4,1,5,1,6] is also accepted.\nExample 2:\nInput: nums = [1,3,2,2,3,1]\nOutput: [2,3,1,3,1,2]\n Constraints:\n1 <= nums.length <= 5 * 104\n0 <= nums[i] <= 5000\nIt is guaranteed that there will be an answer for the given input nums.\n Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?" }, { "post_href": "https://leetcode.com/problems/power-of-three/discuss/1179790/Simple-Python-Recursive-Solution-with-Explanation", "python_solutions": "class Solution:\n def isPowerOfThree(self, n: int) -> bool:\n if n == 1:\n return True\n if n == 0:\n return False\n else:\n return n % 3 == 0 and self.isPowerOfThree(n // 3)", "slug": "power-of-three", "post_title": "Simple Python Recursive Solution with Explanation", "user": "stevenbooke", "upvotes": 8, "views": 356, "problem_title": "power of three", "number": 326, "acceptance": 0.4529999999999999, "difficulty": "Easy", "__index_level_0__": 5582, "question": "Given an integer n, return true if it is a power of three. Otherwise, return false.\nAn integer n is a power of three, if there exists an integer x such that n == 3x.\n Example 1:\nInput: n = 27\nOutput: true\nExplanation: 27 = 33\nExample 2:\nInput: n = 0\nOutput: false\nExplanation: There is no x where 3x = 0.\nExample 3:\nInput: n = -1\nOutput: false\nExplanation: There is no x where 3x = (-1).\n Constraints:\n-231 <= n <= 231 - 1\n Follow up: Could you solve it without loops/recursion?" }, { "post_href": "https://leetcode.com/problems/count-of-range-sum/discuss/1195369/Python3-4-solutions", "python_solutions": "class Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n def fn(lo, hi): \n \"\"\"Return count of range sum between prefix[lo:hi].\"\"\"\n if lo+1 >= hi: return 0 \n mid = lo + hi >> 1\n ans = fn(lo, mid) + fn(mid, hi)\n k = kk = mid \n for i in range(lo, mid): \n while k < hi and prefix[k] - prefix[i] < lower: k += 1\n while kk < hi and prefix[kk] - prefix[i] <= upper: kk += 1\n ans += kk - k \n prefix[lo:hi] = sorted(prefix[lo:hi])\n return ans \n \n return fn(0, len(prefix))", "slug": "count-of-range-sum", "post_title": "[Python3] 4 solutions", "user": "ye15", "upvotes": 8, "views": 459, "problem_title": "count of range sum", "number": 327, "acceptance": 0.361, "difficulty": "Hard", "__index_level_0__": 5643, "question": "Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.\nRange sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.\n Example 1:\nInput: nums = [-2,5,-1], lower = -2, upper = 2\nOutput: 3\nExplanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\nExample 2:\nInput: nums = [0], lower = 0, upper = 0\nOutput: 1\n Constraints:\n1 <= nums.length <= 105\n-231 <= nums[i] <= 231 - 1\n-105 <= lower <= upper <= 105\nThe answer is guaranteed to fit in a 32-bit integer." }, { "post_href": "https://leetcode.com/problems/odd-even-linked-list/discuss/2458296/easy-approach-using-two-pointer-in-python-With-Comments-TC-%3A-O(N)-SC-%3A-O(1)", "python_solutions": "class Solution:\n def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if(head is None or head.next is None):\n return head\n # assign odd = head(starting node of ODD)\n # assign even = head.next(starting node of EVEN)\n odd , even = head , head.next\n \n Even = even # keep starting point of Even Node so later we will connect with Odd Node\n while(odd.next and even.next):\n odd.next = odd.next.next # Connect odd.next to odd Node\n even.next = even.next.next # Connect even,next to Even Node\n \n odd = odd.next # move odd \n even = even.next # move even\n \n odd.next = Even # now connect odd.next to starting point to Even list\n \n return head", "slug": "odd-even-linked-list", "post_title": "easy approach using two pointer in python With Comments [TC : O(N) SC : O(1)]", "user": "rajitkumarchauhan99", "upvotes": 4, "views": 156, "problem_title": "odd even linked list", "number": 328, "acceptance": 0.603, "difficulty": "Medium", "__index_level_0__": 5648, "question": "Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.\nThe first node is considered odd, and the second node is even, and so on.\nNote that the relative order inside both the even and odd groups should remain as it was in the input.\nYou must solve the problem in O(1) extra space complexity and O(n) time complexity.\n Example 1:\nInput: head = [1,2,3,4,5]\nOutput: [1,3,5,2,4]\nExample 2:\nInput: head = [2,1,3,5,6,4,7]\nOutput: [2,3,6,7,1,5,4]\n Constraints:\nThe number of nodes in the linked list is in the range [0, 104].\n-106 <= Node.val <= 106" }, { "post_href": "https://leetcode.com/problems/longest-increasing-path-in-a-matrix/discuss/2052380/Python-DFS-with-Memoization-Beats-~90", "python_solutions": "class Solution:\n def longestIncreasingPath(self, grid: List[List[int]]) -> int:\n m,n=len(grid),len(grid[0])\n directions = [0, 1, 0, -1, 0] # four directions \n \n @lru_cache(maxsize=None) # using python cache lib for memoization\n def dfs(r,c):\n ans=1 \n\t\t\t# iterating through all 4 directions\n for i in range(4): \n new_row,new_col=r+directions[i], c+directions[i+1] # calculating the new cell\n\t\t\t\t# check if new cell is within the grid bounds and is an increasing sequence\n if 0<=new_rowgrid[r][c]: \n ans = max(ans, dfs(new_row, new_col) + 1 ) # finding the max length of valid path from the current cell \n return ans\n \n return max(dfs(r,c) for r in range(m) for c in range(n))", "slug": "longest-increasing-path-in-a-matrix", "post_title": "Python DFS with Memoization Beats ~90%", "user": "constantine786", "upvotes": 4, "views": 580, "problem_title": "longest increasing path in a matrix", "number": 329, "acceptance": 0.522, "difficulty": "Hard", "__index_level_0__": 5669, "question": "Given an m x n integers matrix, return the length of the longest increasing path in matrix.\nFrom 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 Example 1:\nInput: matrix = [[9,9,4],[6,6,8],[2,1,1]]\nOutput: 4\nExplanation: The longest increasing path is [1, 2, 6, 9].\nExample 2:\nInput: matrix = [[3,4,5],[3,2,6],[2,2,1]]\nOutput: 4\nExplanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.\nExample 3:\nInput: matrix = [[1]]\nOutput: 1\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 200\n0 <= matrix[i][j] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/patching-array/discuss/1432390/Python-3-easy-solution", "python_solutions": "class Solution:\n\tdef minPatches(self, nums: List[int], n: int) -> int:\n\t\tans, total = 0, 0\n\t\tnum_idx = 0\n\t\twhile total < n:\n\t\t\tif num_idx < len(nums):\n\t\t\t\tif total < nums[num_idx] - 1:\n\t\t\t\t\ttotal = total * 2 + 1\n\t\t\t\t\tans += 1\n\t\t\t\telse:\n\t\t\t\t\ttotal += nums[num_idx]\n\t\t\t\t\tnum_idx += 1\n\t\t\telse:\n\t\t\t\ttotal = total * 2 + 1\n\t\t\t\tans += 1\n\t\treturn ans", "slug": "patching-array", "post_title": "Python 3 easy solution", "user": "Andy_Feng97", "upvotes": 1, "views": 231, "problem_title": "patching array", "number": 330, "acceptance": 0.4, "difficulty": "Hard", "__index_level_0__": 5714, "question": "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.\nReturn the minimum number of patches required.\n Example 1:\nInput: nums = [1,3], n = 6\nOutput: 1\nExplanation:\nCombinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\nNow if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\nPossible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\nSo we only need 1 patch.\nExample 2:\nInput: nums = [1,5,10], n = 20\nOutput: 2\nExplanation: The two patches can be [2, 4].\nExample 3:\nInput: nums = [1,2,2], n = 5\nOutput: 0\n Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 104\nnums is sorted in ascending order.\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/discuss/1459342/Python3-or-O(n)-Time-and-O(n)-space", "python_solutions": "class Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n stack = []\n items = preorder.split(\",\")\n for i, val in enumerate(items):\n if i>0 and not stack:\n return False\n if stack:\n stack[-1][1] -= 1\n if stack[-1][1] == 0:\n stack.pop()\n if val != \"#\":\n stack.append([val, 2])\n return not stack", "slug": "verify-preorder-serialization-of-a-binary-tree", "post_title": "Python3 | O(n) Time and O(n) space", "user": "Sanjaychandak95", "upvotes": 3, "views": 73, "problem_title": "verify preorder serialization of a binary tree", "number": 331, "acceptance": 0.4429999999999999, "difficulty": "Medium", "__index_level_0__": 5716, "question": "One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.\nFor example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where '#' represents a null node.\nGiven a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.\nIt is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer.\nYou may assume that the input format is always valid.\nFor example, it could never contain two consecutive commas, such as \"1,,3\".\nNote: You are not allowed to reconstruct the tree.\n Example 1:\nInput: preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\nOutput: true\nExample 2:\nInput: preorder = \"1,#\"\nOutput: false\nExample 3:\nInput: preorder = \"9,#,#,1\"\nOutput: false\n Constraints:\n1 <= preorder.length <= 104\npreorder consist of integers in the range [0, 100] and '#' separated by commas ','." }, { "post_href": "https://leetcode.com/problems/reconstruct-itinerary/discuss/1475876/Python-LC-but-better-explained", "python_solutions": "class Solution:\n def __init__(self):\n self.path = []\n \n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n flights = {}\n \n # as graph is directed\n # => no bi-directional paths\n for t1, t2 in tickets:\n if t1 not in flights:\n flights[t1] = []\n \n flights[t1].append(t2)\n\n visited = {}\n for k, v in flights.items():\n v.sort()\n visited[k] = [False for _ in range(len(v))]\n \n base_check = len(tickets) + 1\n routes = ['JFK']\n self.dfs('JFK', routes, base_check, flights, visited)\n \n return self.path\n \n \n def dfs(self, curr, routes, base_check, flights, visited):\n if len(routes) == base_check:\n self.path = routes\n return True\n \n # deadlock\n if curr not in flights:\n return False\n \n for idx in range(len(flights[curr])):\n if not visited[curr][idx]:\n visited[curr][idx] = True\n \n next_airport = flights[curr][idx]\n routes += [next_airport]\n result = self.dfs(next_airport, routes, base_check,\n flights, visited)\n \n if result:\n return True\n routes.pop()\n visited[curr][idx] = False\n\n return False", "slug": "reconstruct-itinerary", "post_title": "Python LC, but better explained", "user": "SleeplessChallenger", "upvotes": 1, "views": 213, "problem_title": "reconstruct itinerary", "number": 332, "acceptance": 0.41, "difficulty": "Hard", "__index_level_0__": 5724, "question": "You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.\nAll of the tickets belong to a man who departs from \"JFK\", thus, the itinerary must begin with \"JFK\". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.\nFor example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"].\nYou may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.\n Example 1:\nInput: tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\nOutput: [\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]\nExample 2:\nInput: tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\nOutput: [\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\nExplanation: Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"] but it is larger in lexical order.\n Constraints:\n1 <= tickets.length <= 300\ntickets[i].length == 2\nfromi.length == 3\ntoi.length == 3\nfromi and toi consist of uppercase English letters.\nfromi != toi" }, { "post_href": "https://leetcode.com/problems/increasing-triplet-subsequence/discuss/270884/Python-2-solutions%3A-Right-So-Far-One-pass-O(1)-Space-Clean-and-Concise", "python_solutions": "class Solution:\n def increasingTriplet(self, nums: List[int]) -> bool:\n n = len(nums)\n maxRight = [0] * n # maxRight[i] is the maximum element among nums[i+1...n-1]\n maxRight[-1] = nums[-1]\n for i in range(n-2, -1, -1):\n maxRight[i] = max(maxRight[i+1], nums[i+1])\n \n minLeft = nums[0]\n for i in range(1, n-1):\n if minLeft < nums[i] < maxRight[i]:\n return True\n minLeft = min(minLeft, nums[i])\n return False", "slug": "increasing-triplet-subsequence", "post_title": "[Python] 2 solutions: Right So Far, One pass - O(1) Space - Clean & Concise", "user": "hiepit", "upvotes": 94, "views": 2000, "problem_title": "increasing triplet subsequence", "number": 334, "acceptance": 0.427, "difficulty": "Medium", "__index_level_0__": 5735, "question": "Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.\n Example 1:\nInput: nums = [1,2,3,4,5]\nOutput: true\nExplanation: Any triplet where i < j < k is valid.\nExample 2:\nInput: nums = [5,4,3,2,1]\nOutput: false\nExplanation: No triplet exists.\nExample 3:\nInput: nums = [2,1,5,0,4,6]\nOutput: true\nExplanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.\n Constraints:\n1 <= nums.length <= 5 * 105\n-231 <= nums[i] <= 231 - 1\n Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?" }, { "post_href": "https://leetcode.com/problems/self-crossing/discuss/710582/Python3-complex-number-solution-Self-Crossing", "python_solutions": "class Solution:\n def isSelfCrossing(self, x: List[int]) -> bool:\n def intersect(p1, p2, p3, p4):\n v1 = p2 - p1\n if v1.real == 0:\n return p1.imag <= p3.imag <= p2.imag and p3.real <= p1.real <= p4.real\n return p3.imag <= p1.imag <= p4.imag and p1.real <= p3.real <= p2.real\n \n def overlap(p1, p2, p3, p4):\n v1 = p2 - p1\n if v1.real == 0:\n return min(p2.imag, p4.imag) >= max(p1.imag, p3.imag) and p1.real == p3.real\n return min(p2.real, p4.real) >= max(p1.real, p3.real) and p1.imag == p3.imag\n \n uv = complex(0, 1)\n p = complex(0, 0)\n segments = deque()\n for s in x:\n segments.append(sorted([p, (np := p + uv * s)], key=lambda x:(x.real, x.imag)))\n if len(segments) > 5 and intersect(*segments[-1], *segments[-6]):\n return True\n if len(segments) > 4 and overlap(*segments[-1], *segments[-5]):\n return True\n if len(segments) > 3 and intersect(*segments[-1], *segments[-4]):\n return True\n if len(segments) == 6:\n segments.popleft()\n p = np\n uv *= complex(0, 1)\n return False", "slug": "self-crossing", "post_title": "Python3 complex number solution - Self Crossing", "user": "r0bertz", "upvotes": 0, "views": 221, "problem_title": "self crossing", "number": 335, "acceptance": 0.293, "difficulty": "Hard", "__index_level_0__": 5790, "question": "You are given an array of integers distance.\nYou start at the 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.\nReturn true if your path crosses itself or false if it does not.\n Example 1:\nInput: distance = [2,1,1,2]\nOutput: true\nExplanation: The path crosses itself at the point (0, 1).\nExample 2:\nInput: distance = [1,2,3,4]\nOutput: false\nExplanation: The path does not cross itself at any point.\nExample 3:\nInput: distance = [1,1,1,2,1]\nOutput: true\nExplanation: The path crosses itself at the point (0, 0).\n Constraints:\n1 <= distance.length <= 105\n1 <= distance[i] <= 105" }, { "post_href": "https://leetcode.com/problems/palindrome-pairs/discuss/2585442/Intuitive-Python3-or-HashMap-or-95-Time-and-Space-or-O(N*W2)", "python_solutions": "class Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n backward, res = {}, []\n for i, word in enumerate(words):\n backward[word[::-1]] = i\n\n for i, word in enumerate(words):\n \n if word in backward and backward[word] != i:\n res.append([i, backward[word]])\n \n if word != \"\" and \"\" in backward and word == word[::-1]:\n res.append([i, backward[\"\"]])\n res.append([backward[\"\"], i])\n \n for j in range(len(word)):\n if word[j:] in backward and word[:j] == word[j-1::-1]:\n res.append([backward[word[j:]], i])\n if word[:j] in backward and word[j:] == word[:j-1:-1]:\n res.append([i, backward[word[:j]]])\n \n return res", "slug": "palindrome-pairs", "post_title": "Intuitive Python3 | HashMap | 95% Time & Space | O(N*W^2)", "user": "ryangrayson", "upvotes": 54, "views": 3000, "problem_title": "palindrome pairs", "number": 336, "acceptance": 0.352, "difficulty": "Hard", "__index_level_0__": 5791, "question": "You are given a 0-indexed array of unique strings words.\nA palindrome pair is a pair of integers (i, j) such that:\n0 <= i, j < words.length,\ni != j, and\nwords[i] + words[j] (the concatenation of the two strings) is a\npalindrome\n.\nReturn an array of all the palindrome pairs of words.\nYou must write an algorithm with O(sum of words[i].length) runtime complexity.\n Example 1:\nInput: words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\nOutput: [[0,1],[1,0],[3,2],[2,4]]\nExplanation: The palindromes are [\"abcddcba\",\"dcbaabcd\",\"slls\",\"llssssll\"]\nExample 2:\nInput: words = [\"bat\",\"tab\",\"cat\"]\nOutput: [[0,1],[1,0]]\nExplanation: The palindromes are [\"battab\",\"tabbat\"]\nExample 3:\nInput: words = [\"a\",\"\"]\nOutput: [[0,1],[1,0]]\nExplanation: The palindromes are [\"a\",\"a\"]\n Constraints:\n1 <= words.length <= 5000\n0 <= words[i].length <= 300\nwords[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/house-robber-iii/discuss/872676/Python-3-or-DFS-Backtracking-or-Explanation", "python_solutions": "class Solution:\n def rob(self, root: TreeNode) -> int:\n def dfs(node):\n if not node: return 0, 0\n left, right = dfs(node.left), dfs(node.right)\n v_take = node.val + left[1] + right[1]\n v_not_take = max(left) + max(right)\n return v_take, v_not_take\n return max(dfs(root))", "slug": "house-robber-iii", "post_title": "Python 3 | DFS, Backtracking | Explanation", "user": "idontknoooo", "upvotes": 5, "views": 439, "problem_title": "house robber iii", "number": 337, "acceptance": 0.539, "difficulty": "Medium", "__index_level_0__": 5801, "question": "The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.\nBesides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.\nGiven the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.\n Example 1:\nInput: root = [3,2,3,null,3,null,1]\nOutput: 7\nExplanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\nExample 2:\nInput: root = [3,4,5,1,3,null,1]\nOutput: 9\nExplanation: Maximum amount of money the thief can rob = 4 + 5 = 9.\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n0 <= Node.val <= 104" }, { "post_href": "https://leetcode.com/problems/counting-bits/discuss/466438/Python-clean-no-cheat-easy-to-understand.-Based-on-pattern.-Beats-90.", "python_solutions": "class Solution:\n def countBits(self, N: int) -> List[int]:\n stem = [0]\n while len(stem) < N+1:\n stem.extend([s + 1 for s in stem])\n \n return stem[:N+1]", "slug": "counting-bits", "post_title": "Python clean, no cheat, easy to understand. Based on pattern. Beats 90%.", "user": "kimonode", "upvotes": 18, "views": 1100, "problem_title": "counting bits", "number": 338, "acceptance": 0.753, "difficulty": "Easy", "__index_level_0__": 5817, "question": "Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i.\n Example 1:\nInput: n = 2\nOutput: [0,1,1]\nExplanation:\n0 --> 0\n1 --> 1\n2 --> 10\nExample 2:\nInput: n = 5\nOutput: [0,1,1,2,1,2]\nExplanation:\n0 --> 0\n1 --> 1\n2 --> 10\n3 --> 11\n4 --> 100\n5 --> 101\n Constraints:\n0 <= n <= 105\n Follow up:\nIt is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?\nCan you do it without using any built-in function (i.e., like __builtin_popcount in C++)?" }, { "post_href": "https://leetcode.com/problems/power-of-four/discuss/772261/Python3-1-liner-99.95-O(1)-explained", "python_solutions": "class Solution:\n def isPowerOfFour(self, num: int) -> bool:\n return num > 0 and not num & (num - 1) and len(bin(num)) % 2", "slug": "power-of-four", "post_title": "Python3 1 liner 99.95% O(1), explained", "user": "dangtrangiabao", "upvotes": 9, "views": 546, "problem_title": "power of four", "number": 342, "acceptance": 0.4579999999999999, "difficulty": "Easy", "__index_level_0__": 5879, "question": "Given an integer n, return true if it is a power of four. Otherwise, return false.\nAn integer n is a power of four, if there exists an integer x such that n == 4x.\n Example 1:\nInput: n = 16\nOutput: true\nExample 2:\nInput: n = 5\nOutput: false\nExample 3:\nInput: n = 1\nOutput: true\n Constraints:\n-231 <= n <= 231 - 1\n Follow up: Could you solve it without loops/recursion?" }, { "post_href": "https://leetcode.com/problems/integer-break/discuss/2830343/O(1)-oror-TC1-10-line-code", "python_solutions": "class Solution:\n def integerBreak(self, n: int) -> int:\n if(n<=3):\n return n-1\n n3=n//3\n r3=n%3\n if(r3==0):\n return 3**n3\n if(r3==1):\n r3=4\n n3-=1\n return r3*(3**n3)", "slug": "integer-break", "post_title": "O(1) || TC=1 10 line code", "user": "droj", "upvotes": 7, "views": 71, "problem_title": "integer break", "number": 343, "acceptance": 0.5539999999999999, "difficulty": "Medium", "__index_level_0__": 5926, "question": "Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.\nReturn the maximum product you can get.\n Example 1:\nInput: n = 2\nOutput: 1\nExplanation: 2 = 1 + 1, 1 \u00d7 1 = 1.\nExample 2:\nInput: n = 10\nOutput: 36\nExplanation: 10 = 3 + 3 + 4, 3 \u00d7 3 \u00d7 4 = 36.\n Constraints:\n2 <= n <= 58" }, { "post_href": "https://leetcode.com/problems/reverse-string/discuss/670137/Python-3-~actually~-easiest-solution", "python_solutions": "class Solution:\n def reverseString(self, s: List[str]) -> None:\n s[:] = s[::-1]", "slug": "reverse-string", "post_title": "Python 3 ~actually~ easiest solution", "user": "drblessing", "upvotes": 77, "views": 6800, "problem_title": "reverse string", "number": 344, "acceptance": 0.762, "difficulty": "Easy", "__index_level_0__": 5954, "question": "Write a function that reverses a string. The input string is given as an array of characters s.\nYou must do this by modifying the input array in-place with O(1) extra memory.\n Example 1:\nInput: s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\nOutput: [\"o\",\"l\",\"l\",\"e\",\"h\"]\nExample 2:\nInput: s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\nOutput: [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n Constraints:\n1 <= s.length <= 105\ns[i] is a printable ascii character." }, { "post_href": "https://leetcode.com/problems/reverse-vowels-of-a-string/discuss/1164745/Python-Solution-oror-99.58-faster-oror-86.96-less-memory", "python_solutions": "class Solution:\n def reverseVowels(self, s: str) -> str:\n s = list(s)\n left = 0\n right = len(s) - 1\n m = 'aeiouAEIOU'\n while left < right:\n if s[left] in m and s[right] in m:\n \n s[left], s[right] = s[right], s[left]\n \n left += 1; right -= 1\n \n elif s[left] not in m:\n left += 1\n \n elif s[right] not in m:\n right -= 1\n \n return ''.join(s)", "slug": "reverse-vowels-of-a-string", "post_title": "Python Solution || 99.58% faster || 86.96% less memory", "user": "KiranUpase", "upvotes": 22, "views": 1100, "problem_title": "reverse vowels of a string", "number": 345, "acceptance": 0.498, "difficulty": "Easy", "__index_level_0__": 6016, "question": "Given a string s, reverse only all the vowels in the string and return it.\nThe vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.\n Example 1:\nInput: s = \"hello\"\nOutput: \"holle\"\nExample 2:\nInput: s = \"leetcode\"\nOutput: \"leotcede\"\n Constraints:\n1 <= s.length <= 3 * 105\ns consist of printable ASCII characters." }, { "post_href": "https://leetcode.com/problems/top-k-frequent-elements/discuss/1928198/Python-Simple-Python-Solution-Using-Dictionary-(-HashMap-)", "python_solutions": "class Solution:\n\tdef topKFrequent(self, nums: List[int], k: int) -> List[int]:\n\n\t\tfrequency = {}\n\n\t\tfor num in nums:\n\n\t\t\tif num not in frequency:\n\n\t\t\t\tfrequency[num] = 1\n\n\t\t\telse:\n\n\t\t\t\tfrequency[num] = frequency[num] + 1\n\n\t\tfrequency = dict(sorted(frequency.items(), key=lambda x: x[1], reverse=True))\n\n\t\tresult = list(frequency.keys())[:k]\n\n\t\treturn result", "slug": "top-k-frequent-elements", "post_title": "[ Python ] \u2705\u2705 Simple Python Solution Using Dictionary ( HashMap ) \u270c\ud83d\udc4d", "user": "ASHOK_KUMAR_MEGHVANSHI", "upvotes": 24, "views": 2800, "problem_title": "top k frequent elements", "number": 347, "acceptance": 0.648, "difficulty": "Medium", "__index_level_0__": 6072, "question": "Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.\n Example 1:\nInput: nums = [1,1,1,2,2,3], k = 2\nOutput: [1,2]\nExample 2:\nInput: nums = [1], k = 1\nOutput: [1]\n Constraints:\n1 <= nums.length <= 105\n-104 <= nums[i] <= 104\nk is in the range [1, the number of unique elements in the array].\nIt is guaranteed that the answer is unique.\n Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size." }, { "post_href": "https://leetcode.com/problems/intersection-of-two-arrays/discuss/2270388/PYTHON-3-SIMPLE-or-EASY-TO-UNDERSTAND", "python_solutions": "class Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n a = []\n for i in nums1:\n if i not in a and i in nums2:\n a.append(i)\n return a", "slug": "intersection-of-two-arrays", "post_title": "[PYTHON 3] SIMPLE | EASY TO UNDERSTAND", "user": "omkarxpatel", "upvotes": 5, "views": 135, "problem_title": "intersection of two arrays", "number": 349, "acceptance": 0.7040000000000001, "difficulty": "Easy", "__index_level_0__": 6131, "question": "Given two integer arrays nums1 and nums2, return an array of their\nintersection\n. Each element in the result must be unique and you may return the result in any order.\n Example 1:\nInput: nums1 = [1,2,2,1], nums2 = [2,2]\nOutput: [2]\nExample 2:\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [9,4]\nExplanation: [4,9] is also accepted.\n Constraints:\n1 <= nums1.length, nums2.length <= 1000\n0 <= nums1[i], nums2[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/1231807/easy-or-two-pointer-method-or-python", "python_solutions": "class Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \n nums1.sort()\n nums2.sort()\n \n \n one=0\n two=0\n \n ans=[]\n \n while one < len(nums1) and two < len(nums2):\n \n if nums1[one] < nums2[two]:\n one+=1\n elif nums2[two] < nums1[one]:\n two+=1\n else:\n \n ans.append(nums1[one])\n one+=1\n two+=1\n return ans", "slug": "intersection-of-two-arrays-ii", "post_title": "easy | two pointer method | python", "user": "chikushen99", "upvotes": 23, "views": 1300, "problem_title": "intersection of two arrays ii", "number": 350, "acceptance": 0.556, "difficulty": "Easy", "__index_level_0__": 6183, "question": "Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.\n Example 1:\nInput: nums1 = [1,2,2,1], nums2 = [2,2]\nOutput: [2,2]\nExample 2:\nInput: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\nOutput: [4,9]\nExplanation: [9,4] is also accepted.\n Constraints:\n1 <= nums1.length, nums2.length <= 1000\n0 <= nums1[i], nums2[i] <= 1000\n Follow up:\nWhat if the given array is already sorted? How would you optimize your algorithm?\nWhat if nums1's size is small compared to nums2's size? Which algorithm is better?\nWhat if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?" }, { "post_href": "https://leetcode.com/problems/russian-doll-envelopes/discuss/2071626/Python-LIS-based-approach", "python_solutions": "class Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n envelopes.sort(key=lambda x: (x[0], -x[1]))\n \n res = []\t\t\n\t\t# Perform LIS\n for _, h in envelopes:\n l,r=0,len(res)-1\n\t\t\t# find the insertion point in the Sort order\n while l <= r:\n mid=(l+r)>>1\n if res[mid]>=h:\n r=mid-1\n else:\n l=mid+1 \n idx = l\n if idx == len(res):\n res.append(h)\n else:\n res[idx]=h\n return len(res)", "slug": "russian-doll-envelopes", "post_title": "Python LIS based approach", "user": "constantine786", "upvotes": 19, "views": 1800, "problem_title": "russian doll envelopes", "number": 354, "acceptance": 0.382, "difficulty": "Hard", "__index_level_0__": 6234, "question": "You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.\nOne 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.\nReturn the maximum number of envelopes you can Russian doll (i.e., put one inside the other).\nNote: You cannot rotate an envelope.\n Example 1:\nInput: envelopes = [[5,4],[6,4],[6,7],[2,3]]\nOutput: 3\nExplanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).\nExample 2:\nInput: envelopes = [[1,1],[1,1],[1,1]]\nOutput: 1\n Constraints:\n1 <= envelopes.length <= 105\nenvelopes[i].length == 2\n1 <= wi, hi <= 105" }, { "post_href": "https://leetcode.com/problems/count-numbers-with-unique-digits/discuss/2828071/Python3-Mathematics-approach.-Explained-in-details.-Step-by-step", "python_solutions": "class Solution:\n def countNumbersWithUniqueDigits(self, n: int) -> int:\n if n == 0: return 1\n if n == 1: return 10\n\n res = 91\n mult = 8\n comb = 81\n for i in range(n - 2):\n comb *= mult\n mult -= 1\n res += comb\n\n return res", "slug": "count-numbers-with-unique-digits", "post_title": "Python3 Mathematics approach. Explained in details. Step-by-step", "user": "Alex_Gr", "upvotes": 0, "views": 2, "problem_title": "count numbers with unique digits", "number": 357, "acceptance": 0.516, "difficulty": "Medium", "__index_level_0__": 6239, "question": "Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.\n Example 1:\nInput: n = 2\nOutput: 91\nExplanation: The answer should be the total numbers in the range of 0 \u2264 x < 100, excluding 11,22,33,44,55,66,77,88,99\nExample 2:\nInput: n = 0\nOutput: 1\n Constraints:\n0 <= n <= 8" }, { "post_href": "https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/2488882/Solution-In-Python", "python_solutions": "class Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n ans = float(\"-inf\")\n m, n = len(matrix), len(matrix[0])\n for i in range(n):\n lstSum = [0] * m\n for j in range(i, n):\n currSum = 0\n curlstSum = [0]\n for t in range(m):\n lstSum[t] += matrix[t][j]\n currSum += lstSum[t]\n pos = bisect_left(curlstSum, currSum - k)\n if pos < len(curlstSum):\n if curlstSum[pos] == currSum - k:\n return k\n else:\n ans = max(ans, currSum - curlstSum[pos])\n insort(curlstSum, currSum)\n return ans", "slug": "max-sum-of-rectangle-no-larger-than-k", "post_title": "Solution In Python", "user": "AY_", "upvotes": 8, "views": 1200, "problem_title": "max sum of rectangle no larger than k", "number": 363, "acceptance": 0.441, "difficulty": "Hard", "__index_level_0__": 6250, "question": "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.\nIt is guaranteed that there will be a rectangle with a sum no larger than k.\n Example 1:\nInput: matrix = [[1,0,1],[0,-2,3]], k = 2\nOutput: 2\nExplanation: 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).\nExample 2:\nInput: matrix = [[2,2,-1]], k = 3\nOutput: 3\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= 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?" }, { "post_href": "https://leetcode.com/problems/water-and-jug-problem/discuss/393886/Solution-in-Python-3-(beats-~100)-(one-line)-(Math-Solution)", "python_solutions": "class Solution:\n def canMeasureWater(self, x: int, y: int, z: int) -> bool:\n return False if x + y < z else True if x + y == 0 else not z % math.gcd(x,y)\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "water-and-jug-problem", "post_title": "Solution in Python 3 (beats ~100%) (one line) (Math Solution)", "user": "junaidmansuri", "upvotes": 5, "views": 1300, "problem_title": "water and jug problem", "number": 365, "acceptance": 0.367, "difficulty": "Medium", "__index_level_0__": 6254, "question": "You are given two jugs with capacities x liters and y liters. You have an infinite water supply. Return whether the total amount of water in both jugs may reach target using the following operations:\nFill either jug completely with water.\nCompletely empty either jug.\nPour water from one jug into another until the receiving jug is full, or the transferring jug is empty.\n Example 1:\nInput: x = 3, y = 5, target = 4\nOutput: true\nExplanation:\nFollow these steps to reach a total of 4 liters:\nFill the 5-liter jug (0, 5).\nPour from the 5-liter jug into the 3-liter jug, leaving 2 liters (3, 2).\nEmpty the 3-liter jug (0, 2).\nTransfer the 2 liters from the 5-liter jug to the 3-liter jug (2, 0).\nFill the 5-liter jug again (2, 5).\nPour from the 5-liter jug into the 3-liter jug until the 3-liter jug is full. This leaves 4 liters in the 5-liter jug (3, 4).\nEmpty the 3-liter jug. Now, you have exactly 4 liters in the 5-liter jug (0, 4).\nReference: The Die Hard example.\nExample 2:\nInput: x = 2, y = 6, target = 5\nOutput: false\nExample 3:\nInput: x = 1, y = 2, target = 3\nOutput: true\nExplanation: Fill both jugs. The total amount of water in both jugs is equal to 3 now.\n Constraints:\n1 <= x, y, target <= 103" }, { "post_href": "https://leetcode.com/problems/valid-perfect-square/discuss/1063963/100-Python-One-Liner-UPVOTE-PLEASE", "python_solutions": "class Solution:\n def isPerfectSquare(self, num: int) -> bool:\n return int(num**0.5) == num**0.5", "slug": "valid-perfect-square", "post_title": "100% Python One-Liner UPVOTE PLEASE", "user": "1coder", "upvotes": 6, "views": 451, "problem_title": "valid perfect square", "number": 367, "acceptance": 0.433, "difficulty": "Easy", "__index_level_0__": 6265, "question": "Given a positive integer num, return true if num is a perfect square or false otherwise.\nA perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.\nYou must not use any built-in library function, such as sqrt.\n Example 1:\nInput: num = 16\nOutput: true\nExplanation: We return true because 4 * 4 = 16 and 4 is an integer.\nExample 2:\nInput: num = 14\nOutput: false\nExplanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.\n Constraints:\n1 <= num <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/largest-divisible-subset/discuss/1127633/Python-Dynamic-Programming-with-comments", "python_solutions": "class Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n if not nums or len(nums) == 0:\n return []\n\n # since we are doing a \"subset\" question\n # sorting does not make any differences\n nums.sort()\n n = len(nums)\n\n # initilization\n # f[i] represents the size of LDS ended with nums[i]\n f = [1 for _ in range(n)]\n for i in range(1, n):\n for j in range(i):\n # since we have already sorted,\n # then nums[j] % nums[i] will never equals zero\n # unless nums[i] == nums[j]\n if nums[i] % nums[j] == 0:\n f[i] = max(f[i], f[j] + 1)\n\n # extract result from dp array\n max_size = max(f)\n max_idx = f.index(max_size) # since we can return one of the largest\n prev_num, prev_size = nums[max_idx], f[max_idx]\n res = [prev_num]\n for curr_idx in range(max_idx, -1, -1):\n if prev_num % nums[curr_idx] == 0 and f[curr_idx] == prev_size - 1:\n # update\n res.append(nums[curr_idx])\n prev_num = nums[curr_idx]\n prev_size = f[curr_idx]\n\n return res[::-1]", "slug": "largest-divisible-subset", "post_title": "Python Dynamic Programming with comments", "user": "zna2", "upvotes": 3, "views": 227, "problem_title": "largest divisible subset", "number": 368, "acceptance": 0.413, "difficulty": "Medium", "__index_level_0__": 6316, "question": "Given a set of distinct positive integers nums, return the largest subset answer such that every pair (answer[i], answer[j]) of elements in this subset satisfies:\nanswer[i] % answer[j] == 0, or\nanswer[j] % answer[i] == 0\nIf there are multiple solutions, return any of them.\n Example 1:\nInput: nums = [1,2,3]\nOutput: [1,2]\nExplanation: [1,3] is also accepted.\nExample 2:\nInput: nums = [1,2,4,8]\nOutput: [1,2,4,8]\n Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 2 * 109\nAll the integers in nums are unique." }, { "post_href": "https://leetcode.com/problems/sum-of-two-integers/discuss/1876632/Python-one-line-solution-using-the-logic-of-logs-and-powers", "python_solutions": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n return int(math.log2(2**a * 2**b))", "slug": "sum-of-two-integers", "post_title": "Python one line solution using the logic of logs and powers", "user": "alishak1999", "upvotes": 7, "views": 596, "problem_title": "sum of two integers", "number": 371, "acceptance": 0.507, "difficulty": "Medium", "__index_level_0__": 6324, "question": "Given two integers a and b, return the sum of the two integers without using the operators + and -.\n Example 1:\nInput: a = 1, b = 2\nOutput: 3\nExample 2:\nInput: a = 2, b = 3\nOutput: 5\n Constraints:\n-1000 <= a, b <= 1000" }, { "post_href": "https://leetcode.com/problems/super-pow/discuss/400893/Python-3-(With-Explanation)-(Handles-All-Test-Cases)-(one-line)-(beats-~97)", "python_solutions": "class Solution:\n def superPow(self, a: int, b: List[int]) -> int:\n return (a % 1337)**(1140 + int(''.join(map(str, b))) % 1140) % 1337\n\t\t\n\t\t\n- Junaid Mansuri", "slug": "super-pow", "post_title": "Python 3 (With Explanation) (Handles All Test Cases) (one line) (beats ~97%)", "user": "junaidmansuri", "upvotes": 11, "views": 1900, "problem_title": "super pow", "number": 372, "acceptance": 0.371, "difficulty": "Medium", "__index_level_0__": 6343, "question": "Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.\n Example 1:\nInput: a = 2, b = [3]\nOutput: 8\nExample 2:\nInput: a = 2, b = [1,0]\nOutput: 1024\nExample 3:\nInput: a = 1, b = [4,3,3,8,5,2]\nOutput: 1\n Constraints:\n1 <= a <= 231 - 1\n1 <= b.length <= 2000\n0 <= b[i] <= 9\nb does not contain leading zeros." }, { "post_href": "https://leetcode.com/problems/find-k-pairs-with-smallest-sums/discuss/1701122/Python-Simple-heap-solution-explained", "python_solutions": "class Solution:\n def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n hq = []\n heapq.heapify(hq)\n \n # add all the pairs that we can form with\n # all the (first k) items in nums1 with the first\n # item in nums2\n for i in range(min(len(nums1), k)):\n heapq.heappush(hq, (nums1[i]+nums2[0], nums1[i], nums2[0], 0))\n\n # since the smallest pair will\n # be the first element from both nums1 and nums2. We'll\n # start with that and then subsequently, we'll pop it out\n # from the heap and also insert the pair of the current\n # element from nums1 with the next nums2 element\n out = []\n while k > 0 and hq:\n _, n1, n2, idx = heapq.heappop(hq)\n out.append((n1, n2))\n if idx + 1 < len(nums2):\n # the heap will ensure that the smallest element\n # based on the sum will remain on top and the\n # next iteration will give us the pair we require\n heapq.heappush(hq, (n1+nums2[idx+1], n1, nums2[idx+1], idx+1))\n k -= 1\n \n return out", "slug": "find-k-pairs-with-smallest-sums", "post_title": "[Python] Simple heap solution explained", "user": "buccatini", "upvotes": 11, "views": 1400, "problem_title": "find k pairs with smallest sums", "number": 373, "acceptance": 0.3829999999999999, "difficulty": "Medium", "__index_level_0__": 6363, "question": "You are given two integer arrays nums1 and nums2 sorted in non-decreasing order and an integer k.\nDefine a pair (u, v) which consists of one element from the first array and one element from the second array.\nReturn the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.\n Example 1:\nInput: nums1 = [1,7,11], nums2 = [2,4,6], k = 3\nOutput: [[1,2],[1,4],[1,6]]\nExplanation: The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]\nExample 2:\nInput: nums1 = [1,1,2], nums2 = [1,2,3], k = 2\nOutput: [[1,1],[1,1]]\nExplanation: The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]\n Constraints:\n1 <= nums1.length, nums2.length <= 105\n-109 <= nums1[i], nums2[i] <= 109\nnums1 and nums2 both are sorted in non-decreasing order.\n1 <= k <= 104\nk <= nums1.length * nums2.length" }, { "post_href": "https://leetcode.com/problems/guess-number-higher-or-lower/discuss/2717871/DONT-TRY-THIS-CODE-or-ONE-LINE-PYTHON-CODE", "python_solutions": "class Solution:\n def guessNumber(self, n: int) -> int:\n return __pick__", "slug": "guess-number-higher-or-lower", "post_title": "DONT TRY THIS CODE | ONE LINE PYTHON CODE", "user": "raghavdabra", "upvotes": 9, "views": 441, "problem_title": "guess number higher or lower", "number": 374, "acceptance": 0.514, "difficulty": "Easy", "__index_level_0__": 6377, "question": "We are playing the Guess Game. The game is as follows:\nI pick a number from 1 to n. You have to guess which number I picked.\nEvery time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.\nYou call a pre-defined API int guess(int num), which returns three possible results:\n-1: Your guess is higher than the number I picked (i.e. num > pick).\n1: Your guess is lower than the number I picked (i.e. num < pick).\n0: your guess is equal to the number I picked (i.e. num == pick).\nReturn the number that I picked.\n Example 1:\nInput: n = 10, pick = 6\nOutput: 6\nExample 2:\nInput: n = 1, pick = 1\nOutput: 1\nExample 3:\nInput: n = 2, pick = 1\nOutput: 1\n Constraints:\n1 <= n <= 231 - 1\n1 <= pick <= n" }, { "post_href": "https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/1510747/Python-DP-beat-97.52-in-time-99-in-memory-(with-explanation)", "python_solutions": "class Solution:\n def getMoneyAmount(self, n: int) -> int:\n if n == 1:\n return 1\n starting_index = 1 if n % 2 == 0 else 2\n selected_nums = [i for i in range(starting_index, n, 2)]\n selected_nums_length = len(selected_nums)\n dp = [[0] * selected_nums_length for _ in range(selected_nums_length)]\n\n for i in range(selected_nums_length):\n dp[i][i] = selected_nums[i]\n\n for length in range(2, selected_nums_length + 1):\n for i in range(selected_nums_length - length + 1):\n j = i + length - 1\n dp[i][j] = float(\"inf\")\n for k in range(i, j + 1):\n dp_left = dp[i][k - 1] if k != 0 else 0\n dp_right = dp[k + 1][j] if k != j else 0\n dp[i][j] = min(dp[i][j], selected_nums[k] + max(dp_left, dp_right))\n\n return dp[0][-1]", "slug": "guess-number-higher-or-lower-ii", "post_title": "[Python] DP, beat 97.52% in time, 99% in memory (with explanation)", "user": "wingskh", "upvotes": 31, "views": 1100, "problem_title": "guess number higher or lower ii", "number": 375, "acceptance": 0.465, "difficulty": "Medium", "__index_level_0__": 6399, "question": "We are playing the Guessing Game. The game will work as follows:\nI pick a number between 1 and n.\nYou guess a number.\nIf you guess the right number, you win the game.\nIf you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.\nEvery time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game.\nGiven a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.\n Example 1:\nInput: n = 10\nOutput: 16\nExplanation: The winning strategy is as follows:\n- The range is [1,10]. Guess 7.\n - If this is my number, your total is $0. Otherwise, you pay $7.\n - If my number is higher, the range is [8,10]. Guess 9.\n - If this is my number, your total is $7. Otherwise, you pay $9.\n - If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.\n - If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.\n - If my number is lower, the range is [1,6]. Guess 3.\n - If this is my number, your total is $7. Otherwise, you pay $3.\n - If my number is higher, the range is [4,6]. Guess 5.\n - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.\n - If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.\n - If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.\n - If my number is lower, the range is [1,2]. Guess 1.\n - If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.\n - If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.\nThe worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.\nExample 2:\nInput: n = 1\nOutput: 0\nExplanation: There is only one possible number, so you can guess 1 and not have to pay anything.\nExample 3:\nInput: n = 2\nOutput: 1\nExplanation: There are two possible numbers, 1 and 2.\n- Guess 1.\n - If this is my number, your total is $0. Otherwise, you pay $1.\n - If my number is higher, it must be 2. Guess 2. Your total is $1.\nThe worst case is that you pay $1.\n Constraints:\n1 <= n <= 200" }, { "post_href": "https://leetcode.com/problems/wiggle-subsequence/discuss/2230152/Beats-73.3-Simple-Python-Solution-Greedy", "python_solutions": "class Solution:\n def wiggleMaxLength(self, nums: List[int]) -> int:\n length = 0\n curr = 0\n \n for i in range(len(nums) - 1):\n if curr == 0 and nums[i + 1] - nums[i] != 0:\n length += 1\n curr = nums[i + 1] - nums[i]\n \n if curr < 0 and nums[i + 1] - nums[i] > 0:\n length += 1\n curr = nums[i + 1] - nums[i]\n \n elif curr > 0 and nums[i + 1] - nums[i] < 0:\n length += 1\n curr = nums[i + 1] - nums[i]\n \n else:\n continue\n \n return length + 1", "slug": "wiggle-subsequence", "post_title": "Beats 73.3% - Simple Python Solution - Greedy", "user": "7yler", "upvotes": 3, "views": 183, "problem_title": "wiggle subsequence", "number": 376, "acceptance": 0.482, "difficulty": "Medium", "__index_level_0__": 6406, "question": "A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.\nFor example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.\nIn contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.\nA subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.\nGiven an integer array nums, return the length of the longest wiggle subsequence of nums.\n Example 1:\nInput: nums = [1,7,4,9,2,5]\nOutput: 6\nExplanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\nExample 2:\nInput: nums = [1,17,5,10,13,15,10,5,16,8]\nOutput: 7\nExplanation: There are several subsequences that achieve this length.\nOne is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).\nExample 3:\nInput: nums = [1,2,3,4,5,6,7,8,9]\nOutput: 2\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] <= 1000\n Follow up: Could you solve this in O(n) time?" }, { "post_href": "https://leetcode.com/problems/combination-sum-iv/discuss/1272869/Python-3-Faster-than-96-(Super-Simple!)", "python_solutions": "class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n waysToAdd = [0 for x in range(target+1)]\n waysToAdd[0] = 1\n \n for i in range(min(nums), target+1):\n waysToAdd[i] = sum(waysToAdd[i-num] for num in nums if i-num >= 0)\n \n return waysToAdd[-1]", "slug": "combination-sum-iv", "post_title": "[Python 3] Faster than 96% (Super Simple!)", "user": "jodoko", "upvotes": 3, "views": 323, "problem_title": "combination sum iv", "number": 377, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 6438, "question": "Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.\nThe test cases are generated so that the answer can fit in a 32-bit integer.\n Example 1:\nInput: nums = [1,2,3], target = 4\nOutput: 7\nExplanation:\nThe possible combination ways are:\n(1, 1, 1, 1)\n(1, 1, 2)\n(1, 2, 1)\n(1, 3)\n(2, 1, 1)\n(2, 2)\n(3, 1)\nNote that different sequences are counted as different combinations.\nExample 2:\nInput: nums = [9], target = 3\nOutput: 0\n Constraints:\n1 <= nums.length <= 200\n1 <= nums[i] <= 1000\nAll the elements of nums are unique.\n1 <= target <= 1000\n Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?" }, { "post_href": "https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/2233868/Simple-yet-best-Interview-Code-or-Python-Code-beats-90", "python_solutions": "class Solution:\n def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n \n m = len(matrix)\n n = len(matrix[0])\n \n def count(m):\n c = 0 # count of element less than equals to 'm'\n i = n-1\n j = 0\n \n while i >= 0 and j < n:\n if matrix[i][j] > m:\n i -= 1\n else:\n c += i+1\n j += 1\n return c\n \n \n low = matrix[0][0]\n high = matrix[n-1][n-1]\n \n while low <= high:\n m = (low+high)//2\n cnt = count(m)\n if cnt < k:\n low = m + 1\n else:\n cnt1 = count(m-1)\n if cnt1 < k:\n return m\n high = m-1\n return 0", "slug": "kth-smallest-element-in-a-sorted-matrix", "post_title": "\u2705 Simple yet best Interview Code | Python Code beats 90%", "user": "reinkarnation", "upvotes": 5, "views": 532, "problem_title": "kth smallest element in a sorted matrix", "number": 378, "acceptance": 0.616, "difficulty": "Medium", "__index_level_0__": 6467, "question": "Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.\nNote that it is the kth smallest element in the sorted order, not the kth distinct element.\nYou must find a solution with a memory complexity better than O(n2).\n Example 1:\nInput: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\nOutput: 13\nExplanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13\nExample 2:\nInput: matrix = [[-5]], k = 1\nOutput: -5\n Constraints:\nn == matrix.length == matrix[i].length\n1 <= n <= 300\n-109 <= matrix[i][j] <= 109\nAll the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.\n1 <= k <= n2\n Follow up:\nCould you solve the problem with a constant memory (i.e., O(1) memory complexity)?\nCould you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun." }, { "post_href": "https://leetcode.com/problems/linked-list-random-node/discuss/811617/Python3-reservoir-sampling", "python_solutions": "class Solution:\n\n def __init__(self, head: ListNode):\n \"\"\"\n @param head The linked list's head.\n Note that the head is guaranteed to be not null, so it contains at least one node.\n \"\"\"\n self.head = head # store head of linked list \n\n def getRandom(self) -> int:\n \"\"\"\n Returns a random node's value.\n \"\"\"\n cnt = 0\n node = self.head \n while node: \n cnt += 1\n if randint(1, cnt) == cnt: ans = node.val # reservoir sampling \n node = node.next \n return ans", "slug": "linked-list-random-node", "post_title": "[Python3] reservoir sampling", "user": "ye15", "upvotes": 4, "views": 395, "problem_title": "linked list random node", "number": 382, "acceptance": 0.596, "difficulty": "Medium", "__index_level_0__": 6513, "question": "Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.\nImplement the Solution class:\nSolution(ListNode head) Initializes the object with the head of the singly-linked list head.\nint getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.\n Example 1:\nInput\n[\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n[[[1, 2, 3]], [], [], [], [], []]\nOutput\n[null, 1, 3, 2, 2, 3]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.getRandom(); // return 1\nsolution.getRandom(); // return 3\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 2\nsolution.getRandom(); // return 3\n// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n Constraints:\nThe number of nodes in the linked list will be in the range [1, 104].\n-104 <= Node.val <= 104\nAt most 104 calls will be made to getRandom.\n Follow up:\nWhat if the linked list is extremely large and its length is unknown to you?\nCould you solve this efficiently without using extra space?" }, { "post_href": "https://leetcode.com/problems/ransom-note/discuss/1346131/Easiest-python-solution-faster-than-95", "python_solutions": "class Solution:\n def canConstruct(self, ransomNote, magazine):\n for i in set(ransomNote):\n if magazine.count(i) < ransomNote.count(i):\n return False\n return True", "slug": "ransom-note", "post_title": "Easiest python solution, faster than 95%", "user": "mqueue", "upvotes": 35, "views": 3500, "problem_title": "ransom note", "number": 383, "acceptance": 0.5760000000000001, "difficulty": "Easy", "__index_level_0__": 6520, "question": "Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.\nEach letter in magazine can only be used once in ransomNote.\n Example 1:\nInput: ransomNote = \"a\", magazine = \"b\"\nOutput: false\nExample 2:\nInput: ransomNote = \"aa\", magazine = \"ab\"\nOutput: false\nExample 3:\nInput: ransomNote = \"aa\", magazine = \"aab\"\nOutput: true\n Constraints:\n1 <= ransomNote.length, magazine.length <= 105\nransomNote and magazine consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/shuffle-an-array/discuss/1673643/Python-or-Best-Optimal-Approach", "python_solutions": "class Solution:\n\tdef __init__(self, nums: List[int]):\n\t\tself.arr = nums[:] # Deep Copy, Can also use Shallow Copy concept!\n\t\t# self.arr = nums # Shallow Copy would be something like this!\n\n\tdef reset(self) -> List[int]:\n\t\treturn self.arr\n\n\tdef shuffle(self) -> List[int]:\n\t\tans = self.arr[:]\n\t\tfor i in range(len(ans)):\n\t\t\tswp_num = random.randrange(i, len(ans)) # Fisher-Yates Algorithm\n\t\t\tans[i], ans[swp_num] = ans[swp_num], ans[i]\n\t\treturn ans", "slug": "shuffle-an-array", "post_title": "{ Python } | Best Optimal Approach \u2714", "user": "leet_satyam", "upvotes": 6, "views": 725, "problem_title": "shuffle an array", "number": 384, "acceptance": 0.5770000000000001, "difficulty": "Medium", "__index_level_0__": 6569, "question": "Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling.\nImplement the Solution class:\nSolution(int[] nums) Initializes the object with the integer array nums.\nint[] reset() Resets the array to its original configuration and returns it.\nint[] shuffle() Returns a random shuffling of the array.\n Example 1:\nInput\n[\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\n[[[1, 2, 3]], [], [], []]\nOutput\n[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n\nExplanation\nSolution solution = new Solution([1, 2, 3]);\nsolution.shuffle(); // Shuffle the array [1,2,3] and return its result.\n // Any permutation of [1,2,3] must be equally likely to be returned.\n // Example: return [3, 1, 2]\nsolution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\nsolution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\n Constraints:\n1 <= nums.length <= 50\n-106 <= nums[i] <= 106\nAll the elements of nums are unique.\nAt most 104 calls in total will be made to reset and shuffle." }, { "post_href": "https://leetcode.com/problems/mini-parser/discuss/875743/Python3-a-concise-recursive-solution", "python_solutions": "class Solution:\n def deserialize(self, s: str) -> NestedInteger:\n if not s: return NestedInteger()\n if not s.startswith(\"[\"): return NestedInteger(int(s)) # integer \n ans = NestedInteger()\n s = s[1:-1] # strip outer \"[\" and \"]\"\n if s: \n ii = op = 0 \n for i in range(len(s)): \n if s[i] == \"[\": op += 1\n if s[i] == \"]\": op -= 1\n if s[i] == \",\" and op == 0: \n ans.add(self.deserialize(s[ii:i]))\n ii = i+1\n ans.add(self.deserialize(s[ii:i+1]))\n return ans", "slug": "mini-parser", "post_title": "[Python3] a concise recursive solution", "user": "ye15", "upvotes": 2, "views": 178, "problem_title": "mini parser", "number": 385, "acceptance": 0.366, "difficulty": "Medium", "__index_level_0__": 6590, "question": "Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger.\nEach element is either an integer or a list whose elements may also be integers or other lists.\n Example 1:\nInput: s = \"324\"\nOutput: 324\nExplanation: You should return a NestedInteger object which contains a single integer 324.\nExample 2:\nInput: s = \"[123,[456,[789]]]\"\nOutput: [123,[456,[789]]]\nExplanation: Return a NestedInteger object containing a nested list with 2 elements:\n1. An integer containing value 123.\n2. A nested list containing two elements:\n i. An integer containing value 456.\n ii. A nested list with one element:\n a. An integer containing value 789\n Constraints:\n1 <= s.length <= 5 * 104\ns consists of digits, square brackets \"[]\", negative sign '-', and commas ','.\ns is the serialization of valid NestedInteger.\nAll the values in the input are in the range [-106, 106]." }, { "post_href": "https://leetcode.com/problems/lexicographical-numbers/discuss/2053392/Python-oneliner", "python_solutions": "class Solution:\n def lexicalOrder(self, n: int) -> List[int]:\n return sorted([x for x in range(1,n+1)],key=lambda x: str(x))", "slug": "lexicographical-numbers", "post_title": "Python oneliner", "user": "StikS32", "upvotes": 1, "views": 135, "problem_title": "lexicographical numbers", "number": 386, "acceptance": 0.608, "difficulty": "Medium", "__index_level_0__": 6592, "question": "Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.\nYou must write an algorithm that runs in O(n) time and uses O(1) extra space. \n Example 1:\nInput: n = 13\nOutput: [1,10,11,12,13,2,3,4,5,6,7,8,9]\nExample 2:\nInput: n = 2\nOutput: [1,2]\n Constraints:\n1 <= n <= 5 * 104" }, { "post_href": "https://leetcode.com/problems/first-unique-character-in-a-string/discuss/1793386/Python-Simple-Python-Solution-With-Two-Approach", "python_solutions": "class Solution:\n\tdef firstUniqChar(self, s: str) -> int:\n\n\t\tfor i in range(len(s)):\n\n\t\t\tif s[i] not in s[:i] and s[i] not in s[i+1:]:\n\n\t\t\t\treturn i\n\n\t\treturn -1", "slug": "first-unique-character-in-a-string", "post_title": "[ Python ] \u2705\u2705 Simple Python Solution With Two Approach \ud83e\udd73\u270c\ud83d\udc4d", "user": "ASHOK_KUMAR_MEGHVANSHI", "upvotes": 28, "views": 1600, "problem_title": "first unique character in a string", "number": 387, "acceptance": 0.59, "difficulty": "Easy", "__index_level_0__": 6607, "question": "Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.\n Example 1:\nInput: s = \"leetcode\"\nOutput: 0\nExample 2:\nInput: s = \"loveleetcode\"\nOutput: 2\nExample 3:\nInput: s = \"aabb\"\nOutput: -1\n Constraints:\n1 <= s.length <= 105\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/longest-absolute-file-path/discuss/812407/Python-3-or-Stack-or-Explanation", "python_solutions": "class Solution:\n def lengthLongestPath(self, s: str) -> int:\n paths, stack, ans = s.split('\\n'), [], 0\n for path in paths:\n p = path.split('\\t')\n depth, name = len(p) - 1, p[-1]\n l = len(name)\n while stack and stack[-1][1] >= depth: stack.pop()\n if not stack: stack.append((l, depth))\n else: stack.append((l+stack[-1][0], depth))\n if '.' in name: ans = max(ans, stack[-1][0] + stack[-1][1]) \n return ans", "slug": "longest-absolute-file-path", "post_title": "Python 3 | Stack | Explanation", "user": "idontknoooo", "upvotes": 23, "views": 1900, "problem_title": "longest absolute file path", "number": 388, "acceptance": 0.465, "difficulty": "Medium", "__index_level_0__": 6655, "question": "Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:\nHere, we have dir as the only directory in the root. dir contains two subdirectories, subdir1 and subdir2. subdir1 contains a file file1.ext and subdirectory subsubdir1. subdir2 contains a subdirectory subsubdir2, which contains a file file2.ext.\nIn text form, it looks like this (with \u27f6 representing the tab character):\ndir\n\u27f6 subdir1\n\u27f6 \u27f6 file1.ext\n\u27f6 \u27f6 subsubdir1\n\u27f6 subdir2\n\u27f6 \u27f6 subsubdir2\n\u27f6 \u27f6 \u27f6 file2.ext\nIf we were to write this representation in code, it will look like this: \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\". Note that the '\\n' and '\\t' are the new-line and tab characters.\nEvery file and directory has a unique absolute path in the file system, which is the order of directories that must be opened to reach the file/directory itself, all concatenated by '/'s. Using the above example, the absolute path to file2.ext is \"dir/subdir2/subsubdir2/file2.ext\". Each directory name consists of letters, digits, and/or spaces. Each file name is of the form name.extension, where name and extension consist of letters, digits, and/or spaces.\nGiven a string input representing the file system in the explained format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0.\nNote that the testcases are generated such that the file system is valid and no file or directory name has length 0.\n Example 1:\nInput: input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"\nOutput: 20\nExplanation: We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.\nExample 2:\nInput: input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\nOutput: 32\nExplanation: We have two files:\n\"dir/subdir1/file1.ext\" of length 21\n\"dir/subdir2/subsubdir2/file2.ext\" of length 32.\nWe return 32 since it is the longest absolute path to a file.\nExample 3:\nInput: input = \"a\"\nOutput: 0\nExplanation: We do not have any files, just a single directory named \"a\".\n Constraints:\n1 <= input.length <= 104\ninput may contain lowercase or uppercase English letters, a new line character '\\n', a tab character '\\t', a dot '.', a space ' ', and digits.\nAll file and directory names have positive length." }, { "post_href": "https://leetcode.com/problems/find-the-difference/discuss/379846/Three-Solutions-in-Python-3", "python_solutions": "class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n \ts, t = sorted(s), sorted(t)\n \tfor i,j in enumerate(s):\n \t\tif j != t[i]: return t[i]\n \treturn t[-1]", "slug": "find-the-difference", "post_title": "Three Solutions in Python 3", "user": "junaidmansuri", "upvotes": 23, "views": 2300, "problem_title": "find the difference", "number": 389, "acceptance": 0.603, "difficulty": "Easy", "__index_level_0__": 6673, "question": "You are given two strings s and t.\nString t is generated by random shuffling string s and then add one more letter at a random position.\nReturn the letter that was added to t.\n Example 1:\nInput: s = \"abcd\", t = \"abcde\"\nOutput: \"e\"\nExplanation: 'e' is the letter that was added.\nExample 2:\nInput: s = \"\", t = \"y\"\nOutput: \"y\"\n Constraints:\n0 <= s.length <= 1000\nt.length == s.length + 1\ns and t consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/elimination-game/discuss/824126/Python3-3-line-O(logN)", "python_solutions": "class Solution:\n def lastRemaining(self, n: int) -> int:\n if n == 1: return 1\n if n&1: n -= 1\n return n + 2 - 2*self.lastRemaining(n//2)", "slug": "elimination-game", "post_title": "[Python3] 3-line O(logN)", "user": "ye15", "upvotes": 5, "views": 588, "problem_title": "elimination game", "number": 390, "acceptance": 0.465, "difficulty": "Medium", "__index_level_0__": 6739, "question": "You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order. Apply the following algorithm on arr:\nStarting from left to right, remove the first number and every other number afterward until you reach the end of the list.\nRepeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.\nKeep repeating the steps again, alternating left to right and right to left, until a single number remains.\nGiven the integer n, return the last number that remains in arr.\n Example 1:\nInput: n = 9\nOutput: 6\nExplanation:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\narr = [2, 4, 6, 8]\narr = [2, 6]\narr = [6]\nExample 2:\nInput: n = 1\nOutput: 1\n Constraints:\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/perfect-rectangle/discuss/968076/Python-Fast-and-clear-solution-with-explanation", "python_solutions": "class Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n \n area = 0\n corners = set()\n a = lambda: (Y-y) * (X-x)\n \n for x, y, X, Y in rectangles:\n area += a()\n corners ^= {(x,y), (x,Y), (X,y), (X,Y)}\n\n if len(corners) != 4: return False\n x, y = min(corners, key=lambda x: x[0] + x[1])\n X, Y = max(corners, key=lambda x: x[0] + x[1])\n return a() == area", "slug": "perfect-rectangle", "post_title": "[Python] Fast and clear solution with explanation", "user": "modusV", "upvotes": 40, "views": 1200, "problem_title": "perfect rectangle", "number": 391, "acceptance": 0.325, "difficulty": "Hard", "__index_level_0__": 6748, "question": "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).\nReturn true if all the rectangles together form an exact cover of a rectangular region.\n Example 1:\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\nOutput: true\nExplanation: All 5 rectangles together form an exact cover of a rectangular region.\nExample 2:\nInput: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\nOutput: false\nExplanation: Because there is a gap between the two rectangular regions.\nExample 3:\nInput: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\nOutput: false\nExplanation: Because two of the rectangles overlap with each other.\n Constraints:\n1 <= rectangles.length <= 2 * 104\nrectangles[i].length == 4\n-105 <= xi, yi, ai, bi <= 105" }, { "post_href": "https://leetcode.com/problems/is-subsequence/discuss/2473010/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-JS-C-Python3-(Two-Pointers-Approach)", "python_solutions": "class Solution(object):\n def isSubsequence(self, s, t):\n # Base case\n if not s:\n return True\n i = 0\n # Traverse elements of t string\n for j in t:\n # If this index matches to the index of s string, increment i pointer...\n if j == s[i]:\n i += 1\n # If the pointer is equal to the size of s...\n if i == len(s):\n break\n return i == len(s)", "slug": "is-subsequence", "post_title": "Very Easy || 100% || Fully Explained || Java, C++, Python, JS, C, Python3 (Two-Pointers Approach)", "user": "PratikSen07", "upvotes": 16, "views": 998, "problem_title": "is subsequence", "number": 392, "acceptance": 0.49, "difficulty": "Easy", "__index_level_0__": 6752, "question": "Given two strings s and t, return true if s is a subsequence of t, or false otherwise.\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not).\n Example 1:\nInput: s = \"abc\", t = \"ahbgdc\"\nOutput: true\nExample 2:\nInput: s = \"axc\", t = \"ahbgdc\"\nOutput: false\n Constraints:\n0 <= s.length <= 100\n0 <= t.length <= 104\ns and t consist only of lowercase English letters.\n Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where k >= 109, and you want to check one by one to see if t has its subsequence. In this scenario, how would you change your code?" }, { "post_href": "https://leetcode.com/problems/utf-8-validation/discuss/2568848/Python3-or-DP-or-Memoization-or-Neat-Solution-or-O(n)", "python_solutions": "class Solution:\n def validUtf8(self, data: List[int]) -> bool:\n n = len(data)\n l = [2**i for i in range(7, -1, -1)]\n \n def isXByteSeq(pos, X):\n f = data[pos]\n rem = data[pos+1:pos+X]\n ret = (f&l[X]) == 0\n for i in range(X):\n ret &= (f&l[i]) != 0\n for num in rem:\n ret &= (num&l[0]) != 0\n ret &= (num&l[1]) == 0\n return ret\n \n @cache\n def res(pos = 0):\n ret = False\n if pos == n:\n ret = True\n if pos + 3 < n:\n ret |= isXByteSeq(pos, 4) and res(pos + 4)\n if pos + 2 < n:\n ret |= isXByteSeq(pos, 3) and res(pos + 3)\n if pos + 1 < n:\n ret |= isXByteSeq(pos, 2) and res(pos + 2)\n if pos < n:\n ret |= isXByteSeq(pos, 0) and res(pos + 1)\n return ret\n \n return res()", "slug": "utf-8-validation", "post_title": "Python3 | DP | Memoization | Neat Solution | O(n)", "user": "DheerajGadwala", "upvotes": 4, "views": 497, "problem_title": "utf 8 validation", "number": 393, "acceptance": 0.452, "difficulty": "Medium", "__index_level_0__": 6807, "question": "Given an integer array data representing the data, return whether it is a valid UTF-8 encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).\nA character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:\nFor a 1-byte character, the first bit is a 0, followed by its Unicode code.\nFor an n-bytes character, the first n bits are all one's, the n + 1 bit is 0, followed by n - 1 bytes with the most significant 2 bits being 10.\nThis is how the UTF-8 encoding would work:\n Number of Bytes | UTF-8 Octet Sequence\n | (binary)\n --------------------+-----------------------------------------\n 1 | 0xxxxxxx\n 2 | 110xxxxx 10xxxxxx\n 3 | 1110xxxx 10xxxxxx 10xxxxxx\n 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\nx denotes a bit in the binary form of a byte that may be either 0 or 1.\nNote: The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.\n Example 1:\nInput: data = [197,130,1]\nOutput: true\nExplanation: data represents the octet sequence: 11000101 10000010 00000001.\nIt is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\nExample 2:\nInput: data = [235,140,4]\nOutput: false\nExplanation: data represented the octet sequence: 11101011 10001100 00000100.\nThe first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\nThe next byte is a continuation byte which starts with 10 and that's correct.\nBut the second continuation byte does not start with 10, so it is invalid.\n Constraints:\n1 <= data.length <= 2 * 104\n0 <= data[i] <= 255" }, { "post_href": "https://leetcode.com/problems/decode-string/discuss/1400105/98-faster-oror-With-and-without-Stack-oror-Cleane-and-Concise", "python_solutions": "class Solution:\ndef decodeString(self, s: str) -> str:\n \n res,num = \"\",0\n st = []\n for c in s:\n if c.isdigit():\n num = num*10+int(c) \n elif c==\"[\":\n st.append(res)\n st.append(num)\n res=\"\"\n num=0\n elif c==\"]\":\n pnum = st.pop()\n pstr = st.pop()\n res = pstr + pnum*res\n else:\n res+=c\n \n return res", "slug": "decode-string", "post_title": "\ud83d\udc0d 98% faster || With and without Stack || Cleane & Concise \ud83d\udccc\ud83d\udccc", "user": "abhi9Rai", "upvotes": 27, "views": 2700, "problem_title": "decode string", "number": 394, "acceptance": 0.5760000000000001, "difficulty": "Medium", "__index_level_0__": 6831, "question": "Given an encoded string, return its decoded string.\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.\nYou may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there will not be input like 3a or 2[4].\nThe test cases are generated so that the length of the output will never exceed 105.\n Example 1:\nInput: s = \"3[a]2[bc]\"\nOutput: \"aaabcbc\"\nExample 2:\nInput: s = \"3[a2[c]]\"\nOutput: \"accaccacc\"\nExample 3:\nInput: s = \"2[abc]3[cd]ef\"\nOutput: \"abcabccdcdcdef\"\n Constraints:\n1 <= s.length <= 30\ns consists of lowercase English letters, digits, and square brackets '[]'.\ns is guaranteed to be a valid input.\nAll the integers in s are in the range [1, 300]." }, { "post_href": "https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/discuss/1721267/Faster-than-97.6.-Recursion", "python_solutions": "class Solution:\n def rec(self, s, k):\n c = Counter(s)\n\n if pattern := \"|\".join(filter(lambda x: c[x] < k, c)):\n if arr := list(filter(lambda x: len(x) >= k, re.split(pattern, s))):\n \n return max(map(lambda x: self.rec(x, k), arr))\n \n return 0\n \n return len(s)\n \n def longestSubstring(self, s: str, k: int) -> int:\n return self.rec(s, k)", "slug": "longest-substring-with-at-least-k-repeating-characters", "post_title": "Faster than 97.6%. Recursion", "user": "mygurbanov", "upvotes": 3, "views": 244, "problem_title": "longest substring with at least k repeating characters", "number": 395, "acceptance": 0.4479999999999999, "difficulty": "Medium", "__index_level_0__": 6877, "question": "Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.\nif no such substring exists, return 0.\n Example 1:\nInput: s = \"aaabb\", k = 3\nOutput: 3\nExplanation: The longest substring is \"aaa\", as 'a' is repeated 3 times.\nExample 2:\nInput: s = \"ababbc\", k = 2\nOutput: 5\nExplanation: The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.\n Constraints:\n1 <= s.length <= 104\ns consists of only lowercase English letters.\n1 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/rotate-function/discuss/857056/Python-3-(Py3.8)-or-Math-O(n)-or-Explanation", "python_solutions": "class Solution:\n def maxRotateFunction(self, A: List[int]) -> int:\n s, n = sum(A), len(A)\n cur_sum = sum([i*j for i, j in enumerate(A)])\n ans = cur_sum\n for i in range(n): ans = max(ans, cur_sum := cur_sum + s-A[n-1-i]*n)\n return ans", "slug": "rotate-function", "post_title": "Python 3 (Py3.8) | Math, O(n) | Explanation", "user": "idontknoooo", "upvotes": 6, "views": 588, "problem_title": "rotate function", "number": 396, "acceptance": 0.4039999999999999, "difficulty": "Medium", "__index_level_0__": 6894, "question": "You are given an integer array nums of length n.\nAssume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:\nF(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].\nReturn the maximum value of F(0), F(1), ..., F(n-1).\nThe test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\nInput: nums = [4,3,2,6]\nOutput: 26\nExplanation:\nF(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\nF(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\nF(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\nF(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\nSo the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\nExample 2:\nInput: nums = [100]\nOutput: 0\n Constraints:\nn == nums.length\n1 <= n <= 105\n-100 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/integer-replacement/discuss/663134/Two-solution-in-Python", "python_solutions": "class Solution:\n def integerReplacement(self, n: int) -> int:\n cnt = 0\n while n != 1:\n if n%2 == 0:\n n//=2\n elif n%4 == 1 or n == 3:\n n -= 1\n else:\n n += 1\n cnt += 1\n return cnt", "slug": "integer-replacement", "post_title": "Two solution in Python", "user": "realslimshady", "upvotes": 4, "views": 351, "problem_title": "integer replacement", "number": 397, "acceptance": 0.352, "difficulty": "Medium", "__index_level_0__": 6902, "question": "Given a positive integer n, you can apply one of the following operations:\nIf n is even, replace n with n / 2.\nIf n is odd, replace n with either n + 1 or n - 1.\nReturn the minimum number of operations needed for n to become 1.\n Example 1:\nInput: n = 8\nOutput: 3\nExplanation: 8 -> 4 -> 2 -> 1\nExample 2:\nInput: n = 7\nOutput: 4\nExplanation: 7 -> 8 -> 4 -> 2 -> 1\nor 7 -> 6 -> 3 -> 2 -> 1\nExample 3:\nInput: n = 4\nOutput: 2\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/random-pick-index/discuss/1671979/Python-3-Reservoir-Sampling-O(n)-Time-and-O(1)-Space", "python_solutions": "class Solution:\n\n def __init__(self, nums: List[int]):\n # Reservoir Sampling (which can handle the linked list with unknown size), time complexity O(n) (init: O(1), pick: O(n)), space complextiy O(1)\n self.nums = nums\n\n def pick(self, target: int) -> int:\n # https://docs.python.org/3/library/random.html\n count = 0\n chosen_index = None\n for i in range(len(self.nums)):\n if self.nums[i] != target:\n continue\n count += 1\n if count == 1:\n chosen_index = i\n elif random.random() < 1 / count:\n chosen_index = i\n return chosen_index", "slug": "random-pick-index", "post_title": "Python 3 Reservoir Sampling, O(n) Time & O(1) Space", "user": "xil899", "upvotes": 6, "views": 453, "problem_title": "random pick index", "number": 398, "acceptance": 0.628, "difficulty": "Medium", "__index_level_0__": 6922, "question": "Given an integer array nums with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.\nImplement the Solution class:\nSolution(int[] nums) Initializes the object with the array nums.\nint pick(int target) Picks a random index i from nums where nums[i] == target. If there are multiple valid i's, then each index should have an equal probability of returning.\n Example 1:\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\"]\n[[[1, 2, 3, 3, 3]], [3], [1], [3]]\nOutput\n[null, 4, 0, 2]\n\nExplanation\nSolution solution = new Solution([1, 2, 3, 3, 3]);\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\nsolution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\nsolution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n Constraints:\n1 <= nums.length <= 2 * 104\n-231 <= nums[i] <= 231 - 1\ntarget is an integer from nums.\nAt most 104 calls will be made to pick." }, { "post_href": "https://leetcode.com/problems/evaluate-division/discuss/827506/Python3-dfs-and-union-find", "python_solutions": "class Solution:\n def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n graph = {}\n for (u, v), w in zip(equations, values): \n graph.setdefault(u, []).append((v, 1/w))\n graph.setdefault(v, []).append((u, w))\n\n def dfs(n, g, val=1):\n \"\"\"Depth-first traverse the graph.\"\"\"\n if n in vals: return \n vals[n] = val, g\n for nn, w in graph.get(n, []): dfs(nn, g, w*val)\n \n vals = dict()\n for i, n in enumerate(graph): dfs(n, i)\n \n ans = []\n for u, v in queries: \n if u in vals and v in vals and vals[u][1] == vals[v][1]: ans.append(vals[u][0]/vals[v][0])\n else: ans.append(-1)\n return ans", "slug": "evaluate-division", "post_title": "[Python3] dfs & union-find", "user": "ye15", "upvotes": 8, "views": 489, "problem_title": "evaluate division", "number": 399, "acceptance": 0.596, "difficulty": "Medium", "__index_level_0__": 6938, "question": "You are given an array of variable pairs equations and an array of real numbers values, where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i]. Each Ai or Bi is a string that represents a single variable.\nYou are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.\nReturn the answers to all queries. If a single answer cannot be determined, return -1.0.\nNote: The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.\nNote: The variables that do not occur in the list of equations are undefined, so the answer cannot be determined for them.\n Example 1:\nInput: equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\nOutput: [6.00000,0.50000,-1.00000,1.00000,-1.00000]\nExplanation: \nGiven: a / b = 2.0, b / c = 3.0\nqueries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? \nreturn: [6.0, 0.5, -1.0, 1.0, -1.0 ]\nnote: x is undefined => -1.0\nExample 2:\nInput: equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\nOutput: [3.75000,0.40000,5.00000,0.20000]\nExample 3:\nInput: equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\nOutput: [0.50000,2.00000,-1.00000,-1.00000]\n Constraints:\n1 <= equations.length <= 20\nequations[i].length == 2\n1 <= Ai.length, Bi.length <= 5\nvalues.length == equations.length\n0.0 < values[i] <= 20.0\n1 <= queries.length <= 20\nqueries[i].length == 2\n1 <= Cj.length, Dj.length <= 5\nAi, Bi, Cj, Dj consist of lower case English letters and digits." }, { "post_href": "https://leetcode.com/problems/nth-digit/discuss/828924/Python3-O(logN)-solution", "python_solutions": "class Solution:\n def findNthDigit(self, n: int) -> int:\n digit = base = 1 # starting from 1 digit\n while n > 9*base*digit: # upper limit of d digits \n n -= 9*base*digit\n digit += 1\n base *= 10 \n q, r = divmod(n-1, digit)\n return int(str(base + q)[r])", "slug": "nth-digit", "post_title": "[Python3] O(logN) solution", "user": "ye15", "upvotes": 25, "views": 2100, "problem_title": "nth digit", "number": 400, "acceptance": 0.341, "difficulty": "Medium", "__index_level_0__": 6971, "question": "Given an integer n, return the nth digit of the infinite integer sequence [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...].\n Example 1:\nInput: n = 3\nOutput: 3\nExample 2:\nInput: n = 11\nOutput: 0\nExplanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/binary-watch/discuss/371775/Solution-in-Python-3-(beats-~98)-(one-line)", "python_solutions": "class Solution:\n def readBinaryWatch(self, n: int) -> List[str]:\n \treturn [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') == n]", "slug": "binary-watch", "post_title": "Solution in Python 3 (beats ~98%) (one line)", "user": "junaidmansuri", "upvotes": 10, "views": 1600, "problem_title": "binary watch", "number": 401, "acceptance": 0.517, "difficulty": "Easy", "__index_level_0__": 6979, "question": "A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs on the bottom to represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right.\nFor example, the below binary watch reads \"4:51\".\nGiven an integer turnedOn which represents the number of LEDs that are currently on (ignoring the PM), return all possible times the watch could represent. You may return the answer in any order.\nThe hour must not contain a leading zero.\nFor example, \"01:00\" is not valid. It should be \"1:00\".\nThe minute must consist of two digits and may contain a leading zero.\nFor example, \"10:2\" is not valid. It should be \"10:02\".\n Example 1:\nInput: turnedOn = 1\nOutput: [\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]\nExample 2:\nInput: turnedOn = 9\nOutput: []\n Constraints:\n0 <= turnedOn <= 10" }, { "post_href": "https://leetcode.com/problems/remove-k-digits/discuss/1779520/Python3-MONOTONIC-STACK-(oo)-Explained", "python_solutions": "class Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n st = list()\n for n in num:\n while st and k and st[-1] > n:\n st.pop()\n k -= 1\n \n if st or n is not '0': # prevent leading zeros\n st.append(n)\n \n if k: # not fully spent\n\t\t\tst = st[0:-k]\n \n return ''.join(st) or '0'", "slug": "remove-k-digits", "post_title": "\u2714\ufe0f [Python3] MONOTONIC STACK (o^^o)\u266a, Explained", "user": "artod", "upvotes": 121, "views": 7900, "problem_title": "remove k digits", "number": 402, "acceptance": 0.305, "difficulty": "Medium", "__index_level_0__": 6998, "question": "Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.\n Example 1:\nInput: num = \"1432219\", k = 3\nOutput: \"1219\"\nExplanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\nExample 2:\nInput: num = \"10200\", k = 1\nOutput: \"200\"\nExplanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\nExample 3:\nInput: num = \"10\", k = 2\nOutput: \"0\"\nExplanation: Remove all the digits from the number and it is left with nothing which is 0.\n Constraints:\n1 <= k <= num.length <= 105\nnum consists of only digits.\nnum does not have any leading zeros except for the zero itself." }, { "post_href": "https://leetcode.com/problems/frog-jump/discuss/418003/11-line-DFS-solution", "python_solutions": "class Solution(object):\n def canCross(self, stones):\n n = len(stones)\n stoneSet = set(stones)\n visited = set()\n def goFurther(value,units):\n if (value+units not in stoneSet) or ((value,units) in visited):\n return False\n if value+units == stones[n-1]:\n return True\n visited.add((value,units))\n return goFurther(value+units,units) or goFurther(value+units,units-1) or goFurther(value+units,units+1)\n return goFurther(stones[0],1)", "slug": "frog-jump", "post_title": "11 line DFS solution", "user": "nirajmotiani", "upvotes": 20, "views": 2700, "problem_title": "frog jump", "number": 403, "acceptance": 0.432, "difficulty": "Hard", "__index_level_0__": 7025, "question": "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.\nGiven 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.\nIf 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 Example 1:\nInput: stones = [0,1,3,5,6,8,12,17]\nOutput: true\nExplanation: 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.\nExample 2:\nInput: stones = [0,1,2,3,4,8,9,11]\nOutput: false\nExplanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n Constraints:\n2 <= stones.length <= 2000\n0 <= stones[i] <= 231 - 1\nstones[0] == 0\nstones is sorted in a strictly increasing order." }, { "post_href": "https://leetcode.com/problems/sum-of-left-leaves/discuss/1558223/Python-DFSRecursion-Easy-%2B-Intuitive", "python_solutions": "class Solution:\n def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n\n # does this node have a left child which is a leaf?\n if root.left and not root.left.left and not root.left.right:\n\t\t\t# gotcha\n return root.left.val + self.sumOfLeftLeaves(root.right)\n\n # no it does not have a left child or it's not a leaf\n else:\n\t\t\t# bummer\n return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)", "slug": "sum-of-left-leaves", "post_title": "Python DFS/Recursion Easy + Intuitive", "user": "aayushisingh1703", "upvotes": 36, "views": 2000, "problem_title": "sum of left leaves", "number": 404, "acceptance": 0.563, "difficulty": "Easy", "__index_level_0__": 7041, "question": "Given the root of a binary tree, return the sum of all left leaves.\nA leaf is a node with no children. A left leaf is a leaf that is the left child of another node.\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: 24\nExplanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.\nExample 2:\nInput: root = [1]\nOutput: 0\n Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/1235709/easy-solution-with-explanation", "python_solutions": "class Solution:\n def toHex(self, num: int) -> str:\n hex=\"0123456789abcdef\" #created string for reference\n ot=\"\" # created a string variable to store and update output string\n if num==0:\n return \"0\"\n elif num<0:\n num+=2**32\n while num:\n ot=hex[num%16]+ot # we update the output string with the reminder of num/16 , 16 because we are dealing with hex.\n num//=16 # now we are updating num by dividing it by 16 ***// operator used for floor division , means division will be always integer not float.\n return ot # then we simply return ot", "slug": "convert-a-number-to-hexadecimal", "post_title": "easy solution with explanation", "user": "souravsingpardeshi", "upvotes": 12, "views": 756, "problem_title": "convert a number to hexadecimal", "number": 405, "acceptance": 0.462, "difficulty": "Easy", "__index_level_0__": 7071, "question": "Given an integer num, return a string representing its hexadecimal representation. For negative integers, two\u2019s complement method is used.\nAll the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.\nNote: You are not allowed to use any built-in library method to directly solve this problem.\n Example 1:\nInput: num = 26\nOutput: \"1a\"\nExample 2:\nInput: num = -1\nOutput: \"ffffffff\"\n Constraints:\n-231 <= num <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/queue-reconstruction-by-height/discuss/2211602/Python-Easy-Greedy-O(1)-Space-approach", "python_solutions": "class Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n output=[] \n \n # sort the array in decreasing order of height \n # within the same height group, you would sort it in increasing order of k\n # eg: Input : [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\n # after sorting: [[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]\n people.sort(key=lambda x: (-x[0], x[1])) \n for a in people:\n # Now let's start the greedy here\n # We insert the entry in the output array based on the k value\n # k will act as a position within the array\n output.insert(a[1], a)\n \n return output", "slug": "queue-reconstruction-by-height", "post_title": "Python Easy Greedy O(1) Space approach", "user": "constantine786", "upvotes": 79, "views": 3300, "problem_title": "queue reconstruction by height", "number": 406, "acceptance": 0.728, "difficulty": "Medium", "__index_level_0__": 7092, "question": "You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi.\nReconstruct and return the queue that is represented by the input array people. The returned queue should be formatted as an array queue, where queue[j] = [hj, kj] is the attributes of the jth person in the queue (queue[0] is the person at the front of the queue).\n Example 1:\nInput: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\nOutput: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\nExplanation:\nPerson 0 has height 5 with no other people taller or the same height in front.\nPerson 1 has height 7 with no other people taller or the same height in front.\nPerson 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\nPerson 3 has height 6 with one person taller or the same height in front, which is person 1.\nPerson 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\nPerson 5 has height 7 with one person taller or the same height in front, which is person 1.\nHence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.\nExample 2:\nInput: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\nOutput: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n Constraints:\n1 <= people.length <= 2000\n0 <= hi <= 106\n0 <= ki < people.length\nIt is guaranteed that the queue can be reconstructed." }, { "post_href": "https://leetcode.com/problems/trapping-rain-water-ii/discuss/1138028/Python3Visualization-BFS-Solution-With-Explanation", "python_solutions": "class Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n if not heightMap or not heightMap[0]:\n return 0\n\t\t\t\n\t\t\t\n\t\t# Initial\n\t\t# Board cells cannot trap the water\n m, n = len(heightMap), len(heightMap[0])\n if m < 3 or n < 3:\n return 0\n\t\t\t\n\t\t\t\n\t\t# Add Board cells first\n heap = []\n for i in range(m):\n for j in range(n):\n if i == 0 or i == m - 1 or j == 0 or j == n - 1:\n heapq.heappush(heap, (heightMap[i][j], i, j))\n heightMap[i][j] = -1\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t# Start from level 0\n level, res = 0, 0\n \n\t\twhile heap:\n height, x, y = heapq.heappop(heap)\n level = max(height, level)\n\n for i, j in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:\n if 0 <= i < m and 0 <= j < n and heightMap[i][j] != -1:\n heapq.heappush(heap, (heightMap[i][j], i, j))\n\t\t\t\t\t\n\t\t\t\t\t# If cell's height smaller than the level, then it can trap the rain water\n if heightMap[i][j] < level:\n res += level - heightMap[i][j]\n\t\t\t\t\t\t\n\t\t\t\t\t# Set the height to -1 if the cell is visited\n heightMap[i][j] = -1\n\n return res", "slug": "trapping-rain-water-ii", "post_title": "[Python3][Visualization] BFS Solution With Explanation", "user": "Picassos_Shoes", "upvotes": 209, "views": 4700, "problem_title": "trapping rain water ii", "number": 407, "acceptance": 0.475, "difficulty": "Hard", "__index_level_0__": 7114, "question": "Given an m x n integer matrix heightMap representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.\n Example 1:\nInput: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\nOutput: 4\nExplanation: After the rain, water is trapped between the blocks.\nWe have two small ponds 1 and 3 units trapped.\nThe total volume of water trapped is 4.\nExample 2:\nInput: heightMap = [[3,3,3,3,3],[3,2,2,2,3],[3,2,1,2,3],[3,2,2,2,3],[3,3,3,3,3]]\nOutput: 10\n Constraints:\nm == heightMap.length\nn == heightMap[i].length\n1 <= m, n <= 200\n0 <= heightMap[i][j] <= 2 * 104" }, { "post_href": "https://leetcode.com/problems/longest-palindrome/discuss/2221045/Python-oror-counter-oror-explanation", "python_solutions": "class Solution:\n def longestPalindrome(self, s: str) -> int:\n oddFlag=0\n \n count=collections.Counter(s)\n\n ans=0\n for k,v in count.items():\n if v%2==1:\n ans+=v-1\n oddFlag= 1\n else:\n ans+=v\n \n if oddFlag == 1:\n return ans+1\n return ans", "slug": "longest-palindrome", "post_title": "Python || counter || explanation", "user": "palashbajpai214", "upvotes": 9, "views": 465, "problem_title": "longest palindrome", "number": 409, "acceptance": 0.547, "difficulty": "Easy", "__index_level_0__": 7120, "question": "Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.\nLetters are case sensitive, for example, \"Aa\" is not considered a palindrome here.\n Example 1:\nInput: s = \"abccccdd\"\nOutput: 7\nExplanation: One longest palindrome that can be built is \"dccaccd\", whose length is 7.\nExample 2:\nInput: s = \"a\"\nOutput: 1\nExplanation: The longest palindrome that can be built is \"a\", whose length is 1.\n Constraints:\n1 <= s.length <= 2000\ns consists of lowercase and/or uppercase English letters only." }, { "post_href": "https://leetcode.com/problems/split-array-largest-sum/discuss/1901138/Python-Short-and-Simple-NLogSum", "python_solutions": "class Solution:\n def splitArray(self, nums: List[int], m: int) -> int:\n def isPossible(maxSum):\n curr = count = 0\n for i in nums:\n count += (i + curr > maxSum)\n curr = curr + i if i + curr <= maxSum else i\n return count + 1 <= m\n \n lo, hi = max(nums), sum(nums)\n while lo <= hi:\n mid = (lo + hi) // 2\n if isPossible(mid): hi = mid - 1\n else: lo = mid + 1\n return lo", "slug": "split-array-largest-sum", "post_title": "\u2705 Python Short and Simple NLogSum", "user": "dhananjay79", "upvotes": 3, "views": 112, "problem_title": "split array largest sum", "number": 410, "acceptance": 0.5329999999999999, "difficulty": "Hard", "__index_level_0__": 7161, "question": "Given an integer array nums and an integer k, split nums into k non-empty subarrays such that the largest sum of any subarray is minimized.\nReturn the minimized largest sum of the split.\nA subarray is a contiguous part of the array.\n Example 1:\nInput: nums = [7,2,5,10,8], k = 2\nOutput: 18\nExplanation: There are four ways to split nums into two subarrays.\nThe best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.\nExample 2:\nInput: nums = [1,2,3,4,5], k = 2\nOutput: 9\nExplanation: There are four ways to split nums into two subarrays.\nThe best way is to split it into [1,2,3] and [4,5], where the largest sum among the two subarrays is only 9.\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] <= 106\n1 <= k <= min(50, nums.length)" }, { "post_href": "https://leetcode.com/problems/fizz-buzz/discuss/380065/Solution-in-Python-3-(beats-~98)-(one-line)", "python_solutions": "class Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n \treturn ['FizzBuzz' if i%15 == 0 else 'Buzz' if i%5 == 0 else 'Fizz' if i%3 == 0 else str(i) for i in range(1,n+1)]\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "fizz-buzz", "post_title": "Solution in Python 3 (beats ~98%) (one line)", "user": "junaidmansuri", "upvotes": 6, "views": 1900, "problem_title": "fizz buzz", "number": 412, "acceptance": 0.69, "difficulty": "Easy", "__index_level_0__": 7186, "question": "Given an integer n, return a string array answer (1-indexed) where:\nanswer[i] == \"FizzBuzz\" if i is divisible by 3 and 5.\nanswer[i] == \"Fizz\" if i is divisible by 3.\nanswer[i] == \"Buzz\" if i is divisible by 5.\nanswer[i] == i (as a string) if none of the above conditions are true.\n Example 1:\nInput: n = 3\nOutput: [\"1\",\"2\",\"Fizz\"]\nExample 2:\nInput: n = 5\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\nExample 3:\nInput: n = 15\nOutput: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/arithmetic-slices/discuss/1816132/beginners-solution-Easy-to-understand", "python_solutions": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n count = 0\n for i in range(len(nums)-2):\n j = i+1\n while(j int:\n \tn, T = list(set(nums)), [float('-inf')]*3\n \tfor i in n:\n \t\tif i > T[0]:\n \t\t\tT = [i,T[0],T[1]]\n \t\t\tcontinue\n \t\tif i > T[1]:\n \t\t\tT = [T[0],i,T[1]]\n \t\t\tcontinue\n \t\tif i > T[2]:\n \t\t\tT = [T[0],T[1],i]\n \treturn T[2] if T[2] != float('-inf') else T[0]\n\t\t\n\t\t\n- Junaid Mansuri", "slug": "third-maximum-number", "post_title": "Solution in Python 3 (beats ~99%) ( O(n) )", "user": "junaidmansuri", "upvotes": 18, "views": 3500, "problem_title": "third maximum number", "number": 414, "acceptance": 0.326, "difficulty": "Easy", "__index_level_0__": 7282, "question": "Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.\n Example 1:\nInput: nums = [3,2,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2.\nThe third distinct maximum is 1.\nExample 2:\nInput: nums = [1,2]\nOutput: 2\nExplanation:\nThe first distinct maximum is 2.\nThe second distinct maximum is 1.\nThe third distinct maximum does not exist, so the maximum (2) is returned instead.\nExample 3:\nInput: nums = [2,2,3,1]\nOutput: 1\nExplanation:\nThe first distinct maximum is 3.\nThe second distinct maximum is 2 (both 2's are counted together since they have the same value).\nThe third distinct maximum is 1.\n Constraints:\n1 <= nums.length <= 104\n-231 <= nums[i] <= 231 - 1\n Follow up: Can you find an O(n) solution?" }, { "post_href": "https://leetcode.com/problems/add-strings/discuss/1591891/Python-Straightforward-Solution-or-Easy-to-Understand", "python_solutions": "class Solution:\n\tdef addStrings(self, num1: str, num2: str) -> str:\n\t\tnum1 = list(num1)\n\t\tnum2 = list(num2)\n\t\tcar = 0\n\t\tres = \"\"\n\t\twhile num1 or num2 or car:\n\t\t\tif num1:\n\t\t\t\tcar += int(num1.pop())\n\t\t\tif num2:\n\t\t\t\tcar += int(num2.pop())\n\t\t\tres += str((car % 10))\n\t\t\tcar //= 10\n\t\treturn res[::-1]", "slug": "add-strings", "post_title": "Python Straightforward Solution | Easy to Understand", "user": "leet_satyam", "upvotes": 10, "views": 605, "problem_title": "add strings", "number": 415, "acceptance": 0.526, "difficulty": "Easy", "__index_level_0__": 7334, "question": "Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.\nYou must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.\n Example 1:\nInput: num1 = \"11\", num2 = \"123\"\nOutput: \"134\"\nExample 2:\nInput: num1 = \"456\", num2 = \"77\"\nOutput: \"533\"\nExample 3:\nInput: num1 = \"0\", num2 = \"0\"\nOutput: \"0\"\n Constraints:\n1 <= num1.length, num2.length <= 104\nnum1 and num2 consist of only digits.\nnum1 and num2 don't have any leading zeros except for the zero itself." }, { "post_href": "https://leetcode.com/problems/partition-equal-subset-sum/discuss/1624391/Python-DP-and-DFS-Solutions-Easy-to-understand-with-Explanation", "python_solutions": "class Solution:\n def canPartition(self, nums: List[int]) -> bool:\n\t if sum(nums)%2: # or if sum(nums)&1\n\t\t return False\n\t\t# main logic here", "slug": "partition-equal-subset-sum", "post_title": "[Python] DP & DFS Solutions - Easy-to-understand with Explanation", "user": "zayne-siew", "upvotes": 38, "views": 5800, "problem_title": "partition equal subset sum", "number": 416, "acceptance": 0.466, "difficulty": "Medium", "__index_level_0__": 7384, "question": "Given an integer array nums, return true if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false otherwise.\n Example 1:\nInput: nums = [1,5,11,5]\nOutput: true\nExplanation: The array can be partitioned as [1, 5, 5] and [11].\nExample 2:\nInput: nums = [1,2,3,5]\nOutput: false\nExplanation: The array cannot be partitioned into equal sum subsets.\n Constraints:\n1 <= nums.length <= 200\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/2507252/PYTHON-oror-EXPLAINED-oror", "python_solutions": "class Solution:\n def pacificAtlantic(self, ht: List[List[int]]) -> List[List[int]]:\n \n def pac(i,j):\n if rp[i][j]:\n return True\n k=False\n h=ht[i][j]\n ht[i][j]=100001\n if ht[i-1][j]<=h:\n k=k or pac(i-1,j)\n \n if ht[i][j-1]<=h:\n k=k or pac(i,j-1)\n \n if i0 and ht[i-1][j]<=h:\n k=k or ant(i-1,j)\n \n if j>0 and ht[i][j-1]<=h:\n k=k or ant(i,j-1)\n \n if ht[i+1][j]<=h:\n k=k or ant(i+1,j)\n \n if ht[i][j+1]<=h:\n k=k or ant(i,j+1)\n \n ht[i][j]=h\n ra[i][j]=k\n return k\n \n m=len(ht)\n n=len(ht[0])\n rp=[[False for i in range(n)] for j in range(m)]\n ra=[[False for i in range(n)] for j in range(m)]\n \n for i in range(m):\n rp[i][0]=True\n ra[i][-1]=True\n for i in range(n):\n rp[0][i]=True\n ra[-1][i]=True\n \n for i in range(m):\n for j in range(n):\n pac(i,j)\n ant(i,j)\n res=[]\n for i in range(m):\n for j in range(n):\n if rp[i][j] and ra[i][j]:\n res.append([i,j])\n return res", "slug": "pacific-atlantic-water-flow", "post_title": "\ud83e\udd47 PYTHON || EXPLAINED || ; ]", "user": "karan_8082", "upvotes": 16, "views": 1900, "problem_title": "pacific atlantic water flow", "number": 417, "acceptance": 0.541, "difficulty": "Medium", "__index_level_0__": 7432, "question": "There is an m x n rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges.\nThe island is partitioned into a grid of square cells. You are given an m x n integer matrix heights where heights[r][c] represents the height above sea level of the cell at coordinate (r, c).\nThe island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.\nReturn a 2D list of grid coordinates result where result[i] = [ri, ci] denotes that rain water can flow from cell (ri, ci) to both the Pacific and Atlantic oceans.\n Example 1:\nInput: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]\nOutput: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\nExplanation: The following cells can flow to the Pacific and Atlantic oceans, as shown below:\n[0,4]: [0,4] -> Pacific Ocean \n [0,4] -> Atlantic Ocean\n[1,3]: [1,3] -> [0,3] -> Pacific Ocean \n [1,3] -> [1,4] -> Atlantic Ocean\n[1,4]: [1,4] -> [1,3] -> [0,3] -> Pacific Ocean \n [1,4] -> Atlantic Ocean\n[2,2]: [2,2] -> [1,2] -> [0,2] -> Pacific Ocean \n [2,2] -> [2,3] -> [2,4] -> Atlantic Ocean\n[3,0]: [3,0] -> Pacific Ocean \n [3,0] -> [4,0] -> Atlantic Ocean\n[3,1]: [3,1] -> [3,0] -> Pacific Ocean \n [3,1] -> [4,1] -> Atlantic Ocean\n[4,0]: [4,0] -> Pacific Ocean \n [4,0] -> Atlantic Ocean\nNote that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.\nExample 2:\nInput: heights = [[1]]\nOutput: [[0,0]]\nExplanation: The water can flow from the only cell to the Pacific and Atlantic oceans.\n Constraints:\nm == heights.length\nn == heights[r].length\n1 <= m, n <= 200\n0 <= heights[r][c] <= 105" }, { "post_href": "https://leetcode.com/problems/battleships-in-a-board/discuss/1523048/Simple-Easy-to-Understand-Python-O(1)-extra-memory", "python_solutions": "class Solution:\n def countBattleships(self, board: List[List[str]]) -> int:\n count = 0\n for r in range(len(board)):\n for c in range(len(board[0])):\n if board[r][c] == 'X':\n var = 1\n if (r > 0 and board[r-1][c] == 'X') or (c > 0 and board[r][c-1] == 'X'):\n var = 0\n count += var\n return count", "slug": "battleships-in-a-board", "post_title": "Simple Easy to Understand Python O(1) extra memory", "user": "bshien", "upvotes": 9, "views": 638, "problem_title": "battleships in a board", "number": 419, "acceptance": 0.747, "difficulty": "Medium", "__index_level_0__": 7472, "question": "Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.\nBattleships can only be placed horizontally or vertically on board. In other words, they can only be made of the shape 1 x k (1 row, k columns) or k x 1 (k rows, 1 column), where k can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships).\n Example 1:\nInput: board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]\nOutput: 2\nExample 2:\nInput: board = [[\".\"]]\nOutput: 0\n Constraints:\nm == board.length\nn == board[i].length\n1 <= m, n <= 200\nboard[i][j] is either '.' or 'X'.\n Follow up: Could you do it in one-pass, using only O(1) extra memory and without modifying the values board?" }, { "post_href": "https://leetcode.com/problems/strong-password-checker/discuss/2345991/Runtime%3A-23-ms-or-Memory-Usage%3A-13.9-MB-or-python3", "python_solutions": "class Solution:\n def strongPasswordChecker(self, password: str) -> int:\n #vimla_kushwaha\n s = password\n missing_type = 3\n if any('a' <= c <= 'z' for c in s): missing_type -= 1\n if any('A' <= c <= 'Z' for c in s): missing_type -= 1\n if any(c.isdigit() for c in s): missing_type -= 1\n\n change = 0\n one = two = 0\n p = 2\n while p < len(s):\n if s[p] == s[p-1] == s[p-2]:\n length = 2\n while p < len(s) and s[p] == s[p-1]:\n length += 1\n p += 1\n \n change += length // 3\n if length % 3 == 0: one += 1\n elif length % 3 == 1: two += 1\n else:\n p += 1\n \n if len(s) < 6:\n return max(missing_type, 6 - len(s))\n elif len(s) <= 20:\n return max(missing_type, change)\n else:\n delete = len(s) - 20\n \n change -= min(delete, one)\n change -= min(max(delete - one, 0), two * 2) // 2\n change -= max(delete - one - 2 * two, 0) // 3\n \n return int(delete + max(missing_type, change))", "slug": "strong-password-checker", "post_title": "Runtime: 23 ms | Memory Usage: 13.9 MB | python3", "user": "vimla_kushwaha", "upvotes": 2, "views": 309, "problem_title": "strong password checker", "number": 420, "acceptance": 0.143, "difficulty": "Hard", "__index_level_0__": 7489, "question": "A password is considered strong if the below conditions are all met:\nIt has at least 6 characters and at most 20 characters.\nIt contains at least one lowercase letter, at least one uppercase letter, and at least one digit.\nIt does not contain three repeating characters in a row (i.e., \"Baaabb0\" is weak, but \"Baaba0\" is strong).\nGiven a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0.\nIn one step, you can:\nInsert one character to password,\nDelete one character from password, or\nReplace one character of password with another character.\n Example 1:\nInput: password = \"a\"\nOutput: 5\nExample 2:\nInput: password = \"aA1\"\nOutput: 3\nExample 3:\nInput: password = \"1337C0d3\"\nOutput: 0\n Constraints:\n1 <= password.length <= 50\npassword consists of letters, digits, dot '.' or exclamation mark '!'." }, { "post_href": "https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/discuss/404504/Python-O(N)-Trie-Solution-wcomments-and-explanations", "python_solutions": "class Solution:\n def findMaximumXOR(self, nums: List[int]) -> int:\n # need to know the largest binary representation\n\t\t# bin prepends '0b', ignore\n\t\tL = len(bin(max(nums))) - 2\n\n\t\t# preprocess step - left-pad zeros to ensure each number has L bits\n\t\t# (x >> i) & 1 produces the bit at position i for number x\n\t\t# x's value is moved right by i bits, we & 1 to produce 0 or 1\n\t\t# e.g., if L = 5, then 3 = [0, 0, 0, 1, 1], so the steps to get there are:\n\t\t# (3 >> 4) & 1 = 0\n\t\t# (3 >> 3) & 1 = 0\n\t\t# (3 >> 2) & 1 = 0\n\t\t# (3 >> 1) & 1 = 1\n\t\t# (3 >> 0) & 1 = 1\n\t\tnums_bits = [[(x >> i) & 1 for i in reversed(range(L))] for x in nums]\n\t\troot = {}\n\t\t# build the trie\n\t\tfor num, bits in zip(nums, nums_bits):\n\t\t\tnode = root\n\t\t\tfor bit in bits:\n\t\t\t\tnode = node.setdefault(bit, {})\n\t\t\tnode[\"#\"] = num\n\n\t\tmax_xor = 0\n\t\tfor num, bits in zip(nums, nums_bits):\n\t\t\tnode = root\n\t\t\t# we want to find the node that will produce the largest XOR with num\n\t\t\tfor bit in bits:\n\t\t\t\t# our goal is to find the opposite bit, e.g. bit = 0, we want 1\n\t\t\t\t# this is our goal because we want as many 1's as possible\n\t\t\t\ttoggled_bit = 1 - bit\n\t\t\t\tif toggled_bit in node:\n\t\t\t\t\tnode = node[toggled_bit]\n\t\t\t\telse:\n\t\t\t\t\tnode = node[bit]\n\t\t\t# we're at a leaf node, now we can do the XOR computation\n\t\t\tmax_xor = max(max_xor, node[\"#\"] ^ num)\n\n\n return max_xor", "slug": "maximum-xor-of-two-numbers-in-an-array", "post_title": "Python O(N) Trie Solution w/comments and explanations", "user": "crippled_baby", "upvotes": 2, "views": 904, "problem_title": "maximum xor of two numbers in an array", "number": 421, "acceptance": 0.545, "difficulty": "Medium", "__index_level_0__": 7492, "question": "Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.\n Example 1:\nInput: nums = [3,10,5,25,2,8]\nOutput: 28\nExplanation: The maximum result is 5 XOR 25 = 28.\nExample 2:\nInput: nums = [14,70,53,83,49,91,36,80,92,51,66,70]\nOutput: 127\n Constraints:\n1 <= nums.length <= 2 * 105\n0 <= nums[i] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/reconstruct-original-digits-from-english/discuss/1556493/Python3-One-pass-solution", "python_solutions": "class Solution:\n def originalDigits(self, s: str) -> str:\n c = collections.Counter(s)\n \n digit_count = [0] * 10\n digit_count[0] = c['z']\n digit_count[2] = c['w']\n digit_count[4] = c['u']\n digit_count[6] = c['x']\n digit_count[8] = c['g']\n \n digit_count[3] = c['h'] - digit_count[8]\n digit_count[5] = c['f'] - digit_count[4]\n digit_count[7] = c['s'] - digit_count[6]\n \n digit_count[9] = c['i'] - digit_count[5] - digit_count[6] - digit_count[8]\n digit_count[1] = c['n'] - digit_count[9] * 2 - digit_count[7]\n \n return \"\".join([str(idx) * cnt for idx, cnt in enumerate(digit_count) if cnt > 0])", "slug": "reconstruct-original-digits-from-english", "post_title": "[Python3] One pass solution", "user": "maosipov11", "upvotes": 2, "views": 361, "problem_title": "reconstruct original digits from english", "number": 423, "acceptance": 0.513, "difficulty": "Medium", "__index_level_0__": 7499, "question": "Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.\n Example 1:\nInput: s = \"owoztneoer\"\nOutput: \"012\"\nExample 2:\nInput: s = \"fviefuro\"\nOutput: \"45\"\n Constraints:\n1 <= s.length <= 105\ns[i] is one of the characters [\"e\",\"g\",\"f\",\"i\",\"h\",\"o\",\"n\",\"s\",\"r\",\"u\",\"t\",\"w\",\"v\",\"x\",\"z\"].\ns is guaranteed to be valid." }, { "post_href": "https://leetcode.com/problems/longest-repeating-character-replacement/discuss/900524/Simple-Python-solution-moving-window-O(n)-time-O(1)-space", "python_solutions": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n \n # Maintain a dictionary that keeps track of last 'window' characters\n # See if 'window' size minus occurrences of the most common char is <= k, if so it's valid\n # Run time is O(length of string * size of alphabet)\n\t\t# Space is O(size of alphabet)\n \n d = {}\n window = 0\n \n for i, char in enumerate(s):\n d[char] = d.get(char, 0) + 1\n if window+1 - max(d.values()) <= k:\n window += 1\n else:\n d[s[i-window]] -= 1\n \n return window", "slug": "longest-repeating-character-replacement", "post_title": "Simple Python solution, moving window O(n) time, O(1) space", "user": "wesleyliao3", "upvotes": 16, "views": 2100, "problem_title": "longest repeating character replacement", "number": 424, "acceptance": 0.515, "difficulty": "Medium", "__index_level_0__": 7505, "question": "You are given a string s and an integer k. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most k times.\nReturn the length of the longest substring containing the same letter you can get after performing the above operations.\n Example 1:\nInput: s = \"ABAB\", k = 2\nOutput: 4\nExplanation: Replace the two 'A's with two 'B's or vice versa.\nExample 2:\nInput: s = \"AABABBA\", k = 1\nOutput: 4\nExplanation: Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\nThe substring \"BBBB\" has the longest repeating letters, which is 4.\nThere may exists other ways to achieve this answer too.\n Constraints:\n1 <= s.length <= 105\ns consists of only uppercase English letters.\n0 <= k <= s.length" }, { "post_href": "https://leetcode.com/problems/construct-quad-tree/discuss/874250/Python3-building-tree-recursively", "python_solutions": "class Solution:\n def construct(self, grid: List[List[int]]) -> 'Node':\n \n def fn(x0, x1, y0, y1): \n \"\"\"Return QuadTree subtree.\"\"\"\n val = {grid[i][j] for i, j in product(range(x0, x1), range(y0, y1))}\n if len(val) == 1: return Node(val.pop(), True, None, None, None, None)\n tl = fn(x0, (x0+x1)//2, y0, (y0+y1)//2)\n tr = fn(x0, (x0+x1)//2, (y0+y1)//2, y1)\n bl = fn((x0+x1)//2, x1, y0, (y0+y1)//2)\n br = fn((x0+x1)//2, x1, (y0+y1)//2, y1)\n return Node(None, False, tl, tr, bl, br)\n \n n = len(grid)\n return fn(0, n, 0, n)", "slug": "construct-quad-tree", "post_title": "[Python3] building tree recursively", "user": "ye15", "upvotes": 2, "views": 167, "problem_title": "construct quad tree", "number": 427, "acceptance": 0.6629999999999999, "difficulty": "Medium", "__index_level_0__": 7552, "question": "Given a n * n matrix grid of 0's and 1's only. We want to represent grid with a Quad-Tree.\nReturn the root of the Quad-Tree representing grid.\nA Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:\nval: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the val to True or False when isLeaf is False, and both are accepted in the answer.\nisLeaf: True if the node is a leaf node on the tree or False if the node has four children.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}\nWe can construct a Quad-Tree from a two-dimensional area using the following steps:\nIf the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.\nIf the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.\nRecurse for each of the children with the proper sub-grid.\nIf you want to know more about the Quad-Tree, you can refer to the wiki.\nQuad-Tree format:\nYou don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.\nIt is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].\nIf the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.\n Example 1:\nInput: grid = [[0,1],[1,0]]\nOutput: [[0,1],[1,0],[1,1],[1,1],[1,0]]\nExplanation: The explanation of this example is shown below:\nNotice that 0 represents False and 1 represents True in the photo representing the Quad-Tree.\nExample 2:\nInput: grid = [[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,0,0,0,0]]\nOutput: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nExplanation: All values in the grid are not the same. We divide the grid into four sub-grids.\nThe topLeft, bottomLeft and bottomRight each has the same value.\nThe topRight have different values so we divide it into 4 sub-grids where each has the same value.\nExplanation is shown in the photo below:\n Constraints:\nn == grid.length == grid[i].length\nn == 2x where 0 <= x <= 6" }, { "post_href": "https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/2532005/Python-BFS", "python_solutions": "class Solution:\n def levelOrder(self, root: 'Node') -> List[List[int]]:\n result = [] \n q = deque([root] if root else [])\n while q:\n result.append([])\n for _ in range(len(q)):\n node = q.popleft()\n result[-1].append(node.val)\n q.extend(node.children)\n \n return result", "slug": "n-ary-tree-level-order-traversal", "post_title": "Python, BFS", "user": "blue_sky5", "upvotes": 14, "views": 1300, "problem_title": "n ary tree level order traversal", "number": 429, "acceptance": 0.706, "difficulty": "Medium", "__index_level_0__": 7558, "question": "Given an n-ary tree, return the level order traversal of its nodes' values.\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n Example 1:\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [[1],[3,2,4],[5,6]]\nExample 2:\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n Constraints:\nThe height of the n-ary tree is less than or equal to 1000\nThe total number of nodes is between [0, 104]" }, { "post_href": "https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/discuss/1550377/Python-Recursion%3A-Easy-to-understand-with-Explanation", "python_solutions": "class Solution:\n def flatten(self, head: 'Node') -> 'Node':\n def getTail(node):\n prev = None\n while node:\n _next = node.next\n if node.child:\n\t\t\t\t\t# ... <-> node <-> node.child <-> ...\n node.next = node.child\n node.child = None\n node.next.prev = node\n\t\t\t\t\t# get the end node of the node.child list\n prev = getTail(node.next)\n if _next:\n\t\t\t\t\t\t# ... <-> prev (end node) <-> _next (originally node.next) <-> ...\n _next.prev = prev\n prev.next = _next\n else:\n prev = node\n node = _next # loop through the list of nodes\n return prev # return end node\n \n getTail(head)\n return head", "slug": "flatten-a-multilevel-doubly-linked-list", "post_title": "Python Recursion: Easy-to-understand with Explanation", "user": "zayne-siew", "upvotes": 6, "views": 501, "problem_title": "flatten a multilevel doubly linked list", "number": 430, "acceptance": 0.595, "difficulty": "Medium", "__index_level_0__": 7597, "question": "You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below.\nGiven the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list.\nReturn the head of the flattened list. The nodes in the list must have all of their child pointers set to null.\n Example 1:\nInput: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\nOutput: [1,2,3,7,8,11,12,9,10,4,5,6]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\nExample 2:\nInput: head = [1,2,null,3]\nOutput: [1,3,2]\nExplanation: The multilevel linked list in the input is shown.\nAfter flattening the multilevel linked list it becomes:\nExample 3:\nInput: head = []\nOutput: []\nExplanation: There could be empty list in the input.\n Constraints:\nThe number of Nodes will not exceed 1000.\n1 <= Node.val <= 105\n How the multilevel linked list is represented in test cases:\nWe use the multilevel linked list from Example 1 above:\n 1---2---3---4---5---6--NULL\n |\n 7---8---9---10--NULL\n |\n 11--12--NULL\nThe serialization of each level is as follows:\n[1,2,3,4,5,6,null]\n[7,8,9,10,null]\n[11,12,null]\nTo serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:\n[1, 2, 3, 4, 5, 6, null]\n |\n[null, null, 7, 8, 9, 10, null]\n |\n[ null, 11, 12, null]\nMerging the serialization of each level and removing trailing nulls we obtain:\n[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]" }, { "post_href": "https://leetcode.com/problems/minimum-genetic-mutation/discuss/2769493/SIMPLE-PYTHON-SOLUTION-USING-BFS", "python_solutions": "class Solution:\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n dic=defaultdict(lambda :0)\n lst=[[start,0]]\n dic[start]=1\n while lst:\n x,d=lst.pop(0)\n if x==end:\n return d\n for i in range(len(bank)):\n ct=0\n for j in range(8):\n if x[j]!=bank[i][j]:\n ct+=1\n if ct==1:\n if dic[bank[i]]==0:\n lst.append([bank[i],d+1])\n dic[bank[i]]=1\n return -1", "slug": "minimum-genetic-mutation", "post_title": "SIMPLE PYTHON SOLUTION USING BFS", "user": "beneath_ocean", "upvotes": 2, "views": 148, "problem_title": "minimum genetic mutation", "number": 433, "acceptance": 0.52, "difficulty": "Medium", "__index_level_0__": 7622, "question": "A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.\nSuppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string.\nFor example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation.\nThere is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.\nGiven the two gene strings startGene and endGene and the gene bank bank, return the minimum number of mutations needed to mutate from startGene to endGene. If there is no such a mutation, return -1.\nNote that the starting point is assumed to be valid, so it might not be included in the bank.\n Example 1:\nInput: startGene = \"AACCGGTT\", endGene = \"AACCGGTA\", bank = [\"AACCGGTA\"]\nOutput: 1\nExample 2:\nInput: startGene = \"AACCGGTT\", endGene = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\nOutput: 2\n Constraints:\n0 <= bank.length <= 10\nstartGene.length == endGene.length == bank[i].length == 8\nstartGene, endGene, and bank[i] consist of only the characters ['A', 'C', 'G', 'T']." }, { "post_href": "https://leetcode.com/problems/number-of-segments-in-a-string/discuss/1015806/One-Line-python-Solution", "python_solutions": "class Solution:\n def countSegments(self, s: str) -> int:\n return len([i for i in s.split(\" \") if i!=\"\"])", "slug": "number-of-segments-in-a-string", "post_title": "One Line python Solution", "user": "moazmar", "upvotes": 3, "views": 464, "problem_title": "number of segments in a string", "number": 434, "acceptance": 0.377, "difficulty": "Easy", "__index_level_0__": 7656, "question": "Given a string s, return the number of segments in the string.\nA segment is defined to be a contiguous sequence of non-space characters.\n Example 1:\nInput: s = \"Hello, my name is John\"\nOutput: 5\nExplanation: The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]\nExample 2:\nInput: s = \"Hello\"\nOutput: 1\n Constraints:\n0 <= s.length <= 300\ns consists of lowercase and uppercase English letters, digits, or one of the following characters \"!@#$%^&*()_+-=',.:\".\nThe only space character in s is ' '." }, { "post_href": "https://leetcode.com/problems/non-overlapping-intervals/discuss/1896849/Python-easy-to-read-and-understand-or-sorting", "python_solutions": "class Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: x[1])\n n = len(intervals)\n ans, curr = 1, intervals[0]\n\n for i in range(n):\n if intervals[i][0] >= curr[1]:\n ans += 1\n curr = intervals[i]\n\n return n - ans", "slug": "non-overlapping-intervals", "post_title": "Python easy to read and understand | sorting", "user": "sanial2001", "upvotes": 2, "views": 196, "problem_title": "non overlapping intervals", "number": 435, "acceptance": 0.499, "difficulty": "Medium", "__index_level_0__": 7682, "question": "Given an array of intervals intervals where intervals[i] = [starti, endi], return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.\n Example 1:\nInput: intervals = [[1,2],[2,3],[3,4],[1,3]]\nOutput: 1\nExplanation: [1,3] can be removed and the rest of the intervals are non-overlapping.\nExample 2:\nInput: intervals = [[1,2],[1,2],[1,2]]\nOutput: 2\nExplanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.\nExample 3:\nInput: intervals = [[1,2],[2,3]]\nOutput: 0\nExplanation: You don't need to remove any of the intervals since they're already non-overlapping.\n Constraints:\n1 <= intervals.length <= 105\nintervals[i].length == 2\n-5 * 104 <= starti < endi <= 5 * 104" }, { "post_href": "https://leetcode.com/problems/find-right-interval/discuss/2812012/Python-Sort-and-Two-Pointers-(Same-approach-as-826.-Most-Profit-Assigning-Work)", "python_solutions": "class Solution:\n def findRightInterval(self, intervals: List[List[int]]) -> List[int]:\n start = sorted([[intervals[i][0], i] for i in range(len(intervals))])\n end = sorted([[intervals[i][1], i] for i in range(len(intervals))])\n i = 0\n res = []\n for endVal, endIdx in end:\n while i < len(start) and (endVal > start[i][0]):\n i += 1\n if i < len(start):\n res.append(start[i][1])\n else:\n while len(res) < len(start):\n res.append(-1)\n ans = []\n for i in range(len(end)):\n ans.append((end[i][1], res[i]))\n ans.sort()\n return [ele[1] for ele in sorted([[a[1], b] for a, b in zip(end, res)])]", "slug": "find-right-interval", "post_title": "[Python] Sort and Two Pointers (Same approach as # 826. Most Profit Assigning Work)", "user": "low_key_low_key", "upvotes": 0, "views": 4, "problem_title": "find right interval", "number": 436, "acceptance": 0.504, "difficulty": "Medium", "__index_level_0__": 7700, "question": "You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.\nThe right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.\nReturn an array of right interval indices for each interval i. If no right interval exists for interval i, then put -1 at index i.\n Example 1:\nInput: intervals = [[1,2]]\nOutput: [-1]\nExplanation: There is only one interval in the collection, so it outputs -1.\nExample 2:\nInput: intervals = [[3,4],[2,3],[1,2]]\nOutput: [-1,0,1]\nExplanation: There is no right interval for [3,4].\nThe right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.\nThe right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.\nExample 3:\nInput: intervals = [[1,4],[2,3],[3,4]]\nOutput: [-1,2,-1]\nExplanation: There is no right interval for [1,4] and [3,4].\nThe right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.\n Constraints:\n1 <= intervals.length <= 2 * 104\nintervals[i].length == 2\n-106 <= starti <= endi <= 106\nThe start point of each interval is unique." }, { "post_href": "https://leetcode.com/problems/path-sum-iii/discuss/1049652/Python-Solution", "python_solutions": "class Solution:\n def pathSum(self, root: TreeNode, sum: int) -> int:\n \n global result\n result = 0\n \n def dfs(node, target):\n if node is None: return\n find_path_from_node(node, target)\n dfs(node.left, target)\n dfs(node.right, target)\n \n def find_path_from_node(node, target):\n global result\n if node is None: return\n if node.val == target: result += 1\n find_path_from_node(node.left, target-node.val)\n find_path_from_node(node.right, target-node.val)\n \n dfs(root, sum)\n \n return result", "slug": "path-sum-iii", "post_title": "Python Solution", "user": "dev-josh", "upvotes": 14, "views": 631, "problem_title": "path sum iii", "number": 437, "acceptance": 0.486, "difficulty": "Medium", "__index_level_0__": 7713, "question": "Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.\nThe path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).\n Example 1:\nInput: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\nOutput: 3\nExplanation: The paths that sum to 8 are shown.\nExample 2:\nInput: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\nOutput: 3\n Constraints:\nThe number of nodes in the tree is in the range [0, 1000].\n-109 <= Node.val <= 109\n-1000 <= targetSum <= 1000" }, { "post_href": "https://leetcode.com/problems/find-all-anagrams-in-a-string/discuss/1738367/Python-Sliding-Window(-)-algorithm-Detailed-Explanation-Concise-Soln-or-Faster-than-80", "python_solutions": "class Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]: \n # take counter of first n elements in s_dict with n = len(p) - 1\n s_dict = collections.Counter(s[:len(p)-1]) \n # counter of p, this should not be changed\n p_dict = collections.Counter(p)\n start = 0\n # final result list\n res = []\n # We iterate over the string s, and in each step we check if s_dict and p_dict match\n for i in range(len(p)-1, len(s)):\n # updating the counter & adding the character\n s_dict[s[i]] += 1\n # checking if counters match\n if s_dict == p_dict:\n res.append(start)\n # remove the first element from counter\n s_dict[s[start]] -= 1\n #if element count = 0, pop it from the counter\n if s_dict[s[start]] == 0:\n del s_dict[s[start]]\n start += 1\n \n return res", "slug": "find-all-anagrams-in-a-string", "post_title": "\ud83d\udd0e Python - Sliding Window( \ud83d\ude85 \ud83e\ude9f) algorithm Detailed Explanation, Concise Soln | Faster than 80%", "user": "mystic_sd2001", "upvotes": 16, "views": 1400, "problem_title": "find all anagrams in a string", "number": 438, "acceptance": 0.49, "difficulty": "Medium", "__index_level_0__": 7723, "question": "Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n Example 1:\nInput: s = \"cbaebabacd\", p = \"abc\"\nOutput: [0,6]\nExplanation:\nThe substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\nThe substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\nExample 2:\nInput: s = \"abab\", p = \"ab\"\nOutput: [0,1,2]\nExplanation:\nThe substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\nThe substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\nThe substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n Constraints:\n1 <= s.length, p.length <= 3 * 104\ns and p consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/k-th-smallest-in-lexicographical-order/discuss/1608540/Python3-traverse-denary-trie", "python_solutions": "class Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n \n def fn(x): \n \"\"\"Return node counts in denary trie.\"\"\"\n ans, diff = 0, 1\n while x <= n: \n ans += min(n - x + 1, diff)\n x *= 10 \n diff *= 10 \n return ans \n \n x = 1\n while k > 1: \n cnt = fn(x)\n if k > cnt: k -= cnt; x += 1\n else: k -= 1; x *= 10 \n return x", "slug": "k-th-smallest-in-lexicographical-order", "post_title": "[Python3] traverse denary trie", "user": "ye15", "upvotes": 3, "views": 435, "problem_title": "k th smallest in lexicographical order", "number": 440, "acceptance": 0.308, "difficulty": "Hard", "__index_level_0__": 7769, "question": "Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].\n Example 1:\nInput: n = 13, k = 2\nOutput: 10\nExplanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\nExample 2:\nInput: n = 1, k = 1\nOutput: 1\n Constraints:\n1 <= k <= n <= 109" }, { "post_href": "https://leetcode.com/problems/arranging-coins/discuss/2801813/Python-Simple-Binary-Search", "python_solutions": "class Solution:\n def arrangeCoins(self, n: int) -> int:\n\n first = 1\n last = n\n if n==1:\n return 1\n while first <= last:\n mid = (first+last)//2\n\n if mid*(mid+1) == 2*n:\n return mid\n elif mid*(mid+1) > 2*n:\n last = mid-1\n else:\n first = mid+1\n return last", "slug": "arranging-coins", "post_title": "Python Simple Binary Search", "user": "BhavyaBusireddy", "upvotes": 2, "views": 69, "problem_title": "arranging coins", "number": 441, "acceptance": 0.462, "difficulty": "Easy", "__index_level_0__": 7770, "question": "You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.\nGiven the integer n, return the number of complete rows of the staircase you will build.\n Example 1:\nInput: n = 5\nOutput: 2\nExplanation: Because the 3rd row is incomplete, we return 2.\nExample 2:\nInput: n = 8\nOutput: 3\nExplanation: Because the 4th row is incomplete, we return 3.\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/find-all-duplicates-in-an-array/discuss/396890/Two-Solutions-in-Python-3-(-O(n)-time-)-(-O(1)-space-)", "python_solutions": "class Solution:\n def findDuplicates(self, N: List[int]) -> List[int]:\n S, A = set(), []\n for n in N:\n if n in S: A.append(n)\n else: S.add(n)\n return A", "slug": "find-all-duplicates-in-an-array", "post_title": "Two Solutions in Python 3 ( O(n) time ) ( O(1) space )", "user": "junaidmansuri", "upvotes": 9, "views": 1700, "problem_title": "find all duplicates in an array", "number": 442, "acceptance": 0.7340000000000001, "difficulty": "Medium", "__index_level_0__": 7818, "question": "Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.\nYou must write an algorithm that runs in O(n) time and uses only constant extra space.\n Example 1:\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [2,3]\nExample 2:\nInput: nums = [1,1,2]\nOutput: [1]\nExample 3:\nInput: nums = [1]\nOutput: []\n Constraints:\nn == nums.length\n1 <= n <= 105\n1 <= nums[i] <= n\nEach element in nums appears once or twice." }, { "post_href": "https://leetcode.com/problems/string-compression/discuss/1025555/Python3-Simple-and-Intuitive", "python_solutions": "class Solution:\n def compress(self, chars: List[str]) -> int:\n if not chars:\n return 0\n mychar = chars[0]\n count = 0\n length = len(chars)\n chars.append(\" \") # Append a space so last char group is not left out in loop\n for i in range(length+1): #+1 for extra space char we added\n char = chars.pop(0)\n if char == mychar: #if same character then just increase the count\n count += 1\n else:\n if count == 1: #if not same then append the char to chars\n chars.append(mychar) #if count is 1 don't append count\n elif count > 1:\n chars.append(mychar)\n chars += (list(str(count))) #if count > 1 append count as a string\n mychar = char #update mychar as the new different char in chars\n count = 1 #reset count to 1 as we have already read the new char\n return len(chars) #since all previous are popped, only the answer remains in chars now", "slug": "string-compression", "post_title": "Python3 Simple and Intuitive", "user": "upenj", "upvotes": 10, "views": 1800, "problem_title": "string compression", "number": 443, "acceptance": 0.489, "difficulty": "Medium", "__index_level_0__": 7866, "question": "Given an array of characters chars, compress it using the following algorithm:\nBegin with an empty string s. For each group of consecutive repeating characters in chars:\nIf the group's length is 1, append the character to s.\nOtherwise, append the character followed by the group's length.\nThe compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.\nAfter you are done modifying the input array, return the new length of the array.\nYou must write an algorithm that uses only constant extra space.\n Example 1:\nInput: chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\nOutput: Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\nExplanation: The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".\nExample 2:\nInput: chars = [\"a\"]\nOutput: Return 1, and the first character of the input array should be: [\"a\"]\nExplanation: The only group is \"a\", which remains uncompressed since it's a single character.\nExample 3:\nInput: chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\nOutput: Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\nExplanation: The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".\n Constraints:\n1 <= chars.length <= 2000\nchars[i] is a lowercase English letter, uppercase English letter, digit, or symbol." }, { "post_href": "https://leetcode.com/problems/add-two-numbers-ii/discuss/486730/Python-Using-One-Stack-Memory-Usage%3A-Less-than-100", "python_solutions": "class Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n\t\n n1 = n2 = 0\n ptr1, ptr2 = l1, l2\n stack = []\n \n while ptr1: n1 += 1; ptr1 = ptr1.next\n while ptr2: n2 += 1; ptr2 = ptr2.next\n max_len = max(n1, n2)\n \n while max_len:\n a = b = 0\n if max_len <= n1: a = l1.val; l1 = l1.next\n if max_len <= n2: b = l2.val; l2 = l2.next\n stack.append(a + b)\n max_len -= 1\n \n sumval, head = 0, None\n while stack or sumval:\n if stack: sumval += stack.pop()\n node = ListNode(sumval % 10)\n node.next = head\n head = node\n sumval //= 10\n return head", "slug": "add-two-numbers-ii", "post_title": "Python - Using One Stack [Memory Usage: Less than 100%]", "user": "mmbhatk", "upvotes": 11, "views": 766, "problem_title": "add two numbers ii", "number": 445, "acceptance": 0.595, "difficulty": "Medium", "__index_level_0__": 7889, "question": "You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\nYou may assume the two numbers do not contain any leading zero, except the number 0 itself.\n Example 1:\nInput: l1 = [7,2,4,3], l2 = [5,6,4]\nOutput: [7,8,0,7]\nExample 2:\nInput: l1 = [2,4,3], l2 = [5,6,4]\nOutput: [8,0,7]\nExample 3:\nInput: l1 = [0], l2 = [0]\nOutput: [0]\n Constraints:\nThe number of nodes in each linked list is in the range [1, 100].\n0 <= Node.val <= 9\nIt is guaranteed that the list represents a number that does not have leading zeros.\n Follow up: Could you solve it without reversing the input lists?" }, { "post_href": "https://leetcode.com/problems/arithmetic-slices-ii-subsequence/discuss/1292744/Python3-freq-tables", "python_solutions": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n ans = 0 \n freq = [defaultdict(int) for _ in range(len(nums))] # arithmetic sub-seqs\n for i, x in enumerate(nums): \n for ii in range(i): \n diff = x - nums[ii]\n ans += freq[ii].get(diff, 0)\n freq[i][diff] += 1 + freq[ii][diff]\n return ans", "slug": "arithmetic-slices-ii-subsequence", "post_title": "[Python3] freq tables", "user": "ye15", "upvotes": 2, "views": 120, "problem_title": "arithmetic slices ii subsequence", "number": 446, "acceptance": 0.3989999999999999, "difficulty": "Hard", "__index_level_0__": 7914, "question": "Given an integer array nums, return the number of all the arithmetic subsequences of nums.\nA 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.\nFor example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.\nFor example, [1, 1, 2, 5, 7] is not an arithmetic sequence.\nA subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\nFor example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\nThe test cases are generated so that the answer fits in 32-bit integer.\n Example 1:\nInput: nums = [2,4,6,8,10]\nOutput: 7\nExplanation: 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]\nExample 2:\nInput: nums = [7,7,7,7,7]\nOutput: 16\nExplanation: Any subsequence of this array is arithmetic.\n Constraints:\n1 <= nums.length <= 1000\n-231 <= nums[i] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/number-of-boomerangs/discuss/355205/Solution-in-Python-3", "python_solutions": "class Solution:\n def numberOfBoomerangs(self, p: List[List[int]]) -> int:\n L, t = len(p), 0\n D = [[0]*L for i in range(L)]\n for i in range(L):\n \tE = {}\n \tfor j in range(L):\n \t\tif j > i: D[i][j] = D[j][i] = (p[j][0]-p[i][0])**2 + (p[j][1]-p[i][1])**2\n \t\tE[D[i][j]] = E[D[i][j]] + 1 if D[i][j] in E else 1\n \tt += sum(r*(r-1) for r in E.values())\n return t\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "number-of-boomerangs", "post_title": "Solution in Python 3", "user": "junaidmansuri", "upvotes": 2, "views": 847, "problem_title": "number of boomerangs", "number": 447, "acceptance": 0.547, "difficulty": "Medium", "__index_level_0__": 7917, "question": "You are given n points in the plane that are all distinct, where points[i] = [xi, yi]. A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).\nReturn the number of boomerangs.\n Example 1:\nInput: points = [[0,0],[1,0],[2,0]]\nOutput: 2\nExplanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].\nExample 2:\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: 2\nExample 3:\nInput: points = [[1,1]]\nOutput: 0\n Constraints:\nn == points.length\n1 <= n <= 500\npoints[i].length == 2\n-104 <= xi, yi <= 104\nAll the points are unique." }, { "post_href": "https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/discuss/313703/Python-3", "python_solutions": "class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n for n in nums:\n a = abs(n) - 1\n if nums[a] > 0: nums[a] *= -1\n return [i+1 for i in range(len(nums)) if nums[i] > 0]", "slug": "find-all-numbers-disappeared-in-an-array", "post_title": "Python 3", "user": "slight_edge", "upvotes": 54, "views": 7900, "problem_title": "find all numbers disappeared in an array", "number": 448, "acceptance": 0.597, "difficulty": "Easy", "__index_level_0__": 7919, "question": "Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.\n Example 1:\nInput: nums = [4,3,2,7,8,2,3,1]\nOutput: [5,6]\nExample 2:\nInput: nums = [1,1]\nOutput: [2]\n Constraints:\nn == nums.length\n1 <= n <= 105\n1 <= nums[i] <= n\n Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space." }, { "post_href": "https://leetcode.com/problems/delete-node-in-a-bst/discuss/543124/Python-O(-h-)-with-BST-property.-85%2B-w-Comment", "python_solutions": "class Solution:\n def deleteNode(self, root: TreeNode, key: int) -> TreeNode:\n \n if not root:\n return None\n \n if root.val > key:\n\t\t # Target node is smaller than currnet node, search left subtree\n\t\t\t\n root.left = self.deleteNode( root.left, key )\n\n elif root.val < key:\n\t\t # Target node is larger than currnet node, search right subtree\n\t\t\t\n root.right = self.deleteNode( root.right, key )\n\n else:\n # Current node is target node\n\t\t\t\n if (not root.left) or (not root.right):\n # At least one child is empty\n # Target node is replaced by either non-empty child or None\n root = root.left if root.left else root.right\n\n else:\n # Both two childs exist\n # Target node is replaced by smallest element of right subtree\n cur = root.right\n\n while cur.left:\n cur = cur.left\n\n root.val = cur.val\n root.right = self.deleteNode( root.right, cur.val )\n \n return root", "slug": "delete-node-in-a-bst", "post_title": "Python O( h ) with BST property. 85%+ [w/ Comment ]", "user": "brianchiang_tw", "upvotes": 8, "views": 605, "problem_title": "delete node in a bst", "number": 450, "acceptance": 0.5, "difficulty": "Medium", "__index_level_0__": 7962, "question": "Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.\nBasically, the deletion can be divided into two stages:\nSearch for a node to remove.\nIf the node is found, delete the node.\n Example 1:\nInput: root = [5,3,6,2,4,null,7], key = 3\nOutput: [5,4,6,2,null,null,7]\nExplanation: Given key to delete is 3. So we find the node with value 3 and delete it.\nOne valid answer is [5,4,6,2,null,null,7], shown in the above BST.\nPlease notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.\nExample 2:\nInput: root = [5,3,6,2,4,null,7], key = 0\nOutput: [5,3,6,2,4,null,7]\nExplanation: The tree does not contain a node with value = 0.\nExample 3:\nInput: root = [], key = 0\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n-105 <= Node.val <= 105\nEach node has a unique value.\nroot is a valid binary search tree.\n-105 <= key <= 105\n Follow up: Could you solve it with time complexity O(height of tree)?" }, { "post_href": "https://leetcode.com/problems/sort-characters-by-frequency/discuss/1024318/Python3-Solution-or-24-MS-Runtime-or-15.2-MB-Memoryor-Easy-to-understand-solution", "python_solutions": "class Solution:\n def frequencySort(self, s: str) -> str:\n \n ans_str = ''\n # Find unique characters\n characters = set(s)\n \n counts = []\n # Count their frequency\n for i in characters:\n counts.append([i,s.count(i)])\n \n\t\t# Sort characters according to their frequency\n counts = sorted(counts, key= lambda x: x[1], reverse = True)\n \n\t\t# Generate answer string by multiplying frequency count with the character\n for i,j in counts:\n ans_str += i*j\n \n return ans_str", "slug": "sort-characters-by-frequency", "post_title": "Python3 Solution | 24 MS Runtime | 15.2 MB Memory| Easy to understand solution", "user": "dakshal33", "upvotes": 5, "views": 401, "problem_title": "sort characters by frequency", "number": 451, "acceptance": 0.6859999999999999, "difficulty": "Medium", "__index_level_0__": 7984, "question": "Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.\nReturn the sorted string. If there are multiple answers, return any of them.\n Example 1:\nInput: s = \"tree\"\nOutput: \"eert\"\nExplanation: 'e' appears twice while 'r' and 't' both appear once.\nSo 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.\nExample 2:\nInput: s = \"cccaaa\"\nOutput: \"aaaccc\"\nExplanation: Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\nNote that \"cacaca\" is incorrect, as the same characters must be together.\nExample 3:\nInput: s = \"Aabb\"\nOutput: \"bbAa\"\nExplanation: \"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\nNote that 'A' and 'a' are treated as two different characters.\n Constraints:\n1 <= s.length <= 5 * 105\ns consists of uppercase and lowercase English letters and digits." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons/discuss/1686588/Python3-COMBO-Explained", "python_solutions": "class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n pts = sorted(points, key=lambda el: el[1])\n \n res, combo = 0, (float(\"-inf\"), float(\"-inf\"))\n for start, end in pts:\n if start <= combo[1]: # overlaps?\n combo = (max(combo[0], start), min(combo[1], end))\n else:\n combo = (start, end)\n res += 1\n \n return res", "slug": "minimum-number-of-arrows-to-burst-balloons", "post_title": "\u2714\ufe0f [Python3] \u27b5 COMBO \ud83c\udf38, Explained", "user": "artod", "upvotes": 9, "views": 290, "problem_title": "minimum number of arrows to burst balloons", "number": 452, "acceptance": 0.532, "difficulty": "Medium", "__index_level_0__": 8027, "question": "There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons.\nArrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.\nGiven the array points, return the minimum number of arrows that must be shot to burst all balloons.\n Example 1:\nInput: points = [[10,16],[2,8],[1,6],[7,12]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6].\n- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12].\nExample 2:\nInput: points = [[1,2],[3,4],[5,6],[7,8]]\nOutput: 4\nExplanation: One arrow needs to be shot for each balloon for a total of 4 arrows.\nExample 3:\nInput: points = [[1,2],[2,3],[3,4],[4,5]]\nOutput: 2\nExplanation: The balloons can be burst by 2 arrows:\n- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3].\n- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5].\n Constraints:\n1 <= points.length <= 105\npoints[i].length == 2\n-231 <= xstart < xend <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements/discuss/1909521/1-line-solution-beats-98-O(N)-time-and-96-O(1)-space-easy-to-understand", "python_solutions": "class Solution:\n def minMoves(self, nums: List[int]) -> int:\n return sum(nums) - (len(nums) * min(nums))", "slug": "minimum-moves-to-equal-array-elements", "post_title": "1 line solution; beats 98% O(N) time and 96% O(1) space; easy to understand", "user": "sahajamatya", "upvotes": 10, "views": 461, "problem_title": "minimum moves to equal array elements", "number": 453, "acceptance": 0.557, "difficulty": "Medium", "__index_level_0__": 8053, "question": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.\nIn one move, you can increment n - 1 elements of the array by 1.\n Example 1:\nInput: nums = [1,2,3]\nOutput: 3\nExplanation: Only three moves are needed (remember each move increments two elements):\n[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]\nExample 2:\nInput: nums = [1,1,1]\nOutput: 0\n Constraints:\nn == nums.length\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109\nThe answer is guaranteed to fit in a 32-bit integer." }, { "post_href": "https://leetcode.com/problems/4sum-ii/discuss/1741072/Python-Clean-and-concise-or-Detail-explanation-or-One-linear", "python_solutions": "class Solution:\n def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:\n \n # hashmap and final result count\n nums12, res = defaultdict(int), 0\n \n # storing all possible combinations of sum\n for i in nums1:\n for j in nums2:\n nums12[i+j] += 1\n \n # iterating the left out two array to find negation of same value\n for k in nums3:\n for l in nums4:\n res += nums12[-(k+l)]\n \n return res", "slug": "4sum-ii", "post_title": "[Python] Clean and concise | Detail explanation | One linear", "user": "sidheshwar_s", "upvotes": 19, "views": 939, "problem_title": "4sum ii", "number": 454, "acceptance": 0.573, "difficulty": "Medium", "__index_level_0__": 8069, "question": "Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:\n0 <= i, j, k, l < n\nnums1[i] + nums2[j] + nums3[k] + nums4[l] == 0\n Example 1:\nInput: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\nOutput: 2\nExplanation:\nThe two tuples are:\n1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0\nExample 2:\nInput: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\nOutput: 1\n Constraints:\nn == nums1.length\nn == nums2.length\nn == nums3.length\nn == nums4.length\n1 <= n <= 200\n-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228" }, { "post_href": "https://leetcode.com/problems/assign-cookies/discuss/1334075/Python-Solution-or-Two-Pointers-or-O(nlogn)", "python_solutions": "class Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n g.sort() # O(nlogn)\n s.sort() # O(nlogn)\n \n child_point = 0\n cookie_point = 0\n counter = 0\n \n # O(n)\n while child_point < len(g) and cookie_point < len(s):\n if g[child_point] <= s[cookie_point]:\n counter += 1\n child_point += 1\n cookie_point += 1\n else:\n cookie_point += 1\n \n return counter", "slug": "assign-cookies", "post_title": "Python Solution | Two Pointers | O(nlogn)", "user": "peatear-anthony", "upvotes": 2, "views": 267, "problem_title": "assign cookies", "number": 455, "acceptance": 0.505, "difficulty": "Easy", "__index_level_0__": 8099, "question": "Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.\nEach child i has a greed factor g[i], which is the minimum size of a cookie that the child will be content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.\n Example 1:\nInput: g = [1,2,3], s = [1,1]\nOutput: 1\nExplanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \nAnd even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\nYou need to output 1.\nExample 2:\nInput: g = [1,2], s = [1,2,3]\nOutput: 2\nExplanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \nYou have 3 cookies and their sizes are big enough to gratify all of the children, \nYou need to output 2.\n Constraints:\n1 <= g.length <= 3 * 104\n0 <= s.length <= 3 * 104\n1 <= g[i], s[j] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/132-pattern/discuss/2015125/Python-Solution-using-Stack", "python_solutions": "class Solution:\n def find132pattern(self, nums: List[int]) -> bool:\n if len(nums)<3:\n return False\n \n second_num = -math.inf\n stck = []\n # Try to find nums[i] < second_num < stck[-1]\n for i in range(len(nums) - 1, -1, -1):\n if nums[i] < second_num:\n return True\n # always ensure stack can be popped in increasing order\n while stck and stck[-1] < nums[i]:\n\t\t\t\tsecond_num = stck.pop() # this will ensure second_num < stck[-1] for next iteration\n\n stck.append(nums[i])\n return False", "slug": "132-pattern", "post_title": "\u2705 Python Solution using Stack", "user": "constantine786", "upvotes": 37, "views": 3400, "problem_title": "132 pattern", "number": 456, "acceptance": 0.325, "difficulty": "Medium", "__index_level_0__": 8121, "question": "Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].\nReturn true if there is a 132 pattern in nums, otherwise, return false.\n Example 1:\nInput: nums = [1,2,3,4]\nOutput: false\nExplanation: There is no 132 pattern in the sequence.\nExample 2:\nInput: nums = [3,1,4,2]\nOutput: true\nExplanation: There is a 132 pattern in the sequence: [1, 4, 2].\nExample 3:\nInput: nums = [-1,3,2,0]\nOutput: true\nExplanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n Constraints:\nn == nums.length\n1 <= n <= 2 * 105\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/circular-array-loop/discuss/1317119/Python-3-or-Short-Python-Set-or-Explanation", "python_solutions": "class Solution:\n def circularArrayLoop(self, nums: List[int]) -> bool:\n n, visited = len(nums), set()\n for i in range(n):\n if i not in visited:\n local_s = set()\n while True:\n if i in local_s: return True\n if i in visited: break # credit to @crazyhyz, add this condition to avoid revisited\n visited.add(i)\n local_s.add(i)\n prev, i = i, (i + nums[i]) % n\n if prev == i or (nums[i] > 0) != (nums[prev] > 0): break\n return False", "slug": "circular-array-loop", "post_title": "Python 3 | Short Python, Set | Explanation", "user": "idontknoooo", "upvotes": 10, "views": 1200, "problem_title": "circular array loop", "number": 457, "acceptance": 0.3229999999999999, "difficulty": "Medium", "__index_level_0__": 8141, "question": "You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i:\nIf nums[i] is positive, move nums[i] steps forward, and\nIf nums[i] is negative, move nums[i] steps backward.\nSince the array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element.\nA cycle in the array consists of a sequence of indices seq of length k where:\nFollowing the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...\nEvery nums[seq[j]] is either all positive or all negative.\nk > 1\nReturn true if there is a cycle in nums, or false otherwise.\n Example 1:\nInput: nums = [2,-1,1,2,2]\nOutput: true\nExplanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nWe can see the cycle 0 --> 2 --> 3 --> 0 --> ..., and all of its nodes are white (jumping in the same direction).\nExample 2:\nInput: nums = [-1,-2,-3,-4,-5,6]\nOutput: false\nExplanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nThe only cycle is of size 1, so we return false.\nExample 3:\nInput: nums = [1,-1,5,1,4]\nOutput: true\nExplanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\nWe can see the cycle 0 --> 1 --> 0 --> ..., and while it is of size > 1, it has a node jumping forward and a node jumping backward, so it is not a cycle.\nWe can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are white (jumping in the same direction).\n Constraints:\n1 <= nums.length <= 5000\n-1000 <= nums[i] <= 1000\nnums[i] != 0\n Follow up: Could you solve it in O(n) time complexity and O(1) extra space complexity?" }, { "post_href": "https://leetcode.com/problems/poor-pigs/discuss/935581/C%2B%2BPythonPicture-1-line-greedy-solution-with-N-dimension-puzzle-cube-scan", "python_solutions": "class Solution:\n def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:\n return ceil(log(buckets) / log(minutesToTest / minutesToDie + 1));", "slug": "poor-pigs", "post_title": "[C++/Python/Picture] 1-line greedy solution with N-dimension puzzle cube scan", "user": "codedayday", "upvotes": 34, "views": 3400, "problem_title": "poor pigs", "number": 458, "acceptance": 0.643, "difficulty": "Hard", "__index_level_0__": 8151, "question": "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.\nYou can feed the pigs according to these steps:\nChoose some live pigs to feed.\nFor each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.\nWait for minutesToDie minutes. You may not feed any other pigs during this time.\nAfter minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.\nRepeat this process until you run out of time.\nGiven buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.\n Example 1:\nInput: buckets = 4, minutesToDie = 15, minutesToTest = 15\nOutput: 2\nExplanation: We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\nAt time 15, there are 4 possible outcomes:\n- If only the first pig dies, then bucket 1 must be poisonous.\n- If only the second pig dies, then bucket 3 must be poisonous.\n- If both pigs die, then bucket 2 must be poisonous.\n- If neither pig dies, then bucket 4 must be poisonous.\nExample 2:\nInput: buckets = 4, minutesToDie = 15, minutesToTest = 30\nOutput: 2\nExplanation: We can determine the poisonous bucket as follows:\nAt time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\nAt time 15, there are 2 possible outcomes:\n- If either pig dies, then the poisonous bucket is the one it was fed.\n- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.\nAt time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.\n Constraints:\n1 <= buckets <= 1000\n1 <= minutesToDie <= minutesToTest <= 100" }, { "post_href": "https://leetcode.com/problems/repeated-substring-pattern/discuss/2304034/Python-93.74-fasters-or-Python-Simplest-Solution-With-Explanation-or-Beg-to-adv-or-Slicing", "python_solutions": "class Solution:\n def repeatedSubstringPattern(self, s: str) -> bool:\n return s in s[1:] + s[:-1]", "slug": "repeated-substring-pattern", "post_title": "Python 93.74% fasters | Python Simplest Solution With Explanation | Beg to adv | Slicing", "user": "rlakshay14", "upvotes": 6, "views": 332, "problem_title": "repeated substring pattern", "number": 459, "acceptance": 0.437, "difficulty": "Easy", "__index_level_0__": 8155, "question": "Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together.\n Example 1:\nInput: s = \"abab\"\nOutput: true\nExplanation: It is the substring \"ab\" twice.\nExample 2:\nInput: s = \"aba\"\nOutput: false\nExample 3:\nInput: s = \"abcabcabcabc\"\nOutput: true\nExplanation: It is the substring \"abc\" four times or the substring \"abcabc\" twice.\n Constraints:\n1 <= s.length <= 104\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/hamming-distance/discuss/1585601/Handmade-binary-function-(time%3A-O(L))", "python_solutions": "class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n def get_bin(num):\n res = []\n while num > 0:\n res.append(num % 2)\n num //= 2\n return ''.join(str(num) for num in res[::-1])\n \n if x < y:\n x, y = y, x\n \n bin_x, bin_y = get_bin(x), get_bin(y)\n res = 0\n s1, s2 = len(bin_x), len(bin_y)\n bin_y = '0' * (s1 - s2) + bin_y\n \n return sum(bin_x[i] != bin_y[i] for i in range(s1))", "slug": "hamming-distance", "post_title": "Handmade binary function (time: O(L))", "user": "kryuki", "upvotes": 3, "views": 121, "problem_title": "hamming distance", "number": 461, "acceptance": 0.7490000000000001, "difficulty": "Easy", "__index_level_0__": 8184, "question": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\nGiven two integers x and y, return the Hamming distance between them.\n Example 1:\nInput: x = 1, y = 4\nOutput: 2\nExplanation:\n1 (0 0 0 1)\n4 (0 1 0 0)\n \u2191 \u2191\nThe above arrows point to positions where the corresponding bits are different.\nExample 2:\nInput: x = 3, y = 1\nOutput: 1\n Constraints:\n0 <= x, y <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/discuss/2218363/Python3-simple-solution%3A-Get-the-mid-element-from-the-sorted-array", "python_solutions": "class Solution:\n def minMoves2(self, nums: List[int]) -> int:\n nums.sort()\n mid = nums[len(nums)//2]\n result = 0\n for i in nums:\n result+=abs(mid-i)\n return result", "slug": "minimum-moves-to-equal-array-elements-ii", "post_title": "\ud83d\udccc Python3 simple solution: Get the mid element from the sorted array", "user": "Dark_wolf_jss", "upvotes": 6, "views": 68, "problem_title": "minimum moves to equal array elements ii", "number": 462, "acceptance": 0.602, "difficulty": "Medium", "__index_level_0__": 8223, "question": "Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.\nIn one move, you can increment or decrement an element of the array by 1.\nTest cases are designed so that the answer will fit in a 32-bit integer.\n Example 1:\nInput: nums = [1,2,3]\nOutput: 2\nExplanation:\nOnly two moves are needed (remember each move increments or decrements one element):\n[1,2,3] => [2,2,3] => [2,2,2]\nExample 2:\nInput: nums = [1,10,2,9]\nOutput: 16\n Constraints:\nn == nums.length\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/island-perimeter/discuss/343154/Solution-in-Python-3", "python_solutions": "class Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int: \n \tM, N, p = len(grid), len(grid[0]), 0\n \tfor m in range(M):\n \t\tfor n in range(N):\n \t\t\tif grid[m][n] == 1:\n \t\t\t\tif m == 0 or grid[m-1][n] == 0: p += 1\n \t\t\t\tif n == 0 or grid[m][n-1] == 0: p += 1\n \t\t\t\tif n == N-1 or grid[m][n+1] == 0: p += 1\n \t\t\t\tif m == M-1 or grid[m+1][n] == 0: p += 1\n \treturn p\n\t\t\n\t\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "island-perimeter", "post_title": "Solution in Python 3", "user": "junaidmansuri", "upvotes": 36, "views": 3200, "problem_title": "island perimeter", "number": 463, "acceptance": 0.695, "difficulty": "Easy", "__index_level_0__": 8271, "question": "You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.\nGrid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).\nThe island doesn't have \"lakes\", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.\n Example 1:\nInput: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\nOutput: 16\nExplanation: The perimeter is the 16 yellow stripes in the image above.\nExample 2:\nInput: grid = [[1]]\nOutput: 4\nExample 3:\nInput: grid = [[1,0]]\nOutput: 4\n Constraints:\nrow == grid.length\ncol == grid[i].length\n1 <= row, col <= 100\ngrid[i][j] is 0 or 1.\nThere is exactly one island in grid." }, { "post_href": "https://leetcode.com/problems/can-i-win/discuss/850051/Python3-top-down-dp", "python_solutions": "class Solution:\n def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:\n if desiredTotal == 0: return True # edge case 1\n if maxChoosableInteger * (maxChoosableInteger+1)//2 < desiredTotal: return False # edge case 2\n \n @lru_cache(None)\n def fn(mask, total): \n \"\"\"Return True if there is a winning strategy given mask & total.\"\"\"\n if total <= 0: return False # already lost \n for i in range(maxChoosableInteger): \n if mask & (1 << i): # integer i+1 is not used yet \n if not fn(mask ^ (1 << i), total - (i + 1)): return True \n return False \n \n return fn(int(\"1\"*maxChoosableInteger, 2), desiredTotal)", "slug": "can-i-win", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 3, "views": 423, "problem_title": "can i win", "number": 464, "acceptance": 0.298, "difficulty": "Medium", "__index_level_0__": 8316, "question": "In the \"100 game\" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.\nWhat if we change the game so that players cannot re-use integers?\nFor example, two players might take turns drawing from a common pool of numbers from 1 to 15 without replacement until they reach a total >= 100.\nGiven two integers maxChoosableInteger and desiredTotal, return true if the first player to move can force a win, otherwise, return false. Assume both players play optimally.\n Example 1:\nInput: maxChoosableInteger = 10, desiredTotal = 11\nOutput: false\nExplanation:\nNo matter which integer the first player choose, the first player will lose.\nThe first player can choose an integer from 1 up to 10.\nIf the first player choose 1, the second player can only choose integers from 2 up to 10.\nThe second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\nSame with other integers chosen by the first player, the second player will always win.\nExample 2:\nInput: maxChoosableInteger = 10, desiredTotal = 0\nOutput: true\nExample 3:\nInput: maxChoosableInteger = 10, desiredTotal = 1\nOutput: true\n Constraints:\n1 <= maxChoosableInteger <= 20\n0 <= desiredTotal <= 300" }, { "post_href": "https://leetcode.com/problems/count-the-repetitions/discuss/2521184/Python3-repeating-patterns", "python_solutions": "class Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n cnt = idx = 0 \n count = []\n index = []\n for i in range(n1): \n for ch in s1: \n if ch == s2[idx]: \n idx += 1\n if idx == len(s2): \n cnt += 1\n idx = 0 \n count.append(cnt)\n index.append(idx)\n for ii in range(i): \n if index[ii] == idx: \n prev = count[ii]\n repeat = (cnt - prev) * ((n1-1-ii) // (i - ii))\n post = count[ii + (n1-1-ii) % (i-ii)] - count[ii]\n return (prev + repeat + post) // n2\n return count[-1]//n2", "slug": "count-the-repetitions", "post_title": "[Python3] repeating patterns", "user": "ye15", "upvotes": 0, "views": 22, "problem_title": "count the repetitions", "number": 466, "acceptance": 0.293, "difficulty": "Hard", "__index_level_0__": 8321, "question": "We define str = [s, n] as the string str which consists of the string s concatenated n times.\nFor example, str == [\"abc\", 3] ==\"abcabcabc\".\nWe define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.\nFor example, s1 = \"abc\" can be obtained from s2 = \"abdbec\" based on our definition by removing the bolded underlined characters.\nYou are given two strings s1 and s2 and two integers n1 and n2. You have the two strings str1 = [s1, n1] and str2 = [s2, n2].\nReturn the maximum integer m such that str = [str2, m] can be obtained from str1.\n Example 1:\nInput: s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2\nOutput: 2\nExample 2:\nInput: s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1\nOutput: 1\n Constraints:\n1 <= s1.length, s2.length <= 100\ns1 and s2 consist of lowercase English letters.\n1 <= n1, n2 <= 106" }, { "post_href": "https://leetcode.com/problems/unique-substrings-in-wraparound-string/discuss/1705570/Python3-DP-O(N)-time-O(1)-space", "python_solutions": "class Solution:\n def findSubstringInWraproundString(self, p: str) -> int:\n consecutive = 1\n \n # stores the maximum length of a substring ending at a character \n maxSubstr = defaultdict(int)\n maxSubstr[p[0]] = 1\n \n ans = 0\n for x in range(1, len(p)):\n if ord(p[x]) - ord(p[x - 1]) == 1 or p[x] == 'a' and p[x - 1] == 'z':\n consecutive += 1\n else:\n consecutive = 1\n maxSubstr[p[x]] = max(maxSubstr[p[x]], consecutive)\n \n return sum(maxSubstr.values())", "slug": "unique-substrings-in-wraparound-string", "post_title": "Python3 DP O(N) time O(1) space", "user": "srihariv", "upvotes": 1, "views": 92, "problem_title": "unique substrings in wraparound string", "number": 467, "acceptance": 0.3829999999999999, "difficulty": "Medium", "__index_level_0__": 8322, "question": "We define the string base to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\", so base will look like this:\n\"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\".\nGiven a string s, return the number of unique non-empty substrings of s are present in base.\n Example 1:\nInput: s = \"a\"\nOutput: 1\nExplanation: Only the substring \"a\" of s is in base.\nExample 2:\nInput: s = \"cac\"\nOutput: 2\nExplanation: There are two substrings (\"a\", \"c\") of s in base.\nExample 3:\nInput: s = \"zab\"\nOutput: 6\nExplanation: There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of s in base.\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/validate-ip-address/discuss/2440773/Python-or-Easiest-solution-Faster-than-99-or-easy-if-and-else", "python_solutions": "class Solution:\n\tdef validIPAddress(self, query: str) -> str:\n\t\tdot = query.count(\".\")\n\t\tcolon = query.count(\":\")\n\t\tif colon == 0 and dot == 3:\n\t\t\tarr = [i for i in query.split(\".\")]\n\t\t\tprint(arr)\n\t\t\tflag = True\n\t\t\tfor i in arr:\n\t\t\t\tif i.isdigit() and int(i) <= 255:\n\t\t\t\t\tx = int(i)\n\t\t\t\t\tif str(x) != i:\n\t\t\t\t\t\tflag = False\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tflag = False\n\t\t\t\t\tbreak\n\t\t\tif flag:\n\t\t\t\treturn \"IPv4\"\n\t\t\telse:\n\t\t\t\treturn \"Neither\"\n\t\telif colon == 7 and dot == 0:\n\t\t\tflag = True\n\t\t\tarr = [i for i in query.split(\":\")]\n\t\t\tfor parts in arr:\n\t\t\t\tl = 0\n\t\t\t\tfor i in parts:\n\t\t\t\t\tl += 1\n\t\t\t\t\tif i not in \"0123456789abcdefABCDEF\":\n\t\t\t\t\t\tflag = False\n\t\t\t\t\t\tbreak\n\t\t\t\tif l > 4 or l < 1:flag = False;break\n\t\t\tif flag:\n\t\t\t\treturn \"IPv6\"\n\t\t\telse:\n\t\t\t\treturn \"Neither\"\n\n\t\telse:\n\t\t\treturn \"Neither\"", "slug": "validate-ip-address", "post_title": "Python | Easiest solution Faster than 99% | easy if and else", "user": "sami2002", "upvotes": 0, "views": 134, "problem_title": "validate ip address", "number": 468, "acceptance": 0.266, "difficulty": "Medium", "__index_level_0__": 8326, "question": "Given a string queryIP, return \"IPv4\" if IP is a valid IPv4 address, \"IPv6\" if IP is a valid IPv6 address or \"Neither\" if IP is not a correct IP of any type.\nA valid IPv4 address is an IP in the form \"x1.x2.x3.x4\" where 0 <= xi <= 255 and xi cannot contain leading zeros. For example, \"192.168.1.1\" and \"192.168.1.0\" are valid IPv4 addresses while \"192.168.01.1\", \"192.168.1.00\", and \"192.168@1.1\" are invalid IPv4 addresses.\nA valid IPv6 address is an IP in the form \"x1:x2:x3:x4:x5:x6:x7:x8\" where:\n1 <= xi.length <= 4\nxi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F').\nLeading zeros are allowed in xi.\nFor example, \"2001:0db8:85a3:0000:0000:8a2e:0370:7334\" and \"2001:db8:85a3:0:0:8A2E:0370:7334\" are valid IPv6 addresses, while \"2001:0db8:85a3::8A2E:037j:7334\" and \"02001:0db8:85a3:0000:0000:8a2e:0370:7334\" are invalid IPv6 addresses.\n Example 1:\nInput: queryIP = \"172.16.254.1\"\nOutput: \"IPv4\"\nExplanation: This is a valid IPv4 address, return \"IPv4\".\nExample 2:\nInput: queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\nOutput: \"IPv6\"\nExplanation: This is a valid IPv6 address, return \"IPv6\".\nExample 3:\nInput: queryIP = \"256.256.256.256\"\nOutput: \"Neither\"\nExplanation: This is neither a IPv4 address nor a IPv6 address.\n Constraints:\nqueryIP consists only of English letters, digits and the characters '.' and ':'." }, { "post_href": "https://leetcode.com/problems/concatenated-words/discuss/2189673/Python3-TRIE-WITH-RECURSION-(-)-Explained", "python_solutions": "class Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n ddic = lambda: defaultdict(ddic)\n trie = ddic()\n \n for word in words:\n cur = trie\n for char in word:\n cur = cur[char]\n\n cur['end'] = True\n \n def isConcat(word, start):\n cur = trie\n for i in range(start, len(word)):\n char = word[i]\n if char not in cur:\n return False\n cur = cur[char]\n\n if 'end' in cur:\n if i + 1 == len(word):\n # tricky part that helps us distinguish simple word from concat word\n return start != 0\n \n if isConcat(word, i + 1):\n return True\n\n return False\n \n return [word for word in words if isConcat(word, 0)]", "slug": "concatenated-words", "post_title": "\u2714\ufe0f [Python3] TRIE WITH RECURSION \u1555( \u141b )\u1557, Explained", "user": "artod", "upvotes": 4, "views": 100, "problem_title": "concatenated words", "number": 472, "acceptance": 0.4579999999999999, "difficulty": "Hard", "__index_level_0__": 8332, "question": "Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.\nA concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necessarily distinct) in the given array.\n Example 1:\nInput: words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\nOutput: [\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\nExplanation: \"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\".\nExample 2:\nInput: words = [\"cat\",\"dog\",\"catdog\"]\nOutput: [\"catdog\"]\n Constraints:\n1 <= words.length <= 104\n1 <= words[i].length <= 30\nwords[i] consists of only lowercase English letters.\nAll the strings of words are unique.\n1 <= sum(words[i].length) <= 105" }, { "post_href": "https://leetcode.com/problems/matchsticks-to-square/discuss/2270373/Python-3DP-%2B-Bitmask", "python_solutions": "class Solution:\n def makesquare(self, arr: List[int]) -> bool:\n\t\t# no way to make the square if total length not divisble by 4\n if sum(arr) % 4:\n return False\n \n\t\t# target side length\n side = sum(arr) // 4\n \n @lru_cache(None)\n def dp(k, mask, s):\n\t\t\t# finish all four sides\n if k == 4:\n return True\n\t\t\t# move on to next side if current one finished\n if not s:\n return dp(k+1, mask, side)\n \n for i in range(len(arr)):\n\t\t\t\t# if current matchstick used or longer than remaining side length to fill then skip\n if mask & (1 << i) or s < arr[i]: continue\n if dp(k, mask ^ (1 << i), s - arr[i]):\n return True\n return False\n \n return dp(0, 0, side)", "slug": "matchsticks-to-square", "post_title": "[Python 3]DP + Bitmask", "user": "chestnut890123", "upvotes": 6, "views": 662, "problem_title": "matchsticks to square", "number": 473, "acceptance": 0.4039999999999999, "difficulty": "Medium", "__index_level_0__": 8344, "question": "You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.\nReturn true if you can make this square and false otherwise.\n Example 1:\nInput: matchsticks = [1,1,2,2,2]\nOutput: true\nExplanation: You can form a square with length 2, one side of the square came two sticks with length 1.\nExample 2:\nInput: matchsticks = [3,3,3,3,4]\nOutput: false\nExplanation: You cannot find a way to form a square with all the matchsticks.\n Constraints:\n1 <= matchsticks.length <= 15\n1 <= matchsticks[i] <= 108" }, { "post_href": "https://leetcode.com/problems/ones-and-zeroes/discuss/2065208/Python-Easy-DP-2-approaches", "python_solutions": "class Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n counter=[[s.count(\"0\"), s.count(\"1\")] for s in strs]\n \n @cache\n def dp(i,j,idx):\n if i<0 or j<0:\n return -math.inf\n \n if idx==len(strs):\n return 0\n \n return max(dp(i,j,idx+1), 1 + dp(i-counter[idx][0], j-counter[idx][1], idx+1))\n return dp(m,n,0)", "slug": "ones-and-zeroes", "post_title": "Python Easy DP 2 approaches", "user": "constantine786", "upvotes": 71, "views": 4300, "problem_title": "ones and zeroes", "number": 474, "acceptance": 0.467, "difficulty": "Medium", "__index_level_0__": 8360, "question": "You are given an array of binary strings strs and two integers m and n.\nReturn the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.\nA set x is a subset of a set y if all elements of x are also elements of y.\n Example 1:\nInput: strs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"], m = 5, n = 3\nOutput: 4\nExplanation: The largest subset with at most 5 0's and 3 1's is {\"10\", \"0001\", \"1\", \"0\"}, so the answer is 4.\nOther valid but smaller subsets include {\"0001\", \"1\"} and {\"10\", \"1\", \"0\"}.\n{\"111001\"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.\nExample 2:\nInput: strs = [\"10\",\"0\",\"1\"], m = 1, n = 1\nOutput: 2\nExplanation: The largest subset is {\"0\", \"1\"}, so the answer is 2.\n Constraints:\n1 <= strs.length <= 600\n1 <= strs[i].length <= 100\nstrs[i] consists only of digits '0' and '1'.\n1 <= m, n <= 100" }, { "post_href": "https://leetcode.com/problems/heaters/discuss/2711430/python-99.84-speed-O(1)-memory", "python_solutions": "class Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n houses.sort()\n heaters.sort()\n\n if len(heaters) == 1:\n return max(abs(houses[0] - heaters[0]), abs(houses[-1] - heaters[0]))\n\n m_value = -1\n f, s, ind_heat = heaters[0], heaters[1], 2\n for i in range(len(houses)):\n while houses[i] > s and ind_heat < len(heaters):\n f, s = s, heaters[ind_heat]\n ind_heat += 1\n m_value = max(m_value, min(abs(houses[i] - f), abs(houses[i] - s)))\n return m_value", "slug": "heaters", "post_title": "python 99.84% speed O(1) memory", "user": "Yaro1", "upvotes": 2, "views": 234, "problem_title": "heaters", "number": 475, "acceptance": 0.361, "difficulty": "Medium", "__index_level_0__": 8383, "question": "Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.\nEvery house can be warmed, as long as the house is within the heater's warm radius range. \nGiven the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.\nNotice that all the heaters follow your radius standard, and the warm radius will the same.\n Example 1:\nInput: houses = [1,2,3], heaters = [2]\nOutput: 1\nExplanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.\nExample 2:\nInput: houses = [1,2,3,4], heaters = [1,4]\nOutput: 1\nExplanation: The two heaters were placed at positions 1 and 4. We need to use a radius 1 standard, then all the houses can be warmed.\nExample 3:\nInput: houses = [1,5], heaters = [2]\nOutput: 3\n Constraints:\n1 <= houses.length, heaters.length <= 3 * 104\n1 <= houses[i], heaters[i] <= 109" }, { "post_href": "https://leetcode.com/problems/number-complement/discuss/488055/Python-O(-lg-n-)-sol.-by-XOR-masking.-85%2B-With-explanation", "python_solutions": "class Solution:\n def findComplement(self, num: int) -> int:\n \n bit_mask = 2**num.bit_length() -1 \n \n return ( num ^ bit_mask )", "slug": "number-complement", "post_title": "Python O( lg n ) sol. by XOR masking. 85%+ [ With explanation ]", "user": "brianchiang_tw", "upvotes": 17, "views": 1100, "problem_title": "number complement", "number": 476, "acceptance": 0.672, "difficulty": "Easy", "__index_level_0__": 8398, "question": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.\nFor example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\nGiven an integer num, return its complement.\n Example 1:\nInput: num = 5\nOutput: 2\nExplanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.\nExample 2:\nInput: num = 1\nOutput: 0\nExplanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.\n Constraints:\n1 <= num < 231\n Note: This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/" }, { "post_href": "https://leetcode.com/problems/total-hamming-distance/discuss/851194/Python-3-or-Bit-Manipulation-O(N)-or-Explanations", "python_solutions": "class Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n ans = 0\n for i in range(32):\n zero = one = 0\n mask = 1 << i\n for num in nums:\n if mask & num: one += 1\n else: zero += 1 \n ans += one * zero \n return ans", "slug": "total-hamming-distance", "post_title": "Python 3 | Bit Manipulation O(N) | Explanations", "user": "idontknoooo", "upvotes": 26, "views": 1300, "problem_title": "total hamming distance", "number": 477, "acceptance": 0.522, "difficulty": "Medium", "__index_level_0__": 8437, "question": "The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\nGiven an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.\n Example 1:\nInput: nums = [4,14,2]\nOutput: 6\nExplanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\nshowing the four bits relevant in this case).\nThe answer will be:\nHammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\nExample 2:\nInput: nums = [4,14,4]\nOutput: 4\n Constraints:\n1 <= nums.length <= 104\n0 <= nums[i] <= 109\nThe answer for the given input will fit in a 32-bit integer." }, { "post_href": "https://leetcode.com/problems/generate-random-point-in-a-circle/discuss/1113715/Python-wrong-test-cases", "python_solutions": "class Solution:\n\n def __init__(self, radius: float, x_center: float, y_center: float):\n self.x = x_center\n self.y = y_center\n self.radius = radius\n\n def randPoint(self) -> List[float]:\n first = random.uniform(-self.radius, self.radius)\n secondmax = (self.radius ** 2 - first ** 2) ** 0.5\n second = random.uniform(-secondmax, secondmax)\n return [self.x + first, self.y + second]", "slug": "generate-random-point-in-a-circle", "post_title": "Python, wrong test cases?", "user": "warmr0bot", "upvotes": 4, "views": 322, "problem_title": "generate random point in a circle", "number": 478, "acceptance": 0.396, "difficulty": "Medium", "__index_level_0__": 8444, "question": "Given the radius and the position of the center of a circle, implement the function randPoint which generates a uniform random point inside the circle.\nImplement the Solution class:\nSolution(double radius, double x_center, double y_center) initializes the object with the radius of the circle radius and the position of the center (x_center, y_center).\nrandPoint() returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array [x, y].\n Example 1:\nInput\n[\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n[[1.0, 0.0, 0.0], [], [], []]\nOutput\n[null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n\nExplanation\nSolution solution = new Solution(1.0, 0.0, 0.0);\nsolution.randPoint(); // return [-0.02493, -0.38077]\nsolution.randPoint(); // return [0.82314, 0.38945]\nsolution.randPoint(); // return [0.36572, 0.17248]\n Constraints:\n0 < radius <= 108\n-107 <= x_center, y_center <= 107\nAt most 3 * 104 calls will be made to randPoint." }, { "post_href": "https://leetcode.com/problems/largest-palindrome-product/discuss/1521512/Python3-Solution-with-explanation", "python_solutions": "class Solution:\n def largestPalindrome(self, n: int) -> int:\n \n # just to forget about 1-digit case\n if n == 1:\n return 9\n \n # minimal number with n digits (for ex. for n = 4, min_num = 1000)\n min_num = 10 ** (n - 1)\n \n # maximal number with n digits (for ex. 9999)\n max_num = 10 ** n - 1 \n \n max_pal = 0\n \n # step is equal to 2, because we have to get a number, the 1st digit of which is 9, so we have to \n\t\t# iterate only over odd numbers\n for i in range(max_num, min_num - 1, -2): \n \n # since we are looking for the maximum palindrome number, it makes no sense to iterate over the \n # product less than the max_pal obtained from the last iteration\n if i * i < max_pal:\n break\n \n for j in range(max_num, i - 1, -2):\n product = i * j\n \n # since a palindrome with an even number of digits must be mod 11 == 0 and we have no reason to \n # check the product which less or equal than max_pal\n if product % 11 != 0 and product >= max_pal:\n continue\n \n # check if product is a palindrome then update the max_pal\n if str(product) == str(product)[::-1]:\n max_pal = product\n\n return max_pal % 1337", "slug": "largest-palindrome-product", "post_title": "Python3 Solution with explanation", "user": "frolovdmn", "upvotes": 8, "views": 741, "problem_title": "largest palindrome product", "number": 479, "acceptance": 0.317, "difficulty": "Hard", "__index_level_0__": 8450, "question": "Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.\n Example 1:\nInput: n = 2\nOutput: 987\nExplanation: 99 x 91 = 9009, 9009 % 1337 = 987\nExample 2:\nInput: n = 1\nOutput: 9\n Constraints:\n1 <= n <= 8" }, { "post_href": "https://leetcode.com/problems/sliding-window-median/discuss/1942580/Easiest-Python-O(n-log-k)-Two-Heaps-(Lazy-Removal)-96.23", "python_solutions": "class Solution:\n # TC - O((n - k)*log(k))\n # SC - O(k)\n\t# 121 ms, faster than 96.23%\n\n def find_median(self, max_heap, min_heap, heap_size):\n if heap_size % 2 == 1:\n return -max_heap[0]\n else:\n return (-max_heap[0] + min_heap[0]) / 2\n\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n max_heap = []\n min_heap = []\n heap_dict = defaultdict(int)\n result = []\n \n for i in range(k):\n heappush(max_heap, -nums[i])\n heappush(min_heap, -heappop(max_heap))\n if len(min_heap) > len(max_heap):\n heappush(max_heap, -heappop(min_heap))\n \n median = self.find_median(max_heap, min_heap, k)\n result.append(median)\n \n for i in range(k, len(nums)):\n prev_num = nums[i - k]\n heap_dict[prev_num] += 1\n\n balance = -1 if prev_num <= median else 1\n \n if nums[i] <= median:\n balance += 1\n heappush(max_heap, -nums[i])\n else:\n balance -= 1\n heappush(min_heap, nums[i])\n \n if balance < 0:\n heappush(max_heap, -heappop(min_heap))\n elif balance > 0:\n heappush(min_heap, -heappop(max_heap))\n\n while max_heap and heap_dict[-max_heap[0]] > 0:\n heap_dict[-max_heap[0]] -= 1\n heappop(max_heap)\n \n while min_heap and heap_dict[min_heap[0]] > 0:\n heap_dict[min_heap[0]] -= 1\n heappop(min_heap)\n\n median = self.find_median(max_heap, min_heap, k)\n result.append(median)\n \n return result", "slug": "sliding-window-median", "post_title": "\u2705 Easiest Python O(n log k) Two Heaps (Lazy Removal), 96.23%", "user": "AntonBelski", "upvotes": 4, "views": 480, "problem_title": "sliding window median", "number": 480, "acceptance": 0.414, "difficulty": "Hard", "__index_level_0__": 8453, "question": "The 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 values.\nFor examples, if arr = [2,3,4], the median is 3.\nFor examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.\nYou are given an integer array nums and an integer k. 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.\nReturn the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.\n Example 1:\nInput: nums = [1,3,-1,-3,5,3,6,7], k = 3\nOutput: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\nExplanation: \nWindow 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\nExample 2:\nInput: nums = [1,2,3,4,2,3,1,4,2], k = 3\nOutput: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]\n Constraints:\n1 <= k <= nums.length <= 105\n-231 <= nums[i] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/magical-string/discuss/2558509/481.-Magical-String", "python_solutions": "class Solution:\n def magicalString(self, n: int) -> int:\n arr, i = [1,2,2], 2\n \n while len(arr) < n:\n arr.extend([arr[-1]^3]*arr[i])\n i += 1\n \n return arr[:n].count(1)", "slug": "magical-string", "post_title": "481. Magical String", "user": "warrenruud", "upvotes": 3, "views": 417, "problem_title": "magical string", "number": 481, "acceptance": 0.505, "difficulty": "Medium", "__index_level_0__": 8460, "question": "A magical string s consists of only '1' and '2' and obeys the following rules:\nThe string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.\nThe first few elements of s is s = \"1221121221221121122\u2026\u2026\". If we group the consecutive 1's and 2's in s, it will be \"1 22 11 2 1 22 1 22 11 2 11 22 ......\" and the occurrences of 1's or 2's in each group are \"1 2 2 1 1 2 1 2 2 1 2 2 ......\". You can see that the occurrence sequence is s itself.\nGiven an integer n, return the number of 1's in the first n number in the magical string s.\n Example 1:\nInput: n = 6\nOutput: 3\nExplanation: The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.\nExample 2:\nInput: n = 1\nOutput: 1\n Constraints:\n1 <= n <= 105" }, { "post_href": "https://leetcode.com/problems/license-key-formatting/discuss/540266/PythonJSC%2B%2B-O(n)-by-string-operation.-w-Explanation", "python_solutions": "class Solution:\n def licenseKeyFormatting(self, S: str, K: int) -> str:\n \n # Eliminate all dashes\n S = S.replace('-', '')\n \n head = len(S) % K\n \n grouping = []\n \n # Special handle for first group\n if head:\n grouping.append( S[:head] )\n \n # General case:\n for index in range(head, len(S), K ):\n grouping.append( S[ index : index+K ] )\n \n \n # Link each group togetger and separated by dash '-'\n return '-'.join( grouping ).upper()", "slug": "license-key-formatting", "post_title": "Python/JS/C++ O(n) by string operation. [w/ Explanation]", "user": "brianchiang_tw", "upvotes": 35, "views": 1700, "problem_title": "license key formatting", "number": 482, "acceptance": 0.432, "difficulty": "Easy", "__index_level_0__": 8466, "question": "You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k.\nWe want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase.\nReturn the reformatted license key.\n Example 1:\nInput: s = \"5F3Z-2e-9-w\", k = 4\nOutput: \"5F3Z-2E9W\"\nExplanation: The string s has been split into two parts, each part has 4 characters.\nNote that the two extra dashes are not needed and can be removed.\nExample 2:\nInput: s = \"2-5g-3-J\", k = 2\nOutput: \"2-5G-3J\"\nExplanation: The string s has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.\n Constraints:\n1 <= s.length <= 105\ns consists of English letters, digits, and dashes '-'.\n1 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/smallest-good-base/discuss/2368982/faster-than-97.27-or-python", "python_solutions": "class Solution:\n def smallestGoodBase(self, n: str) -> str:\n import math\n n = int(n)\n max_m = math.floor(math.log(n, 2))\n ans = 0\n for m in range(max_m, 0, -1):\n k = int(n ** (1 / m))\n if (k ** (m + 1) - 1) // (k - 1) == n:\n return str(k)\n return str(n - 1)", "slug": "smallest-good-base", "post_title": "faster than 97.27% | python", "user": "vimla_kushwaha", "upvotes": 1, "views": 107, "problem_title": "smallest good base", "number": 483, "acceptance": 0.384, "difficulty": "Hard", "__index_level_0__": 8493, "question": "Given an integer n represented as a string, return the smallest good base of n.\nWe call k >= 2 a good base of n, if all digits of n base k are 1's.\n Example 1:\nInput: n = \"13\"\nOutput: \"3\"\nExplanation: 13 base 3 is 111.\nExample 2:\nInput: n = \"4681\"\nOutput: \"8\"\nExplanation: 4681 base 8 is 11111.\nExample 3:\nInput: n = \"1000000000000000000\"\nOutput: \"999999999999999999\"\nExplanation: 1000000000000000000 base 999999999999999999 is 11.\n Constraints:\nn is an integer in the range [3, 1018].\nn does not contain any leading zeros." }, { "post_href": "https://leetcode.com/problems/max-consecutive-ones/discuss/1011637/Simple-and-easy-if-else-solution-faster-than-99.91", "python_solutions": "class Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n c1,c2=0,0\n for i in nums:\n if i==1:\n c1+=1\n elif i==0:\n c1=0\n if c1>c2:\n c2=c1\n return c2", "slug": "max-consecutive-ones", "post_title": "Simple and easy if-else solution, faster than 99.91%", "user": "thisisakshat", "upvotes": 8, "views": 688, "problem_title": "max consecutive ones", "number": 485, "acceptance": 0.561, "difficulty": "Easy", "__index_level_0__": 8495, "question": "Given a binary array nums, return the maximum number of consecutive 1's in the array.\n Example 1:\nInput: nums = [1,1,0,1,1,1]\nOutput: 3\nExplanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.\nExample 2:\nInput: nums = [1,0,1,1,0,1]\nOutput: 2\n Constraints:\n1 <= nums.length <= 105\nnums[i] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/predict-the-winner/discuss/414803/Python-AC-98-Both-Recursion-and-DP-with-detailed-explanation.", "python_solutions": "class Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n def helper(i, j):\n if i == j:\n return nums[i]\n \n if (i, j) in memo:\n return memo[(i, j)]\n \n score = max(nums[j] - helper(i, j-1), nums[i] - helper(i+1, j))\n memo[(i, j)] = score\n \n return score\n \n memo = {} \n return helper(0, len(nums)-1) >= 0", "slug": "predict-the-winner", "post_title": "Python [AC 98%] Both Recursion & DP with detailed explanation.", "user": "bos", "upvotes": 19, "views": 1300, "problem_title": "predict the winner", "number": 486, "acceptance": 0.509, "difficulty": "Medium", "__index_level_0__": 8546, "question": "You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.\nPlayer 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.\nReturn true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.\n Example 1:\nInput: nums = [1,5,2]\nOutput: false\nExplanation: Initially, player 1 can choose between 1 and 2. \nIf he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). \nSo, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \nHence, player 1 will never be the winner and you need to return false.\nExample 2:\nInput: nums = [1,5,233,7]\nOutput: true\nExplanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.\nFinally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.\n Constraints:\n1 <= nums.length <= 20\n0 <= nums[i] <= 107" }, { "post_href": "https://leetcode.com/problems/zuma-game/discuss/1568450/Python-Easy-BFS-solution-with-explain", "python_solutions": "class Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n \n # start from i and remove continues ball\n def remove_same(s, i):\n if i < 0:\n return s\n \n left = right = i\n while left > 0 and s[left-1] == s[i]:\n left -= 1\n while right+1 < len(s) and s[right+1] == s[i]:\n right += 1\n \n length = right - left + 1\n if length >= 3:\n new_s = s[:left] + s[right+1:]\n return remove_same(new_s, left-1)\n else:\n return s\n\n\n\n hand = \"\".join(sorted(hand))\n\n # board, hand and step\n q = collections.deque([(board, hand, 0)])\n visited = set([(board, hand)])\n\n while q:\n curr_board, curr_hand, step = q.popleft()\n for i in range(len(curr_board)+1):\n for j in range(len(curr_hand)):\n # skip the continue balls in hand\n if j > 0 and curr_hand[j] == curr_hand[j-1]:\n continue\n \n # only insert at the begin of continue balls in board\n if i > 0 and curr_board[i-1] == curr_hand[j]: # left side same color\n continue\n \n pick = False\n # 1. same color with right\n # 2. left and right are same but pick is different\n if i < len(curr_board) and curr_board[i] == curr_hand[j]:\n pick = True\n if 0 WBBW.\n- Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\nThere are still balls remaining on the board, and you are out of balls to insert.\nExample 2:\nInput: board = \"WWRRBBWW\", hand = \"WRBRW\"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'R' so the board becomes WWRRRBBWW. WWRRRBBWW -> WWBBWW.\n- Insert 'B' so the board becomes WWBBBWW. WWBBBWW -> WWWW -> empty.\n2 balls from your hand were needed to clear the board.\nExample 3:\nInput: board = \"G\", hand = \"GGGGG\"\nOutput: 2\nExplanation: To make the board empty:\n- Insert 'G' so the board becomes GG.\n- Insert 'G' so the board becomes GGG. GGG -> empty.\n2 balls from your hand were needed to clear the board.\n Constraints:\n1 <= board.length <= 16\n1 <= hand.length <= 5\nboard and hand consist of the characters 'R', 'Y', 'B', 'G', and 'W'.\nThe initial row of balls on the board will not have any groups of three or more consecutive balls of the same color." }, { "post_href": "https://leetcode.com/problems/increasing-subsequences/discuss/1577928/Python-DFS", "python_solutions": "class Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n def dfs(i, num, curr):\n if len(curr)>=2:\n ans.add(curr[:])\n if i>=len(nums):\n return\n for j in range(i, len(nums)):\n if nums[j]>=num:\n dfs(j+1, nums[j], curr+(nums[j],))\n \n ans = set()\n dfs(0, -float(\"inf\"), ())\n return ans", "slug": "increasing-subsequences", "post_title": "Python DFS", "user": "hX_", "upvotes": 3, "views": 293, "problem_title": "increasing subsequences", "number": 491, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 8566, "question": "Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.\n Example 1:\nInput: nums = [4,6,7,7]\nOutput: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\nExample 2:\nInput: nums = [4,4,3,2,1]\nOutput: [[4,4]]\n Constraints:\n1 <= nums.length <= 15\n-100 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/construct-the-rectangle/discuss/1990625/Python-Easy-Solution-or-Faster-Than-92-Submits", "python_solutions": "class Solution:\n def constructRectangle(self, area: int) -> List[int]:\n \n for i in range(int(area**0.5),0,-1):\n if area % i == 0: return [area//i,i]", "slug": "construct-the-rectangle", "post_title": "[ Python ] Easy Solution | Faster Than 92% Submits", "user": "crazypuppy", "upvotes": 3, "views": 300, "problem_title": "construct the rectangle", "number": 492, "acceptance": 0.5379999999999999, "difficulty": "Easy", "__index_level_0__": 8583, "question": "A web developer needs to know how to design a web page's size. So, given a specific rectangular web page\u2019s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:\nThe area of the rectangular web page you designed must equal to the given target area.\nThe width W should not be larger than the length L, which means L >= W.\nThe difference between length L and width W should be as small as possible.\nReturn an array [L, W] where L and W are the length and width of the web page you designed in sequence.\n Example 1:\nInput: area = 4\nOutput: [2,2]\nExplanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \nBut according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.\nExample 2:\nInput: area = 37\nOutput: [37,1]\nExample 3:\nInput: area = 122122\nOutput: [427,286]\n Constraints:\n1 <= area <= 107" }, { "post_href": "https://leetcode.com/problems/reverse-pairs/discuss/1205560/Python3-summarizing-4-solutions", "python_solutions": "class Solution:\n def reversePairs(self, nums: List[int]) -> int:\n ans = 0\n seen = []\n for x in nums: \n k = bisect_right(seen, 2*x)\n ans += len(seen) - k\n insort(seen, x)\n return ans", "slug": "reverse-pairs", "post_title": "[Python3] summarizing 4 solutions", "user": "ye15", "upvotes": 5, "views": 223, "problem_title": "reverse pairs", "number": 493, "acceptance": 0.309, "difficulty": "Hard", "__index_level_0__": 8600, "question": "Given an integer array nums, return the number of reverse pairs in the array.\nA reverse pair is a pair (i, j) where:\n0 <= i < j < nums.length and\nnums[i] > 2 * nums[j].\n Example 1:\nInput: nums = [1,3,2,3,1]\nOutput: 2\nExplanation: The reverse pairs are:\n(1, 4) --> nums[1] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 3, nums[4] = 1, 3 > 2 * 1\nExample 2:\nInput: nums = [2,4,3,5,1]\nOutput: 3\nExplanation: The reverse pairs are:\n(1, 4) --> nums[1] = 4, nums[4] = 1, 4 > 2 * 1\n(2, 4) --> nums[2] = 3, nums[4] = 1, 3 > 2 * 1\n(3, 4) --> nums[3] = 5, nums[4] = 1, 5 > 2 * 1\n Constraints:\n1 <= nums.length <= 5 * 104\n-231 <= nums[i] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/target-sum/discuss/1198338/Python-recursive-solution-with-memoization-(DFS)", "python_solutions": "class Solution: \n def findTargetSumWays(self, nums: List[int], target: int) -> int: \n dic = defaultdict(int)\n \n def dfs(index=0, total=0): \n key = (index, total)\n \n if key not in dic:\n if index == len(nums): \n return 1 if total == target else 0\n else:\n dic[key] = dfs(index+1, total + nums[index]) + dfs(index+1, total - nums[index]) \n \n return dic[key] \n \n return dfs()", "slug": "target-sum", "post_title": "Python, recursive solution with memoization (DFS)", "user": "swissified", "upvotes": 22, "views": 1500, "problem_title": "target sum", "number": 494, "acceptance": 0.456, "difficulty": "Medium", "__index_level_0__": 8608, "question": "You are given an integer array nums and an integer target.\nYou want to build an expression out of nums by adding one of the symbols '+' and '-' before each integer in nums and then concatenate all the integers.\nFor example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression \"+2-1\".\nReturn the number of different expressions that you can build, which evaluates to target.\n Example 1:\nInput: nums = [1,1,1,1,1], target = 3\nOutput: 5\nExplanation: There are 5 ways to assign symbols to make the sum of nums be target 3.\n-1 + 1 + 1 + 1 + 1 = 3\n+1 - 1 + 1 + 1 + 1 = 3\n+1 + 1 - 1 + 1 + 1 = 3\n+1 + 1 + 1 - 1 + 1 = 3\n+1 + 1 + 1 + 1 - 1 = 3\nExample 2:\nInput: nums = [1], target = 1\nOutput: 1\n Constraints:\n1 <= nums.length <= 20\n0 <= nums[i] <= 1000\n0 <= sum(nums[i]) <= 1000\n-1000 <= target <= 1000" }, { "post_href": "https://leetcode.com/problems/teemo-attacking/discuss/1602614/Python-6-lines-O(n)-concise-solution", "python_solutions": "class Solution(object):\n def findPoisonedDuration(self, timeSeries, duration):\n repeat = 0\n for i in range(len(timeSeries)-1):\n diff = timeSeries[i+1] - timeSeries[i]\n if diff < duration:\n repeat += duration - diff\n return len(timeSeries)*duration - repeat", "slug": "teemo-attacking", "post_title": "Python 6 lines O(n) concise solution", "user": "caitlinttl", "upvotes": 8, "views": 330, "problem_title": "teemo attacking", "number": 495, "acceptance": 0.57, "difficulty": "Easy", "__index_level_0__": 8652, "question": "Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.\nYou are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.\nReturn the total number of seconds that Ashe is poisoned.\n Example 1:\nInput: timeSeries = [1,4], duration = 2\nOutput: 4\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.\nAshe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.\nExample 2:\nInput: timeSeries = [1,2], duration = 2\nOutput: 3\nExplanation: Teemo's attacks on Ashe go as follows:\n- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.\n- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.\nAshe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.\n Constraints:\n1 <= timeSeries.length <= 104\n0 <= timeSeries[i], duration <= 107\ntimeSeries is sorted in non-decreasing order." }, { "post_href": "https://leetcode.com/problems/next-greater-element-i/discuss/640416/Python-sol-by-monotonic-stack-and-dict-w-Comment", "python_solutions": "class Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \n \n # a stack with monotonic decreasing\n monotonic_stack = []\n \n # dictionary:\n # key: number\n # value: next greater number of key\n dict_of_greater_number = {}\n\n # ----------------------------------------------\n \n # launch linear scan to build dict_of_greater_number\n for cur_number in nums2:\n \n # maintain a monotonic decreasing stack\n while monotonic_stack and cur_number > monotonic_stack[-1]:\n \n pop_out_number = monotonic_stack.pop()\n \n # next greater number of pop_out_number is cur_number\n dict_of_greater_number[pop_out_number] = cur_number\n \n monotonic_stack.append(cur_number)\n # ----------------------------------------------\n \n # solution output\n next_greater_element = []\n \n # get next greater element by dictionary\n for x in nums1:\n \n if x in dict_of_greater_number:\n next_greater_element.append( dict_of_greater_number[x] )\n \n else:\n next_greater_element.append(-1)\n \n return next_greater_element", "slug": "next-greater-element-i", "post_title": "Python sol by monotonic stack and dict [w/ Comment ]", "user": "brianchiang_tw", "upvotes": 14, "views": 968, "problem_title": "next greater element i", "number": 496, "acceptance": 0.7140000000000001, "difficulty": "Easy", "__index_level_0__": 8673, "question": "The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.\nYou are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.\nFor each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.\nReturn an array ans of length nums1.length such that ans[i] is the next greater element as described above.\n Example 1:\nInput: nums1 = [4,1,2], nums2 = [1,3,4,2]\nOutput: [-1,3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\n- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.\n- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.\nExample 2:\nInput: nums1 = [2,4], nums2 = [1,2,3,4]\nOutput: [3,-1]\nExplanation: The next greater element for each value of nums1 is as follows:\n- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.\n- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.\n Constraints:\n1 <= nums1.length <= nums2.length <= 1000\n0 <= nums1[i], nums2[i] <= 104\nAll integers in nums1 and nums2 are unique.\nAll the integers of nums1 also appear in nums2.\n Follow up: Could you find an O(nums1.length + nums2.length) solution?" }, { "post_href": "https://leetcode.com/problems/random-point-in-non-overlapping-rectangles/discuss/1453111/Python-Binary-Search", "python_solutions": "class Solution:\n def __init__(self, rects: List[List[int]]):\n self.rects = rects\n self.search_space = []\n\n for i, rect in enumerate(rects):\n a, b, c, d = rect\n self.search_space.append((d - b + 1) * (c - a + 1))\n if i != 0:\n self.search_space[i] += self.search_space[i - 1]\n \n\n def pick(self) -> List[int]:\n randval = random.randint(0, self.search_space[-1] - 1)\n\n low = 0\n high = len(self.search_space) - 1\n\n while low < high:\n midpt = low + (high - low) // 2\n\n if self.search_space[midpt] <= randval:\n low = midpt + 1\n else:\n high = midpt\n\n\n rect = self.rects[low]\n rect_range = randval\n\n if low > 0:\n rect_range -= self.search_space[low - 1] \n\n\n a, b, c, d = rect\n\n return [(rect_range % (c - a + 1)) + a, (rect_range // (c - a + 1)) + b]", "slug": "random-point-in-non-overlapping-rectangles", "post_title": "Python Binary Search", "user": "ypatel38", "upvotes": 1, "views": 155, "problem_title": "random point in non overlapping rectangles", "number": 497, "acceptance": 0.3929999999999999, "difficulty": "Medium", "__index_level_0__": 8722, "question": "You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.\nAny integer point inside the space covered by one of the given rectangles should be equally likely to be returned.\nNote that an integer point is a point that has integer coordinates.\nImplement the Solution class:\nSolution(int[][] rects) Initializes the object with the given rectangles rects.\nint[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.\n Example 1:\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\nOutput\n[null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n\nExplanation\nSolution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\nsolution.pick(); // return [1, -2]\nsolution.pick(); // return [1, -1]\nsolution.pick(); // return [-1, -2]\nsolution.pick(); // return [-2, -2]\nsolution.pick(); // return [0, 0]\n Constraints:\n1 <= rects.length <= 100\nrects[i].length == 4\n-109 <= ai < xi <= 109\n-109 <= bi < yi <= 109\nxi - ai <= 2000\nyi - bi <= 2000\nAll the rectangles do not overlap.\nAt most 104 calls will be made to pick." }, { "post_href": "https://leetcode.com/problems/diagonal-traverse/discuss/272114/Simple-Python-Solution-(with-comments)", "python_solutions": "class Solution:\n def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:\n res = []\n if not matrix:\n return res\n\n # group values in matrix by the sum of their indices in a map\n map = {}\n for i in range(len(matrix) + len(matrix[0]) - 1):\n map[i] = []\n\n # populate the map\n for i, row in enumerate(matrix):\n for j, val in enumerate(row):\n map[i + j].append(val)\n\n # iterate through map and reverse values where key is divisible by two\n for k, v in map.items():\n if k % 2 == 0:\n map[k] = v[::-1]\n \n # populate output\n for v in map.values():\n for val in v:\n res.append(val)\n \n return res", "slug": "diagonal-traverse", "post_title": "Simple Python Solution (with comments)", "user": "AnthonyChao", "upvotes": 5, "views": 612, "problem_title": "diagonal traverse", "number": 498, "acceptance": 0.581, "difficulty": "Medium", "__index_level_0__": 8726, "question": "Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.\n Example 1:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,2,4,7,5,3,6,8,9]\nExample 2:\nInput: mat = [[1,2],[3,4]]\nOutput: [1,2,3,4]\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 104\n1 <= m * n <= 104\n-105 <= mat[i][j] <= 105" }, { "post_href": "https://leetcode.com/problems/keyboard-row/discuss/1525751/Easy-Python-Solution-or-Faster-than-97-(24-ms)", "python_solutions": "class Solution:\n def findWords(self, wds: List[str]) -> List[str]:\n st = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2, 'z': 3, 'x': 3, 'c': 3, 'v': 3, 'b': 3, 'n': 3, 'm': 3}\n\n ret = []\n\n for wd in wds:\n val = 0\n for i in range(len(wd)):\n if i == 0:\n val = st.get(wd[i].lower())\n else:\n if val != st.get(wd[i].lower()):\n val = -1\n break\n if val != -1:\n ret.append(wd)\n return ret", "slug": "keyboard-row", "post_title": "Easy Python Solution | Faster than 97% (24 ms)", "user": "the_sky_high", "upvotes": 5, "views": 462, "problem_title": "keyboard row", "number": 500, "acceptance": 0.6920000000000001, "difficulty": "Easy", "__index_level_0__": 8764, "question": "Given an array of strings words, return the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below.\nIn the American keyboard:\nthe first row consists of the characters \"qwertyuiop\",\nthe second row consists of the characters \"asdfghjkl\", and\nthe third row consists of the characters \"zxcvbnm\".\n Example 1:\nInput: words = [\"Hello\",\"Alaska\",\"Dad\",\"Peace\"]\nOutput: [\"Alaska\",\"Dad\"]\nExample 2:\nInput: words = [\"omk\"]\nOutput: []\nExample 3:\nInput: words = [\"adsdf\",\"sfd\"]\nOutput: [\"adsdf\",\"sfd\"]\n Constraints:\n1 <= words.length <= 20\n1 <= words[i].length <= 100\nwords[i] consists of English letters (both lowercase and uppercase). " }, { "post_href": "https://leetcode.com/problems/find-mode-in-binary-search-tree/discuss/1722526/Python3-Inorder-traversal-beats-99", "python_solutions": "class Solution:\n def findMode(self, root: Optional[TreeNode]) -> List[int]:\n \n def traverse(root: TreeNode) -> None:\n \n if not root:\n return\n \n nonlocal maxcount, count, prevval, modes\n \n traverse(root.left)\n \n if root.val == prevval:\n count += 1\n else: \n count = 1\n \n if count > maxcount:\n maxcount = count\n modes = [root.val]\n elif count == maxcount:\n modes.append(root.val)\n \n prevval = root.val\n traverse(root.right)\n \n \n modes = []\n maxcount = 0\n count = 0\n prevval = root.val\n traverse(root)\n \n return modes", "slug": "find-mode-in-binary-search-tree", "post_title": "[Python3] Inorder traversal; beats 99%", "user": "cwkirby", "upvotes": 2, "views": 90, "problem_title": "find mode in binary search tree", "number": 501, "acceptance": 0.487, "difficulty": "Easy", "__index_level_0__": 8812, "question": "Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.\nIf the tree has more than one mode, return them in any order.\nAssume a BST is defined as follows:\nThe left subtree of a node contains only nodes with keys less than or equal to the node's key.\nThe right subtree of a node contains only nodes with keys greater than or equal to the node's key.\nBoth the left and right subtrees must also be binary search trees.\n Example 1:\nInput: root = [1,null,2,2]\nOutput: [2]\nExample 2:\nInput: root = [0]\nOutput: [0]\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-105 <= Node.val <= 105\n Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count)." }, { "post_href": "https://leetcode.com/problems/ipo/discuss/1492025/Python3-greedy", "python_solutions": "class Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n capital, profits = zip(*sorted(zip(capital, profits)))\n i = 0 \n pq = []\n for _ in range(k): \n while i < len(capital) and capital[i] <= w: \n heappush(pq, -profits[i])\n i += 1\n if pq: w -= heappop(pq)\n return w", "slug": "ipo", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 1, "views": 144, "problem_title": "ipo", "number": 502, "acceptance": 0.45, "difficulty": "Hard", "__index_level_0__": 8832, "question": "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.\nYou are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.\nInitially, 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.\nPick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.\nThe answer is guaranteed to fit in a 32-bit signed integer.\n Example 1:\nInput: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\nOutput: 4\nExplanation: Since your initial capital is 0, you can only start the project indexed 0.\nAfter finishing it you will obtain profit 1 and your capital becomes 1.\nWith capital 1, you can either start the project indexed 1 or the project indexed 2.\nSince you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\nTherefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\nExample 2:\nInput: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\nOutput: 6\n Constraints:\n1 <= k <= 105\n0 <= w <= 109\nn == profits.length\nn == capital.length\n1 <= n <= 105\n0 <= profits[i] <= 104\n0 <= capital[i] <= 109" }, { "post_href": "https://leetcode.com/problems/next-greater-element-ii/discuss/2520585/Python-Stack-98.78-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack", "python_solutions": "class Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n stack, res = [], [-1] * len(nums) # taking an empty stack for storing index, a list with the lenght same as of nums so that we wont add unnecessary elements.\n # [-1] * len(nums) = this will produce a list with len of nums and all elems will be -1.\n for i in list(range(len(nums))) * 2: # see explanation below.\n while stack and (nums[stack[-1]] < nums[i]): # stack is not empty and nums previous elem is less then current, i.e 1<2. \n res[stack.pop()] = nums[i] # then we`ll pop the index in stack and in the res on the same index will add the current num. \n stack.append(i) # if stack is empty then we`ll add the index of num in it for comparision to the next element in the provided list. \n return res # returing the next greater number for every element in nums.", "slug": "next-greater-element-ii", "post_title": "Python Stack 98.78% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack", "user": "rlakshay14", "upvotes": 3, "views": 279, "problem_title": "next greater element ii", "number": 503, "acceptance": 0.631, "difficulty": "Medium", "__index_level_0__": 8836, "question": "Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.\nThe next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return -1 for this number.\n Example 1:\nInput: nums = [1,2,1]\nOutput: [2,-1,2]\nExplanation: The first 1's next greater number is 2; \nThe number 2 can't find next greater number. \nThe second 1's next greater number needs to search circularly, which is also 2.\nExample 2:\nInput: nums = [1,2,3,4,3]\nOutput: [2,3,4,-1,4]\n Constraints:\n1 <= nums.length <= 104\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/base-7/discuss/1014922/Simple-and-easy-faster-than-99.31", "python_solutions": "class Solution:\n def convertToBase7(self, num: int) -> str:\n if not num:\n return \"0\"\n l=[]\n x=num\n if num<0:\n num=-num\n while num>0:\n r=num%7\n l.append(str(r))\n num//=7\n return \"\".join(l[::-1]) if x>=0 else \"-\"+ \"\".join(l[::-1])", "slug": "base-7", "post_title": "Simple and easy - faster than 99.31%", "user": "thisisakshat", "upvotes": 4, "views": 607, "problem_title": "base 7", "number": 504, "acceptance": 0.48, "difficulty": "Easy", "__index_level_0__": 8882, "question": "Given an integer num, return a string of its base 7 representation.\n Example 1:\nInput: num = 100\nOutput: \"202\"\nExample 2:\nInput: num = -7\nOutput: \"-10\"\n Constraints:\n-107 <= num <= 107" }, { "post_href": "https://leetcode.com/problems/relative-ranks/discuss/1705542/Python-Simple-Solution-using-Max-Heap", "python_solutions": "class Solution:\n def findRelativeRanks(self, score: List[int]) -> List[str]:\n rankings = []\n for i, val in enumerate(score):\n heappush(rankings, (-val, i))\n ans = [''] * len(score)\n r = 1\n rank = [\"Gold Medal\", \"Silver Medal\", \"Bronze Medal\"]\n while len(rankings) != 0:\n _, i = heappop(rankings)\n if r <= 3:\n ans[i] = rank[r-1]\n else:\n ans[i] = f'{r}'\n r += 1\n return ans", "slug": "relative-ranks", "post_title": "[Python] Simple Solution using Max-Heap", "user": "anCoderr", "upvotes": 8, "views": 573, "problem_title": "relative ranks", "number": 506, "acceptance": 0.5920000000000001, "difficulty": "Easy", "__index_level_0__": 8896, "question": "You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.\nThe athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:\nThe 1st place athlete's rank is \"Gold Medal\".\nThe 2nd place athlete's rank is \"Silver Medal\".\nThe 3rd place athlete's rank is \"Bronze Medal\".\nFor the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is \"x\").\nReturn an array answer of size n where answer[i] is the rank of the ith athlete.\n Example 1:\nInput: score = [5,4,3,2,1]\nOutput: [\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\nExplanation: The placements are [1st, 2nd, 3rd, 4th, 5th].\nExample 2:\nInput: score = [10,3,8,9,4]\nOutput: [\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\nExplanation: The placements are [1st, 5th, 3rd, 2nd, 4th].\n Constraints:\nn == score.length\n1 <= n <= 104\n0 <= score[i] <= 106\nAll the values in score are unique." }, { "post_href": "https://leetcode.com/problems/perfect-number/discuss/1268856/Python3-simple-solution", "python_solutions": "class Solution:\n def checkPerfectNumber(self, num: int) -> bool:\n if num == 1:\n return False\n res = 1\n for i in range(2,int(num**0.5)+1):\n if num%i == 0:\n res += i + num//i\n return res == num", "slug": "perfect-number", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 10, "views": 439, "problem_title": "perfect number", "number": 507, "acceptance": 0.3779999999999999, "difficulty": "Easy", "__index_level_0__": 8928, "question": "A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.\nGiven an integer n, return true if n is a perfect number, otherwise return false.\n Example 1:\nInput: num = 28\nOutput: true\nExplanation: 28 = 1 + 2 + 4 + 7 + 14\n1, 2, 4, 7, and 14 are all divisors of 28.\nExample 2:\nInput: num = 7\nOutput: false\n Constraints:\n1 <= num <= 108" }, { "post_href": "https://leetcode.com/problems/most-frequent-subtree-sum/discuss/1101640/A-Basic-Python", "python_solutions": "class Solution:\n def findFrequentTreeSum(self, root: TreeNode) -> List[int]:\n \n counts = collections.Counter()\n \n def dfs(node):\n if not node: return 0 \n result = node.val + dfs(node.left) + dfs(node.right)\n counts[result] += 1 \n return result\n \n dfs(root) \n \n # Try to return the most frequent elements\n # Return [] if we run into index errors\n try:\n freq = counts.most_common(1)[0][1]\n return [x[0] for x in counts.items() if x[1] == freq]\n except:\n return []", "slug": "most-frequent-subtree-sum", "post_title": "A Basic Python", "user": "dev-josh", "upvotes": 1, "views": 117, "problem_title": "most frequent subtree sum", "number": 508, "acceptance": 0.644, "difficulty": "Medium", "__index_level_0__": 8945, "question": "Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.\nThe subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).\n Example 1:\nInput: root = [5,2,-3]\nOutput: [2,-3,4]\nExample 2:\nInput: root = [5,2,-5]\nOutput: [2]\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-105 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/fibonacci-number/discuss/336501/Solution-in-Python-3-(beats-~100)-(three-lines)", "python_solutions": "class Solution:\n def fib(self, N: int) -> int:\n \ta, b = 0, 1\n \tfor i in range(N): a, b = b, a + b\n \treturn a\n\t\t\n\t\t\n- Python 3\n- Junaid Mansuri", "slug": "fibonacci-number", "post_title": "Solution in Python 3 (beats ~100%) (three lines)", "user": "junaidmansuri", "upvotes": 41, "views": 6700, "problem_title": "fibonacci number", "number": 509, "acceptance": 0.6920000000000001, "difficulty": "Easy", "__index_level_0__": 8953, "question": "The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,\nF(0) = 0, F(1) = 1\nF(n) = F(n - 1) + F(n - 2), for n > 1.\nGiven n, calculate F(n).\n Example 1:\nInput: n = 2\nOutput: 1\nExplanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\nExample 2:\nInput: n = 3\nOutput: 2\nExplanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\nExample 3:\nInput: n = 4\nOutput: 3\nExplanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n Constraints:\n0 <= n <= 30" }, { "post_href": "https://leetcode.com/problems/find-bottom-left-tree-value/discuss/2680305/Pyhton3-BFS-Solution-oror-BGG", "python_solutions": "class Solution:\n def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n q=[[root]]\n nodes=[]\n while q:\n nodes = q.pop(0)\n t=[]\n for n in nodes:\n if n.left:\n t.append(n.left)\n if n.right:\n t.append(n.right)\n if t:\n q.append(t)\n return nodes[0].val\n# Please upvote if you understand the solution", "slug": "find-bottom-left-tree-value", "post_title": "Pyhton3 BFS Solution || BGG", "user": "hoo__mann", "upvotes": 1, "views": 151, "problem_title": "find bottom left tree value", "number": 513, "acceptance": 0.665, "difficulty": "Medium", "__index_level_0__": 9027, "question": "Given the root of a binary tree, return the leftmost value in the last row of the tree.\n Example 1:\nInput: root = [2,1,3]\nOutput: 1\nExample 2:\nInput: root = [1,2,3,4,null,5,6,null,null,7]\nOutput: 7\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-231 <= Node.val <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/freedom-trail/discuss/1367426/Python3-top-down-dp", "python_solutions": "class Solution:\n def findRotateSteps(self, ring: str, key: str) -> int:\n locs = {}\n for i, ch in enumerate(ring): locs.setdefault(ch, []).append(i)\n \n @cache \n def fn(i, j): \n \"\"\"Return turns to finish key[j:] startin from ith position on ring.\"\"\"\n if j == len(key): return 0 \n loc = locs[key[j]]\n k = bisect_left(loc, i) % len(loc)\n ans = min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1)\n k = (k-1) % len(loc)\n ans = min(ans, min(abs(i-loc[k]), len(ring) - abs(i-loc[k])) + fn(loc[k], j+1))\n return ans \n \n return fn(0, 0) + len(key)", "slug": "freedom-trail", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 165, "problem_title": "freedom trail", "number": 514, "acceptance": 0.467, "difficulty": "Hard", "__index_level_0__": 9051, "question": "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 to open the door.\nGiven a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.\nInitially, the first character of the ring is aligned at the \"12:00\" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the \"12:00\" direction and then by pressing the center button.\nAt the stage of rotating the ring to spell the key character key[i]:\nYou can rotate the ring clockwise or anticlockwise by one place, which counts as one step. The final purpose of the rotation is to align one of ring's characters at the \"12:00\" direction, where this character must equal key[i].\nIf the character key[i] has been aligned at the \"12:00\" direction, press the center button to spell, which also counts as one step. After the pressing, you could begin to spell the next character in the key (next stage). Otherwise, you have finished all the spelling.\n Example 1:\nInput: ring = \"godding\", key = \"gd\"\nOutput: 4\nExplanation:\nFor the first key character 'g', since it is already in place, we just need 1 step to spell this character. \nFor the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\nAlso, we need 1 more step for spelling.\nSo the final output is 4.\nExample 2:\nInput: ring = \"godding\", key = \"godding\"\nOutput: 13\n Constraints:\n1 <= ring.length, key.length <= 100\nring and key consist of only lower case English letters.\nIt is guaranteed that key could always be spelled by rotating ring." }, { "post_href": "https://leetcode.com/problems/find-largest-value-in-each-tree-row/discuss/1620422/Python-3-easy-dfs-recursive-solution-faster-than-94", "python_solutions": "class Solution:\n def largestValues(self, root: Optional[TreeNode]) -> List[int]:\n res = []\n\n def helper(root, depth):\n if root is None:\n return\n \n if depth == len(res):\n res.append(root.val)\n else:\n res[depth] = max(res[depth], root.val)\n \n helper(root.left, depth + 1)\n helper(root.right, depth + 1)\n \n helper(root, 0)\n return res", "slug": "find-largest-value-in-each-tree-row", "post_title": "Python 3, easy dfs recursive solution, faster than 94%", "user": "dereky4", "upvotes": 1, "views": 109, "problem_title": "find largest value in each tree row", "number": 515, "acceptance": 0.6459999999999999, "difficulty": "Medium", "__index_level_0__": 9053, "question": "Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).\n Example 1:\nInput: root = [1,3,2,5,3,null,9]\nOutput: [1,3,9]\nExample 2:\nInput: root = [1,2,3]\nOutput: [1,3]\n Constraints:\nThe number of nodes in the tree will be in the range [0, 104].\n-231 <= Node.val <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/longest-palindromic-subsequence/discuss/1968323/Python-3-Approaches-(Recursion-%2B-Memoization-%2B-DP)", "python_solutions": "class Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n return self.get_longest_subseq(0, len(s)-1, s)\n \n def get_longest_subseq(self, start, end, s):\n \"\"\"\n method used to find the longest palindrome subsequence in a string\n start: start index of the string\n end: end index of the string\n s: string\n return: length of the longest palindrome subsequence\n \"\"\"\n if start == end:\n return 1\n\t\t\t\n if start > end:\n return 0\n\n if s[start] == s[end]:\n return 2 + self.get_longest_subseq(start + 1, end - 1, s)\n \n return max(self.get_longest_subseq(start + 1, end, s), self.get_longest_subseq(start, end - 1, s))", "slug": "longest-palindromic-subsequence", "post_title": "Python - 3 Approaches (Recursion + Memoization + DP)", "user": "superGloria", "upvotes": 6, "views": 225, "problem_title": "longest palindromic subsequence", "number": 516, "acceptance": 0.607, "difficulty": "Medium", "__index_level_0__": 9070, "question": "Given a string s, find the longest palindromic subsequence's length in s.\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n Example 1:\nInput: s = \"bbbab\"\nOutput: 4\nExplanation: One possible longest palindromic subsequence is \"bbbb\".\nExample 2:\nInput: s = \"cbbd\"\nOutput: 2\nExplanation: One possible longest palindromic subsequence is \"bb\".\n Constraints:\n1 <= s.length <= 1000\ns consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/super-washing-machines/discuss/1494245/Python3-greedy", "python_solutions": "class Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n total = sum(machines)\n if total % len(machines): return -1 # impossible \n avg = total // len(machines)\n \n ans = prefix = 0\n for i, x in enumerate(machines): \n ans = max(ans, abs(prefix), x - avg)\n prefix += x - avg\n return ans", "slug": "super-washing-machines", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 1, "views": 138, "problem_title": "super washing machines", "number": 517, "acceptance": 0.401, "difficulty": "Hard", "__index_level_0__": 9099, "question": "You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.\nFor each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.\nGiven an integer array machines representing the number of dresses in each washing machine from left to right on the line, return 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 Example 1:\nInput: machines = [1,0,5]\nOutput: 3\nExplanation:\n1st move: 1 0 <-- 5 => 1 1 4\n2nd move: 1 <-- 1 <-- 4 => 2 1 3\n3rd move: 2 1 <-- 3 => 2 2 2\nExample 2:\nInput: machines = [0,3,0]\nOutput: 2\nExplanation:\n1st move: 0 <-- 3 0 => 1 2 0\n2nd move: 1 2 --> 0 => 1 1 1\nExample 3:\nInput: machines = [0,2,0]\nOutput: -1\nExplanation:\nIt's impossible to make all three washing machines have the same number of dresses.\n Constraints:\nn == machines.length\n1 <= n <= 104\n0 <= machines[i] <= 105" }, { "post_href": "https://leetcode.com/problems/coin-change-ii/discuss/675186/Python3-DP-Solution-O(mn)-Time-and-Space", "python_solutions": "class Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n dp = [[1]+[0]*amount for _ in range(len(coins)+1)]\n for i in range(1, len(coins)+1):\n for j in range(1, amount+1):\n if coins[i-1] <= j:\n dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]]\n else:\n dp[i][j] = dp[i-1][j]\n return dp[len(coins)][amount] # or dp[-1][-1]", "slug": "coin-change-ii", "post_title": "Python3 DP Solution - O(mn) Time and Space", "user": "schedutron", "upvotes": 9, "views": 1200, "problem_title": "coin change ii", "number": 518, "acceptance": 0.599, "difficulty": "Medium", "__index_level_0__": 9100, "question": "You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\nReturn the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.\nYou may assume that you have an infinite number of each kind of coin.\nThe answer is guaranteed to fit into a signed 32-bit integer.\n Example 1:\nInput: amount = 5, coins = [1,2,5]\nOutput: 4\nExplanation: there are four ways to make up the amount:\n5=5\n5=2+2+1\n5=2+1+1+1\n5=1+1+1+1+1\nExample 2:\nInput: amount = 3, coins = [2]\nOutput: 0\nExplanation: the amount of 3 cannot be made up just with coins of 2.\nExample 3:\nInput: amount = 10, coins = [10]\nOutput: 1\n Constraints:\n1 <= coins.length <= 300\n1 <= coins[i] <= 5000\nAll the values of coins are unique.\n0 <= amount <= 5000" }, { "post_href": "https://leetcode.com/problems/random-flip-matrix/discuss/2108517/Python3Three-solutions-with-detailed-explanation.", "python_solutions": "class Solution:\n\n def __init__(self, m: int, n: int):\n self.nums = m * n - 1\n self.cols = n\n self.flipped = set()\n \n\n def flip(self) -> List[int]:\n rc = random.randint(0, self.nums)\n while rc in self.flipped:\n rc = random.randint(0, self.nums)\n \n self.flipped.add(rc)\n return [rc // self.cols, rc % self.cols]\n \n\n def reset(self) -> None:\n self.flipped = set()", "slug": "random-flip-matrix", "post_title": "[Python3]Three solutions with detailed explanation.", "user": "AlainWong", "upvotes": 0, "views": 55, "problem_title": "random flip matrix", "number": 519, "acceptance": 0.3989999999999999, "difficulty": "Medium", "__index_level_0__": 9144, "question": "There is an m x n binary grid matrix with all the values set 0 initially. Design an algorithm to randomly pick an index (i, j) where matrix[i][j] == 0 and flips it to 1. All the indices (i, j) where matrix[i][j] == 0 should be equally likely to be returned.\nOptimize your algorithm to minimize the number of calls made to the built-in random function of your language and optimize the time and space complexity.\nImplement the Solution class:\nSolution(int m, int n) Initializes the object with the size of the binary matrix m and n.\nint[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.\nvoid reset() Resets all the values of the matrix to be 0.\n Example 1:\nInput\n[\"Solution\", \"flip\", \"flip\", \"flip\", \"reset\", \"flip\"]\n[[3, 1], [], [], [], [], []]\nOutput\n[null, [1, 0], [2, 0], [0, 0], null, [2, 0]]\n\nExplanation\nSolution solution = new Solution(3, 1);\nsolution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\nsolution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\nsolution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\nsolution.reset(); // All the values are reset to 0 and can be returned.\nsolution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\n Constraints:\n1 <= m, n <= 104\nThere will be at least one free cell for each call to flip.\nAt most 1000 calls will be made to flip and reset." }, { "post_href": "https://leetcode.com/problems/detect-capital/discuss/336441/Solution-in-Python-3-(one-line)", "python_solutions": "class Solution:\n def detectCapitalUse(self, word: str) -> bool:\n \treturn word in [word.upper(), word.lower(), word.title()]\n\t\t\n\n- Python 3\n- Junaid Mansuri", "slug": "detect-capital", "post_title": "Solution in Python 3 (one line)", "user": "junaidmansuri", "upvotes": 6, "views": 541, "problem_title": "detect capital", "number": 520, "acceptance": 0.555, "difficulty": "Easy", "__index_level_0__": 9147, "question": "We define the usage of capitals in a word to be right when one of the following cases holds:\nAll letters in this word are capitals, like \"USA\".\nAll letters in this word are not capitals, like \"leetcode\".\nOnly the first letter in this word is capital, like \"Google\".\nGiven a string word, return true if the usage of capitals in it is right.\n Example 1:\nInput: word = \"USA\"\nOutput: true\nExample 2:\nInput: word = \"FlaG\"\nOutput: false\n Constraints:\n1 <= word.length <= 100\nword consists of lowercase and uppercase English letters." }, { "post_href": "https://leetcode.com/problems/longest-uncommon-subsequence-i/discuss/1277607/python-two-lines-or-easy", "python_solutions": "class Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n if a==b:return -1\n else:return max(len(a),len(b))", "slug": "longest-uncommon-subsequence-i", "post_title": "python two lines | easy", "user": "chikushen99", "upvotes": 4, "views": 314, "problem_title": "longest uncommon subsequence i", "number": 521, "acceptance": 0.603, "difficulty": "Easy", "__index_level_0__": 9194, "question": "Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If no such uncommon subsequence exists, return -1.\nAn uncommon subsequence between two strings is a string that is a\nsubsequence\nof exactly one of them.\n Example 1:\nInput: a = \"aba\", b = \"cdc\"\nOutput: 3\nExplanation: One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\nNote that \"cdc\" is also a longest uncommon subsequence.\nExample 2:\nInput: a = \"aaa\", b = \"bbb\"\nOutput: 3\nExplanation: The longest uncommon subsequences are \"aaa\" and \"bbb\".\nExample 3:\nInput: a = \"aaa\", b = \"aaa\"\nOutput: -1\nExplanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a. So the answer would be -1.\n Constraints:\n1 <= a.length, b.length <= 100\na and b consist of lower-case English letters." }, { "post_href": "https://leetcode.com/problems/longest-uncommon-subsequence-ii/discuss/380412/Solution-in-Python-3-(beats-~100)", "python_solutions": "class Solution:\n def findLUSlength(self, S: List[str]) -> int:\n \tC = collections.Counter(S)\n \tS = sorted(C.keys(), key = len, reverse = True)\n \tfor i,s in enumerate(S):\n \t\tif C[s] != 1: continue\n \t\tb = True\n \t\tfor j in range(i):\n \t\t\tI, c = -1, True\n \t\t\tfor i in s:\n \t\t\t\tI = S[j].find(i,I+1)\n \t\t\t\tif I == -1:\n \t\t\t\t\tc = False\n \t\t\t\t\tbreak\n \t\t\tif c:\n \t\t\t\tb = False\n \t\t\t\tbreak\n \t\tif b: return len(s)\n \treturn -1\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "longest-uncommon-subsequence-ii", "post_title": "Solution in Python 3 (beats ~100%)", "user": "junaidmansuri", "upvotes": 2, "views": 648, "problem_title": "longest uncommon subsequence ii", "number": 522, "acceptance": 0.4039999999999999, "difficulty": "Medium", "__index_level_0__": 9209, "question": "Given an array of strings strs, return the length of the longest uncommon subsequence between them. If the longest uncommon subsequence does not exist, return -1.\nAn uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.\nA subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\nFor example, \"abc\" is a subsequence of \"aebdc\" because you can delete the underlined characters in \"aebdc\" to get \"abc\". Other subsequences of \"aebdc\" include \"aebdc\", \"aeb\", and \"\" (empty string).\n Example 1:\nInput: strs = [\"aba\",\"cdc\",\"eae\"]\nOutput: 3\nExample 2:\nInput: strs = [\"aaa\",\"aaa\",\"aa\"]\nOutput: -1\n Constraints:\n2 <= strs.length <= 50\n1 <= strs[i].length <= 10\nstrs[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/continuous-subarray-sum/discuss/1582670/Python-Easy-Solution-or-Brute-Force-and-Optimal-Approach", "python_solutions": "class Solution:\n\tdef checkSubarraySum(self, nums: List[int], k: int) -> bool:\n\t\t# Brute Force: O(\ud835\udc5b^2) - TLE\n\t\tcount = 0\n\t\tfor i in range(len(nums)):\n\t\t\tsum = 0\n\t\t\tfor j in range(i, len(nums)):\n\t\t\t\tsum += nums[j]\n\t\t\t\tif sum % k == 0:\n\t\t\t\t return True\n\t\treturn False\n\nclass Solution:\n\tdef checkSubarraySum(self, nums: List[int], k: int) -> bool:\n\t\t# Optimal Approach - Time and Space: O(n), O(n)\n\t\tres = {0: -1}\n\t\tprefSum = 0\n\t\tfor i in range(len(nums)):\n\t\t\tprefSum += nums[i]\n\t\t\trem = prefSum % k\n\t\t\tif rem in res:\n\t\t\t\tif i-res[rem] > 1:\n\t\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tres[rem] = i\n\t\treturn False", "slug": "continuous-subarray-sum", "post_title": "Python Easy Solution | Brute Force and Optimal Approach", "user": "leet_satyam", "upvotes": 5, "views": 603, "problem_title": "continuous subarray sum", "number": 523, "acceptance": 0.285, "difficulty": "Medium", "__index_level_0__": 9213, "question": "Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.\nA good subarray is a subarray where:\nits length is at least two, and\nthe sum of the elements of the subarray is a multiple of k.\nNote that:\nA subarray is a contiguous part of the array.\nAn integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.\n Example 1:\nInput: nums = [23,2,4,6,7], k = 6\nOutput: true\nExplanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.\nExample 2:\nInput: nums = [23,2,6,4,7], k = 6\nOutput: true\nExplanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.\nExample 3:\nInput: nums = [23,2,6,4,7], k = 13\nOutput: false\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109\n0 <= sum(nums[i]) <= 231 - 1\n1 <= k <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/discuss/1077760/Python.-very-clear-and-simplistic-solution.", "python_solutions": "class Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n def is_subseq(main: str, sub: str) -> bool:\n i, j, m, n = 0, 0, len(main), len(sub)\n while i < m and j < n and n - j >= m - i:\n if main[i] == sub[j]:\n i += 1\n j += 1\n return i == m\n \n res = ''\n helper = sorted(d, key = lambda x: len(x), reverse = True)\n for word in helper:\n if len(word) < len(res): return res\n if ( not res or word < res ) and is_subseq(word, s):\n res = word\n return res", "slug": "longest-word-in-dictionary-through-deleting", "post_title": "Python. very clear and simplistic solution.", "user": "m-d-f", "upvotes": 6, "views": 879, "problem_title": "longest word in dictionary through deleting", "number": 524, "acceptance": 0.512, "difficulty": "Medium", "__index_level_0__": 9254, "question": "Given a string s and a string array dictionary, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.\n Example 1:\nInput: s = \"abpcplea\", dictionary = [\"ale\",\"apple\",\"monkey\",\"plea\"]\nOutput: \"apple\"\nExample 2:\nInput: s = \"abpcplea\", dictionary = [\"a\",\"b\",\"c\"]\nOutput: \"a\"\n Constraints:\n1 <= s.length <= 1000\n1 <= dictionary.length <= 1000\n1 <= dictionary[i].length <= 1000\ns and dictionary[i] consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/contiguous-array/discuss/577489/Python-O(n)-by-partial-sum-and-dictionary.-90%2B-w-Visualization", "python_solutions": "class Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n\n partial_sum = 0\n \n\t\t# table is a dictionary\n\t\t# key : partial sum value\n\t\t# value : the left-most index who has the partial sum value\n\t\t\n table = { 0: -1}\n \n max_length = 0\n \n for idx, number in enumerate( nums ):\n \n # partial_sum add 1 for 1\n # partial_sum minus 1 for 0\n \n if number:\n partial_sum += 1\n else:\n partial_sum -= 1\n \n \n if partial_sum in table:\n \n # we have a subarray with equal number of 0 and 1\n # update max length\n \n max_length = max( max_length, ( idx - table[partial_sum] ) )\n \n else:\n # update the left-most index for specified partial sum value\n table[ partial_sum ] = idx\n \n return max_length", "slug": "contiguous-array", "post_title": "Python O(n) by partial sum and dictionary. 90%+ [w/ Visualization]", "user": "brianchiang_tw", "upvotes": 12, "views": 1700, "problem_title": "contiguous array", "number": 525, "acceptance": 0.4679999999999999, "difficulty": "Medium", "__index_level_0__": 9274, "question": "Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.\n Example 1:\nInput: nums = [0,1]\nOutput: 2\nExplanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.\nExample 2:\nInput: nums = [0,1,0]\nOutput: 2\nExplanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n Constraints:\n1 <= nums.length <= 105\nnums[i] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/beautiful-arrangement/discuss/1094146/Python-Backtracking-the-more-intuitive-way", "python_solutions": "class Solution:\n def countArrangement(self, n: int) -> int:\n self.count = 0\n self.backtrack(n, 1, [])\n return self.count\n \n def backtrack(self, N, idx, temp):\n if len(temp) == N:\n self.count += 1\n return\n \n for i in range(1, N+1):\n if i not in temp and (i % idx == 0 or idx % i == 0):\n temp.append(i)\n self.backtrack(N, idx+1, temp)\n temp.pop()", "slug": "beautiful-arrangement", "post_title": "Python Backtracking, the more intuitive way", "user": "IamCookie", "upvotes": 8, "views": 872, "problem_title": "beautiful arrangement", "number": 526, "acceptance": 0.6459999999999999, "difficulty": "Medium", "__index_level_0__": 9297, "question": "Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:\nperm[i] is divisible by i.\ni is divisible by perm[i].\nGiven an integer n, return the number of the beautiful arrangements that you can construct.\n Example 1:\nInput: n = 2\nOutput: 2\nExplanation: \nThe first beautiful arrangement is [1,2]:\n - perm[1] = 1 is divisible by i = 1\n - perm[2] = 2 is divisible by i = 2\nThe second beautiful arrangement is [2,1]:\n - perm[1] = 2 is divisible by i = 1\n - i = 2 is divisible by perm[2] = 1\nExample 2:\nInput: n = 1\nOutput: 1\n Constraints:\n1 <= n <= 15" }, { "post_href": "https://leetcode.com/problems/random-pick-with-weight/discuss/1535699/Better-than-96.5", "python_solutions": "class Solution:\n\n def __init__(self, w: List[int]):\n self.li = []\n ma = sum(w)\n \n for i, weight in enumerate(w):\n ratio = ceil(weight / ma * 100)\n self.li += ([i] * ratio)\n \n\n def pickIndex(self) -> int:\n return random.choice(self.li)", "slug": "random-pick-with-weight", "post_title": "Better than 96.5%", "user": "josephp27", "upvotes": 8, "views": 815, "problem_title": "random pick with weight", "number": 528, "acceptance": 0.461, "difficulty": "Medium", "__index_level_0__": 9315, "question": "You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.\nYou need to implement the function pickIndex(), which randomly picks an index in the range [0, w.length - 1] (inclusive) and returns it. The probability of picking an index i is w[i] / sum(w).\nFor example, if w = [1, 3], the probability of picking index 0 is 1 / (1 + 3) = 0.25 (i.e., 25%), and the probability of picking index 1 is 3 / (1 + 3) = 0.75 (i.e., 75%).\n Example 1:\nInput\n[\"Solution\",\"pickIndex\"]\n[[[1]],[]]\nOutput\n[null,0]\n\nExplanation\nSolution solution = new Solution([1]);\nsolution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\nExample 2:\nInput\n[\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n[[[1,3]],[],[],[],[],[]]\nOutput\n[null,1,1,1,1,0]\n\nExplanation\nSolution solution = new Solution([1, 3]);\nsolution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 1\nsolution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n\nSince this is a randomization problem, multiple answers are allowed.\nAll of the following outputs can be considered correct:\n[null,1,1,1,1,0]\n[null,1,1,1,1,1]\n[null,1,1,1,0,0]\n[null,1,1,1,0,1]\n[null,1,0,1,0,0]\n......\nand so on.\n Constraints:\n1 <= w.length <= 104\n1 <= w[i] <= 105\npickIndex will be called at most 104 times." }, { "post_href": "https://leetcode.com/problems/minesweeper/discuss/875335/Python-3-or-Ad-hoc-DFS-or-Explanation", "python_solutions": "class Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n m, n = len(board), len(board[0])\n def dfs(x, y):\n if board[x][y] == 'M': board[x][y] = 'X'\n elif board[x][y] == 'E':\n cnt, nei = 0, []\n for i, j in map(lambda v: (v[0]+x, v[1]+y), [(-1, 0), (1, 0), (-1, -1), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 1)]):\n if 0 <= i < m and 0 <= j < n:\n nei.append((i, j))\n if board[i][j] == 'M': cnt += 1\n if not cnt:\n board[x][y] = 'B'\n for i, j in nei: dfs(i, j)\n else: board[x][y] = str(cnt)\n dfs(*click) \n return board", "slug": "minesweeper", "post_title": "Python 3 | Ad-hoc DFS | Explanation", "user": "idontknoooo", "upvotes": 5, "views": 743, "problem_title": "minesweeper", "number": 529, "acceptance": 0.655, "difficulty": "Medium", "__index_level_0__": 9331, "question": "Let's play the minesweeper game (Wikipedia, online game)!\nYou are given an m x n char matrix board representing the game board where:\n'M' represents an unrevealed mine,\n'E' represents an unrevealed empty square,\n'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),\ndigit ('1' to '8') represents how many mines are adjacent to this revealed square, and\n'X' represents a revealed mine.\nYou are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').\nReturn the board after revealing this position according to the following rules:\nIf a mine 'M' is revealed, then the game is over. You should change it to 'X'.\nIf an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively.\nIf an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines.\nReturn the board when no more squares will be revealed.\n Example 1:\nInput: board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]\nOutput: [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\nExample 2:\nInput: board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]\nOutput: [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n Constraints:\nm == board.length\nn == board[i].length\n1 <= m, n <= 50\nboard[i][j] is either 'M', 'E', 'B', or a digit from '1' to '8'.\nclick.length == 2\n0 <= clickr < m\n0 <= clickc < n\nboard[clickr][clickc] is either 'M' or 'E'." }, { "post_href": "https://leetcode.com/problems/minimum-absolute-difference-in-bst/discuss/1414654/Faster-than-99.61-of-Python3-with-logical-explanation", "python_solutions": "class Solution:\n def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n d = float('inf')\n s = []\n if root == None:\n return \n d = self.traverse(root,d,s)\n return d\n def traverse(self,root,d,s):\n if root.left != None:\n d = self.traverse(root.left,d,s)\n s.append(root.val)\n if len(s)>1:\n diff = s[-1]-s[-2]\n if diff < d:\n d = diff\n if root.right != None:\n d = self.traverse(root.right,d,s) \n return d", "slug": "minimum-absolute-difference-in-bst", "post_title": "Faster than 99.61% of Python3 with logical explanation", "user": "iron_man_365", "upvotes": 4, "views": 786, "problem_title": "minimum absolute difference in bst", "number": 530, "acceptance": 0.568, "difficulty": "Easy", "__index_level_0__": 9349, "question": "Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.\n Example 1:\nInput: root = [4,2,6,1,3]\nOutput: 1\nExample 2:\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n Constraints:\nThe number of nodes in the tree is in the range [2, 104].\n0 <= Node.val <= 105\n Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/" }, { "post_href": "https://leetcode.com/problems/k-diff-pairs-in-an-array/discuss/1757434/Python-O(n)-Solution-or-98-Faster-or-Easy-Solution-or-K-diff-Pairs-in-an-Array", "python_solutions": "class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n cnt=0\n c=Counter(nums)\n \n if k==0:\n for key,v in c.items():\n if v>1:\n cnt+=1\n else:\n for key,v in c.items():\n if key+k in c:\n cnt+=1\n return cnt", "slug": "k-diff-pairs-in-an-array", "post_title": "\u2714\ufe0f Python O(n) Solution | 98% Faster | Easy Solution | K-diff Pairs in an Array", "user": "pniraj657", "upvotes": 34, "views": 2200, "problem_title": "k diff pairs in an array", "number": 532, "acceptance": 0.408, "difficulty": "Medium", "__index_level_0__": 9362, "question": "Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.\nA k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:\n0 <= i, j < nums.length\ni != j\n|nums[i] - nums[j]| == k\nNotice that |val| denotes the absolute value of val.\n Example 1:\nInput: nums = [3,1,4,1,5], k = 2\nOutput: 2\nExplanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).\nAlthough we have two 1s in the input, we should only return the number of unique pairs.\nExample 2:\nInput: nums = [1,2,3,4,5], k = 1\nOutput: 4\nExplanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\nExample 3:\nInput: nums = [1,3,1,5,4], k = 0\nOutput: 1\nExplanation: There is one 0-diff pair in the array, (1, 1).\n Constraints:\n1 <= nums.length <= 104\n-107 <= nums[i] <= 107\n0 <= k <= 107" }, { "post_href": "https://leetcode.com/problems/complex-number-multiplication/discuss/1187864/Python3-simple-solution", "python_solutions": "class Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n a1,b1 = num1.split('+')\n a1 = int(a1)\n b1 = int(b1[:-1])\n a2,b2 = num2.split('+')\n a2 = int(a2)\n b2 = int(b2[:-1])\n return str(a1*a2 + b1*b2*(-1)) + '+' + str(a1*b2 + a2*b1) + 'i'", "slug": "complex-number-multiplication", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 7, "views": 113, "problem_title": "complex number multiplication", "number": 537, "acceptance": 0.7140000000000001, "difficulty": "Medium", "__index_level_0__": 9384, "question": "A complex number can be represented as a string on the form \"real+imaginaryi\" where:\nreal is the real part and is an integer in the range [-100, 100].\nimaginary is the imaginary part and is an integer in the range [-100, 100].\ni2 == -1.\nGiven two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.\n Example 1:\nInput: num1 = \"1+1i\", num2 = \"1+1i\"\nOutput: \"0+2i\"\nExplanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\nExample 2:\nInput: num1 = \"1+-1i\", num2 = \"1+-1i\"\nOutput: \"0+-2i\"\nExplanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n Constraints:\nnum1 and num2 are valid complex numbers." }, { "post_href": "https://leetcode.com/problems/convert-bst-to-greater-tree/discuss/1057429/Python.-faster-than-100.00.-Explained-clear-and-Easy-understanding-solution.-O(n).-Recursive", "python_solutions": "class Solution:\n\tdef convertBST(self, root: TreeNode) -> TreeNode:\n\t\tsum = 0\n\t\t\n\t\tdef sol(root: TreeNode) -> TreeNode:\n\t\t\tnonlocal sum\n\t\t\tif root:\n\t\t\t\tsol(root.right)\n\t\t\t\troot.val += sum\n\t\t\t\tsum = root.val\n\t\t\t\tsol(root.left)\n\t\t\treturn root\n\t\t\n\t\treturn sol(root)", "slug": "convert-bst-to-greater-tree", "post_title": "Python. faster than 100.00%. Explained, clear & Easy-understanding solution. O(n). Recursive", "user": "m-d-f", "upvotes": 13, "views": 912, "problem_title": "convert bst to greater tree", "number": 538, "acceptance": 0.674, "difficulty": "Medium", "__index_level_0__": 9404, "question": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\nThe left subtree of a node contains only nodes with keys less than the node's key.\nThe right subtree of a node contains only nodes with keys greater than the node's key.\nBoth the left and right subtrees must also be binary search trees.\n Example 1:\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\nExample 2:\nInput: root = [0,null,1]\nOutput: [1,null,1]\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n-104 <= Node.val <= 104\nAll the values in the tree are unique.\nroot is guaranteed to be a valid binary search tree.\n Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" }, { "post_href": "https://leetcode.com/problems/minimum-time-difference/discuss/1829297/python-3-bucket-sort-O(n)-time-O(1)-space", "python_solutions": "class Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n M = 1440\n times = [False] * M\n for time in timePoints:\n minute = self.minute(time)\n if times[minute]:\n return 0\n times[minute] = True\n \n minutes = [i for i in range(M) if times[i]]\n return min((minutes[i] - minutes[i-1]) % M for i in range(len(minutes)))\n \n def minute(self, time: str) -> int:\n h, m = map(int, time.split(':'))\n return 60*h + m", "slug": "minimum-time-difference", "post_title": "[python 3] bucket sort, O(n) time, O(1) space", "user": "dereky4", "upvotes": 9, "views": 595, "problem_title": "minimum time difference", "number": 539, "acceptance": 0.563, "difficulty": "Medium", "__index_level_0__": 9431, "question": "Given a list of 24-hour clock time points in \"HH:MM\" format, return the minimum minutes difference between any two time-points in the list.\n Example 1:\nInput: timePoints = [\"23:59\",\"00:00\"]\nOutput: 1\nExample 2:\nInput: timePoints = [\"00:00\",\"23:59\",\"00:00\"]\nOutput: 0\n Constraints:\n2 <= timePoints.length <= 2 * 104\ntimePoints[i] is in the format \"HH:MM\"." }, { "post_href": "https://leetcode.com/problems/single-element-in-a-sorted-array/discuss/1587293/Python-3-Simple-Approaches-with-Explanation", "python_solutions": "class Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n counts = defaultdict(int)\n for num in nums:\n counts[num] += 1\n for num, count in counts.items():\n if count == 1:\n return num\n return -1 # this will never be reached\n\t\t# return Counter(nums).most_common()[-1][0] # one-liner, but TC O(nlogn)", "slug": "single-element-in-a-sorted-array", "post_title": "[Python] 3 Simple Approaches with Explanation", "user": "zayne-siew", "upvotes": 54, "views": 2800, "problem_title": "single element in a sorted array", "number": 540, "acceptance": 0.585, "difficulty": "Medium", "__index_level_0__": 9449, "question": "You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.\nReturn the single element that appears only once.\nYour solution must run in O(log n) time and O(1) space.\n Example 1:\nInput: nums = [1,1,2,3,3,4,4,8,8]\nOutput: 2\nExample 2:\nInput: nums = [3,3,7,7,10,11,11]\nOutput: 10\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/reverse-string-ii/discuss/343424/Python-3-solution-using-recursion-(efficient)-3-liner-with-explanation", "python_solutions": "class Solution:\n def reverseStr(self, s: str, k: int) -> str:\n if len(s)<(k):return s[::-1]\n if len(s)<(2*k):return (s[:k][::-1]+s[k:])\n return s[:k][::-1]+s[k:2*k]+self.reverseStr(s[2*k:],k)", "slug": "reverse-string-ii", "post_title": "Python 3 solution using recursion (efficient) 3-liner with explanation", "user": "ketan35", "upvotes": 22, "views": 1700, "problem_title": "reverse string ii", "number": 541, "acceptance": 0.505, "difficulty": "Easy", "__index_level_0__": 9496, "question": "Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.\nIf there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.\n Example 1:\nInput: s = \"abcdefg\", k = 2\nOutput: \"bacdfeg\"\nExample 2:\nInput: s = \"abcd\", k = 2\nOutput: \"bacd\"\n Constraints:\n1 <= s.length <= 104\ns consists of only lowercase English letters.\n1 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/01-matrix/discuss/1556018/WEEB-DOES-PYTHON-BFS", "python_solutions": "class Solution:\n\tdef updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n\t\trow, col = len(mat), len(mat[0])\n\t\tqueue = deque([])\n\n\t\tfor x in range(row):\n\t\t\tfor y in range(col):\n\t\t\t\tif mat[x][y] == 0:\n\t\t\t\t\tqueue.append((x, y, 1))\n\n\n\t\treturn self.bfs(row, col, queue, mat)\n\n\tdef bfs(self, row, col, queue, grid):\n\t\tvisited = set()\n\t\twhile queue:\n\t\t\tx, y, steps = queue.popleft()\n\n\t\t\tfor nx, ny in [[x+1,y], [x-1,y], [x,y+1], [x,y-1]]:\n\t\t\t\tif 0<=nx int:\n \"\"\"\n This function needs to do the following:\n 1. Calculate the maximum depth of the left and right sides of the given node\n 2. Determine the diameter at the given node and check if its the maximum\n \"\"\"\n # Calculate maximum depth\n left = self.depth(node.left) if node.left else 0\n right = self.depth(node.right) if node.right else 0\n # Calculate diameter\n if left + right > self.diameter:\n self.diameter = left + right\n # Make sure the parent node(s) get the correct depth from this node\n return 1 + (left if left > right else right)\n \n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n # if not root:\n # return 0\n self.depth(root) # root is guaranteed to be a TreeNode object\n return self.diameter", "slug": "diameter-of-binary-tree", "post_title": "Python Easy-to-understand solution w Explanation", "user": "zayne-siew", "upvotes": 56, "views": 3100, "problem_title": "diameter of binary tree", "number": 543, "acceptance": 0.561, "difficulty": "Easy", "__index_level_0__": 9572, "question": "Given the root of a binary tree, return the length of the diameter of the tree.\nThe diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.\nThe length of a path between two nodes is represented by the number of edges between them.\n Example 1:\nInput: root = [1,2,3,4,5]\nOutput: 3\nExplanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\nExample 2:\nInput: root = [1,2]\nOutput: 1\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/remove-boxes/discuss/1379392/Python3-dp", "python_solutions": "class Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n \n @cache\n def fn(lo, hi, k): \n \"\"\"Return max score of removing boxes from lo to hi with k to the left.\"\"\"\n if lo == hi: return 0 \n while lo+1 < hi and boxes[lo] == boxes[lo+1]: lo, k = lo+1, k+1\n ans = (k+1)*(k+1) + fn(lo+1, hi, 0)\n for mid in range(lo+2, hi): \n if boxes[lo] == boxes[mid]: \n ans = max(ans, fn(lo+1, mid, 0) + fn(mid, hi, k+1))\n return ans \n \n return fn(0, len(boxes), 0)", "slug": "remove-boxes", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 2, "views": 293, "problem_title": "remove boxes", "number": 546, "acceptance": 0.479, "difficulty": "Hard", "__index_level_0__": 9595, "question": "You are given several boxes with different colors represented by different positive numbers.\nYou 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.\nReturn the maximum points you can get.\n Example 1:\nInput: boxes = [1,3,2,2,2,3,4,3,1]\nOutput: 23\nExplanation:\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)\nExample 2:\nInput: boxes = [1,1,1]\nOutput: 9\nExample 3:\nInput: boxes = [1]\nOutput: 1\n Constraints:\n1 <= boxes.length <= 100\n1 <= boxes[i] <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-provinces/discuss/727759/Python3-solution-with-detailed-explanation", "python_solutions": "class Solution(object):\n def findCircleNum(self, M):\n \"\"\"\n :type M: List[List[int]]\n :rtype: int\n \"\"\"\n n = len(M) #1\n visited = [False]*n #2\n count = 0 #3\n \n if not M: #4\n return 0 #5\n \n def dfs(u): #6\n for v in range(n): #7\n if M[u][v] == 1 and visited[v] == False: #8\n visited[v] = True #9\n dfs(v) #10\n \n \n for idx in range(n): #11\n if visited[idx] == False: #12\n count += 1 #13\n visited[idx] == True #14\n dfs(idx) #15\n \n return count #16", "slug": "number-of-provinces", "post_title": "Python3 solution with detailed explanation", "user": "peyman_np", "upvotes": 17, "views": 1600, "problem_title": "number of provinces", "number": 547, "acceptance": 0.634, "difficulty": "Medium", "__index_level_0__": 9597, "question": "There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c.\nA province is a group of directly or indirectly connected cities and no other cities outside of the group.\nYou are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.\nReturn the total number of provinces.\n Example 1:\nInput: isConnected = [[1,1,0],[1,1,0],[0,0,1]]\nOutput: 2\nExample 2:\nInput: isConnected = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\n Constraints:\n1 <= n <= 200\nn == isConnected.length\nn == isConnected[i].length\nisConnected[i][j] is 1 or 0.\nisConnected[i][i] == 1\nisConnected[i][j] == isConnected[j][i]" }, { "post_href": "https://leetcode.com/problems/student-attendance-record-i/discuss/356636/Solution-in-Python-3-(one-line)", "python_solutions": "class Solution:\n def checkRecord(self, s: str) -> bool:\n \treturn (s.count('A') < 2) and ('LLL' not in s)\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "student-attendance-record-i", "post_title": "Solution in Python 3 (one line)", "user": "junaidmansuri", "upvotes": 16, "views": 940, "problem_title": "student attendance record i", "number": 551, "acceptance": 0.481, "difficulty": "Easy", "__index_level_0__": 9644, "question": "You are given a string s representing an attendance record for a student 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'L': Late.\n'P': Present.\nThe student is eligible for an attendance award if they meet both of the following criteria:\nThe student was absent ('A') for strictly fewer than 2 days total.\nThe student was never late ('L') for 3 or more consecutive days.\nReturn true if the student is eligible for an attendance award, or false otherwise.\n Example 1:\nInput: s = \"PPALLP\"\nOutput: true\nExplanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.\nExample 2:\nInput: s = \"PPALLL\"\nOutput: false\nExplanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.\n Constraints:\n1 <= s.length <= 1000\ns[i] is either 'A', 'L', or 'P'." }, { "post_href": "https://leetcode.com/problems/student-attendance-record-ii/discuss/356750/Solution-in-Python-3-(five-lines)-(with-explanation)", "python_solutions": "class Solution:\n def checkRecord(self, n: int) -> int:\n \tC, m = [1,1,0,1,0,0], 10**9 + 7\n \tfor i in range(n-1):\n \t\ta, b = sum(C[:3]) % m, sum(C[3:]) % m\n \t\tC = [a, C[0], C[1], a + b, C[3], C[4]]\n \treturn (sum(C) % m)", "slug": "student-attendance-record-ii", "post_title": "Solution in Python 3 (five lines) (with explanation)", "user": "junaidmansuri", "upvotes": 12, "views": 1900, "problem_title": "student attendance record ii", "number": 552, "acceptance": 0.412, "difficulty": "Hard", "__index_level_0__": 9674, "question": "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'L': Late.\n'P': Present.\nAny student is eligible for an attendance award if they meet both of the following criteria:\nThe student was absent ('A') for strictly fewer than 2 days total.\nThe student was never late ('L') for 3 or more consecutive days.\nGiven 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 Example 1:\nInput: n = 2\nOutput: 8\nExplanation: There are 8 records with length 2 that are eligible for an award:\n\"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\nOnly \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).\nExample 2:\nInput: n = 1\nOutput: 3\nExample 3:\nInput: n = 10101\nOutput: 183236316\n Constraints:\n1 <= n <= 105" }, { "post_href": "https://leetcode.com/problems/optimal-division/discuss/1265206/Python3-string-concatenation", "python_solutions": "class Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n if len(nums) <= 2: return \"/\".join(map(str, nums))\n return f'{nums[0]}/({\"/\".join(map(str, nums[1:]))})'", "slug": "optimal-division", "post_title": "[Python3] string concatenation", "user": "ye15", "upvotes": 3, "views": 86, "problem_title": "optimal division", "number": 553, "acceptance": 0.597, "difficulty": "Medium", "__index_level_0__": 9687, "question": "You are given an integer array nums. The adjacent integers in nums will perform the float division.\nFor example, for nums = [2,3,4], we will evaluate the expression \"2/3/4\".\nHowever, you can add any number of parenthesis at any position to change the priority of operations. You want to add these parentheses such the value of the expression after the evaluation is maximum.\nReturn the corresponding expression that has the maximum value in string format.\nNote: your expression should not contain redundant parenthesis.\n Example 1:\nInput: nums = [1000,100,10,2]\nOutput: \"1000/(100/10/2)\"\nExplanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200\nHowever, the bold parenthesis in \"1000/((100/10)/2)\" are redundant since they do not influence the operation priority.\nSo you should return \"1000/(100/10/2)\".\nOther cases:\n1000/(100/10)/2 = 50\n1000/(100/(10/2)) = 50\n1000/100/10/2 = 0.5\n1000/100/(10/2) = 2\nExample 2:\nInput: nums = [2,3,4]\nOutput: \"2/(3/4)\"\nExplanation: (2/(3/4)) = 8/3 = 2.667\nIt can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667\n Constraints:\n1 <= nums.length <= 10\n2 <= nums[i] <= 1000\nThere is only one optimal division for the given input." }, { "post_href": "https://leetcode.com/problems/brick-wall/discuss/1736767/python-easy-hashmap-solution", "python_solutions": "class Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n count = defaultdict(int)\n tot = len(wall)\n if tot == 1 and len(wall[0]) > 1:\n return 0\n elif tot == 1 and len(wall[0]) == 1:\n return 1\n \n for w in wall:\n s = 0 \n for i in range(len(w)):\n s += w[i]\n count[s] += 1\n count[s] -= 1\n\n return tot - max(count.values())", "slug": "brick-wall", "post_title": "python easy hashmap solution", "user": "byuns9334", "upvotes": 1, "views": 62, "problem_title": "brick wall", "number": 554, "acceptance": 0.532, "difficulty": "Medium", "__index_level_0__": 9696, "question": "There is a rectangular brick wall in front of you with n rows of bricks. The ith row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same.\nDraw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.\nGiven the 2D array wall that contains the information about the wall, return the minimum number of crossed bricks after drawing such a vertical line.\n Example 1:\nInput: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]\nOutput: 2\nExample 2:\nInput: wall = [[1],[1],[1]]\nOutput: 3\n Constraints:\nn == wall.length\n1 <= n <= 104\n1 <= wall[i].length <= 104\n1 <= sum(wall[i].length) <= 2 * 104\nsum(wall[i]) is the same for each row i.\n1 <= wall[i][j] <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/next-greater-element-iii/discuss/983461/Simple-Python-Solution-easy-to-understand-reading-backwards-from-the-end", "python_solutions": "class Solution:\n def nextGreaterElement(self, n: int) -> int:\n m=list(str(n)) ## n = 257761\n l = len(m) ## l = 6\n d = {}\n res = str(n)\n \n ## reading character backwards: 1->6->7->7->5 break\n for i,c in enumerate(m[::-1]): \n if not d:\n d[c]=1 ## d = {'1':1}\n else:\n if all(c >= x for x in d):\n d[c]=d.get(c,0)+1 ## d = {'1':1,'6':1,'7':2} \n else:\n d[c]=d.get(c,0)+1 ## d = {'1':1,'5':1,'6':1,'7':2}\n res = ''.join(m[:l-1-i]) ## res = '2'\n stock = sorted(list(d.keys())) ## stock = ['1','5','6','7']\n cplus = stock[stock.index(c)+1] ## cplus = '6' just > '5'\n res += cplus ## res = '26'\n d[cplus] -= 1 ## d = {'1':1,'5':1,'6':0,'7':2}\n res += ''.join([x * d[x] for x in stock]) \n\t\t\t\t\t ## res = '26' + '1577'\n break\n \n return int(res) if n < int(res) < (2**31-1) else -1", "slug": "next-greater-element-iii", "post_title": "Simple Python Solution, easy to understand, reading backwards from the end", "user": "KevinZzz666", "upvotes": 7, "views": 935, "problem_title": "next greater element iii", "number": 556, "acceptance": 0.341, "difficulty": "Medium", "__index_level_0__": 9708, "question": "Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1.\nNote that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1.\n Example 1:\nInput: n = 12\nOutput: 21\nExample 2:\nInput: n = 21\nOutput: -1\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/reverse-words-in-a-string-iii/discuss/332138/Simple-Python-3-Solution-(beats-~98)-(three-lines)", "python_solutions": "class Solution:\n def reverseWords(self, s: str) -> str:\n \ts = s.split()\n \tfor i in range(len(s)): s[i] = s[i][::-1]\n \treturn \" \".join(s)\n\t\n\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "reverse-words-in-a-string-iii", "post_title": "Simple Python 3 Solution (beats ~98%) (three lines)", "user": "junaidmansuri", "upvotes": 8, "views": 2000, "problem_title": "reverse words in a string iii", "number": 557, "acceptance": 0.816, "difficulty": "Easy", "__index_level_0__": 9725, "question": "Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.\n Example 1:\nInput: s = \"Let's take LeetCode contest\"\nOutput: \"s'teL ekat edoCteeL tsetnoc\"\nExample 2:\nInput: s = \"Mr Ding\"\nOutput: \"rM gniD\"\n Constraints:\n1 <= s.length <= 5 * 104\ns contains printable ASCII characters.\ns does not contain any leading or trailing spaces.\nThere is at least one word in s.\nAll the words in s are separated by a single space." }, { "post_href": "https://leetcode.com/problems/logical-or-of-two-binary-grids-represented-as-quad-trees/discuss/884082/Python3-9-line-recursive-(64ms-93.33)", "python_solutions": "class Solution:\n def intersect(self, quadTree1: 'Node', quadTree2: 'Node') -> 'Node':\n if quadTree1.isLeaf: return quadTree1 if quadTree1.val else quadTree2 # boundary condition \n if quadTree2.isLeaf: return quadTree2 if quadTree2.val else quadTree1 # boundary condition \n tl = self.intersect(quadTree1.topLeft, quadTree2.topLeft)\n tr = self.intersect(quadTree1.topRight, quadTree2.topRight)\n bl = self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)\n br = self.intersect(quadTree1.bottomRight, quadTree2.bottomRight)\n if tl.isLeaf and tr.isLeaf and bl.isLeaf and br.isLeaf and tl.val == tr.val == bl.val == br.val: \n return Node(tl.val, True, None, None, None, None)\n return Node(None, False, tl, tr, bl, br)", "slug": "logical-or-of-two-binary-grids-represented-as-quad-trees", "post_title": "[Python3] 9-line recursive (64ms 93.33%)", "user": "ye15", "upvotes": 2, "views": 151, "problem_title": "logical or of two binary grids represented as quad trees", "number": 558, "acceptance": 0.483, "difficulty": "Medium", "__index_level_0__": 9780, "question": "A Binary Matrix is a matrix in which all the elements are either 0 or 1.\nGiven quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 represents another n * n binary matrix.\nReturn a Quad-Tree representing the n * n binary matrix which is the result of logical bitwise OR of the two binary matrixes represented by quadTree1 and quadTree2.\nNotice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.\nA Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:\nval: True if the node represents a grid of 1's or False if the node represents a grid of 0's.\nisLeaf: True if the node is leaf node on the tree or False if the node has the four children.\nclass Node {\n public boolean val;\n public boolean isLeaf;\n public Node topLeft;\n public Node topRight;\n public Node bottomLeft;\n public Node bottomRight;\n}\nWe can construct a Quad-Tree from a two-dimensional area using the following steps:\nIf the current grid has the same value (i.e all 1's or all 0's) set isLeaf True and set val to the value of the grid and set the four children to Null and stop.\nIf the current grid has different values, set isLeaf to False and set val to any value and divide the current grid into four sub-grids as shown in the photo.\nRecurse for each of the children with the proper sub-grid.\nIf you want to know more about the Quad-Tree, you can refer to the wiki.\nQuad-Tree format:\nThe input/output represents the serialized format of a Quad-Tree using level order traversal, where null signifies a path terminator where no node exists below.\nIt is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].\nIf the value of isLeaf or val is True we represent it as 1 in the list [isLeaf, val] and if the value of isLeaf or val is False we represent it as 0.\n Example 1:\nInput: quadTree1 = [[0,1],[1,1],[1,1],[1,0],[1,0]]\n, quadTree2 = [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\nOutput: [[0,0],[1,1],[1,1],[1,1],[1,0]]\nExplanation: quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.\nIf we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.\nNotice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.\nExample 2:\nInput: quadTree1 = [[1,0]], quadTree2 = [[1,0]]\nOutput: [[1,0]]\nExplanation: Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.\nThe resulting matrix is of size 1*1 with also zero.\n Constraints:\nquadTree1 and quadTree2 are both valid Quad-Trees each representing a n * n grid.\nn == 2x where 0 <= x <= 9." }, { "post_href": "https://leetcode.com/problems/maximum-depth-of-n-ary-tree/discuss/629671/Python-O(n)-by-DFS-90%2B-w-Comment", "python_solutions": "class Solution:\n def maxDepth(self, root: 'Node') -> int:\n \n if root is None:\n # empty node or empty tree\n return 0\n \n else:\n # DFS to choose the longest path\n \n if root.children:\n # current node has subtrees\n return max( self.maxDepth(child) for child in root.children ) + 1\n \n else:\n # current node is leaf node\n return 1", "slug": "maximum-depth-of-n-ary-tree", "post_title": "Python O(n) by DFS 90%+ [w/ Comment]", "user": "brianchiang_tw", "upvotes": 4, "views": 438, "problem_title": "maximum depth of n ary tree", "number": 559, "acceptance": 0.716, "difficulty": "Easy", "__index_level_0__": 9782, "question": "Given a n-ary tree, find its maximum depth.\nThe maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\nNary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).\n Example 1:\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: 3\nExample 2:\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: 5\n Constraints:\nThe total number of nodes is in the range [0, 104].\nThe depth of the n-ary tree is less than or equal to 1000." }, { "post_href": "https://leetcode.com/problems/subarray-sum-equals-k/discuss/1759711/Python-Simple-Python-Solution-Using-PrefixSum-and-Dictionary", "python_solutions": "class Solution:\n\tdef subarraySum(self, nums: List[int], k: int) -> int:\n\n\t\tans=0\n\t\tprefsum=0\n\t\td={0:1}\n\n\t\tfor num in nums:\n\t\t\tprefsum = prefsum + num\n\n\t\t\tif prefsum-k in d:\n\t\t\t\tans = ans + d[prefsum-k]\n\n\t\t\tif prefsum not in d:\n\t\t\t\td[prefsum] = 1\n\t\t\telse:\n\t\t\t\td[prefsum] = d[prefsum]+1\n\n\t\treturn ans", "slug": "subarray-sum-equals-k", "post_title": "[ Python ] \u2705\u2705 Simple Python Solution Using PrefixSum and Dictionary \ud83d\udd25\u270c", "user": "ASHOK_KUMAR_MEGHVANSHI", "upvotes": 192, "views": 26200, "problem_title": "subarray sum equals k", "number": 560, "acceptance": 0.44, "difficulty": "Medium", "__index_level_0__": 9800, "question": "Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.\nA subarray is a contiguous non-empty sequence of elements within an array.\n Example 1:\nInput: nums = [1,1,1], k = 2\nOutput: 2\nExample 2:\nInput: nums = [1,2,3], k = 3\nOutput: 2\n Constraints:\n1 <= nums.length <= 2 * 104\n-1000 <= nums[i] <= 1000\n-107 <= k <= 107" }, { "post_href": "https://leetcode.com/problems/array-partition/discuss/390198/Algorithm-and-solution-in-python3", "python_solutions": "class Solution:\n def arrayPairSum(self, nums: List[int]) -> int:\n nums.sort()\n sum_ = 0\n for i in range(0,len(nums),2):\n sum_ += nums[i]\n return sum_\n\n# Time : 356 ms\n# Memory : 16.7 M", "slug": "array-partition", "post_title": "Algorithm and solution in python3", "user": "ramanaditya", "upvotes": 47, "views": 3200, "problem_title": "array partition", "number": 561, "acceptance": 0.767, "difficulty": "Easy", "__index_level_0__": 9846, "question": "Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum.\n Example 1:\nInput: nums = [1,4,3,2]\nOutput: 4\nExplanation: All possible pairings (ignoring the ordering of elements) are:\n1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\nSo the maximum possible sum is 4.\nExample 2:\nInput: nums = [6,2,6,5,1,2]\nOutput: 9\nExplanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n Constraints:\n1 <= n <= 104\nnums.length == 2 * n\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/binary-tree-tilt/discuss/1617385/Recursive-solution-Python", "python_solutions": "class Solution:\n def findTilt(self, root: Optional[TreeNode]) -> int:\n def rec(node):\n nonlocal res\n if not node:\n return 0\n left_sum = rec(node.left)\n right_sum = rec(node.right)\n res += abs(left_sum - right_sum)\n \n return left_sum + node.val + right_sum\n \n res = 0\n rec(root)\n return res", "slug": "binary-tree-tilt", "post_title": "Recursive solution Python", "user": "kryuki", "upvotes": 3, "views": 192, "problem_title": "binary tree tilt", "number": 563, "acceptance": 0.595, "difficulty": "Easy", "__index_level_0__": 9877, "question": "Given the root of a binary tree, return the sum of every tree node's tilt.\nThe tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.\n Example 1:\nInput: root = [1,2,3]\nOutput: 1\nExplanation: \nTilt of node 2 : |0-0| = 0 (no children)\nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 1 : |2-3| = 1 (left subtree is just left child, so sum is 2; right subtree is just right child, so sum is 3)\nSum of every tilt : 0 + 0 + 1 = 1\nExample 2:\nInput: root = [4,2,9,3,5,null,7]\nOutput: 15\nExplanation: \nTilt of node 3 : |0-0| = 0 (no children)\nTilt of node 5 : |0-0| = 0 (no children)\nTilt of node 7 : |0-0| = 0 (no children)\nTilt of node 2 : |3-5| = 2 (left subtree is just left child, so sum is 3; right subtree is just right child, so sum is 5)\nTilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\nTilt of node 4 : |(3+5+2)-(9+7)| = |10-16| = 6 (left subtree values are 3, 5, and 2, which sums to 10; right subtree values are 9 and 7, which sums to 16)\nSum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15\nExample 3:\nInput: root = [21,7,14,1,1,2,2,3,3]\nOutput: 9\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/find-the-closest-palindrome/discuss/2581120/Only-5-Cases-to-Consider%3A-Concise-implementation-in-Python-with-Full-Explanation", "python_solutions": "class Solution:\n def find_next_palindrome(self, n, additive):\n l = len(n)\n if l == 0:\n return 0\n first_half = str(int(n[:l // 2 + l % 2]) + additive)\n return int(first_half + first_half[(-1 - l%2)::-1])\n \n def nearestPalindromic(self, n: str) -> str:\n m = int(n)\n candidates = [self.find_next_palindrome(n, additive) for additive in range(-1, 2)] # Cases 1, 2, and 3\n candidates.append(self.find_next_palindrome(\"9\"*(len(n)-1), 0)) # Case 4\n candidates.append(self.find_next_palindrome(\"1\" + \"0\"*len(n), 0)) # Case 5\n\n ans = None\n for t in candidates:\n if t == m:\n continue\n if ans is None or abs(ans - m) > abs(t - m) or (abs(ans - m) == abs(t - m) and t < m):\n ans = t\n return str(ans)", "slug": "find-the-closest-palindrome", "post_title": "Only 5 Cases to Consider: Concise implementation in Python with Full Explanation", "user": "metaphysicalist", "upvotes": 3, "views": 269, "problem_title": "find the closest palindrome", "number": 564, "acceptance": 0.22, "difficulty": "Hard", "__index_level_0__": 9890, "question": "Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.\nThe closest is defined as the absolute difference minimized between two integers.\n Example 1:\nInput: n = \"123\"\nOutput: \"121\"\nExample 2:\nInput: n = \"1\"\nOutput: \"0\"\nExplanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.\n Constraints:\n1 <= n.length <= 18\nn consists of only digits.\nn does not have leading zeros.\nn is representing an integer in the range [1, 1018 - 1]." }, { "post_href": "https://leetcode.com/problems/array-nesting/discuss/1438213/CLEAN-and-SHORT-PYTHON-O(N)-TIME-O(N)-SPACE", "python_solutions": "class Solution:\n def arrayNesting(self, nums: List[int]) -> int:\n res, l = 0, len(nums)\n globalSet = set()\n for k in range(l):\n if k not in globalSet:\n currLength, currSet, val = 0, set(), k\n while True:\n if nums[val] in currSet: break\n currSet.add(nums[val])\n globalSet.add(nums[val])\n currLength, val = currLength + 1, nums[val]\n res = max(res, currLength) \n return res", "slug": "array-nesting", "post_title": "CLEAN & SHORT PYTHON, O(N) TIME, O(N) SPACE", "user": "kushagrabainsla", "upvotes": 6, "views": 442, "problem_title": "array nesting", "number": 565, "acceptance": 0.565, "difficulty": "Medium", "__index_level_0__": 9894, "question": "You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].\nYou should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:\nThe first element in s[k] starts with the selection of the element nums[k] of index = k.\nThe next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.\nWe stop adding right before a duplicate element occurs in s[k].\nReturn the longest length of a set s[k].\n Example 1:\nInput: nums = [5,4,0,3,1,6,2]\nOutput: 4\nExplanation: \nnums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\nOne of the longest sets s[k]:\ns[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}\nExample 2:\nInput: nums = [0,1,2]\nOutput: 1\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] < nums.length\nAll the values of nums are unique." }, { "post_href": "https://leetcode.com/problems/reshape-the-matrix/discuss/2046840/Python-Intuitive-%2B-Direct-for-Beginners-with-Illustrations", "python_solutions": "class Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n flatten = []\n new_mat = []\n for row in mat:\n for num in row:\n flatten.append(num)\n \n if r * c != len(flatten): # when given parameters is NOT possible and legal\n return mat\n else:\n for row_index in range(r):\n new_mat.append(flatten[row_index * c : row_index * c + c])\n return new_mat", "slug": "reshape-the-matrix", "post_title": "[Python] Intuitive + Direct for Beginners with Illustrations", "user": "ziaiz-zythoniz", "upvotes": 45, "views": 1100, "problem_title": "reshape the matrix", "number": 566, "acceptance": 0.627, "difficulty": "Easy", "__index_level_0__": 9912, "question": "In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.\nYou are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.\nThe reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.\nIf the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.\n Example 1:\nInput: mat = [[1,2],[3,4]], r = 1, c = 4\nOutput: [[1,2,3,4]]\nExample 2:\nInput: mat = [[1,2],[3,4]], r = 2, c = 4\nOutput: [[1,2],[3,4]]\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 100\n-1000 <= mat[i][j] <= 1000\n1 <= r, c <= 300" }, { "post_href": "https://leetcode.com/problems/permutation-in-string/discuss/1476884/Python-Sliding-Window-and-Dictionary.-Easy-to-understand", "python_solutions": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n window = len(s1)\n s1_c = Counter(s1)\n \n for i in range(len(s2)-window+1):\n s2_c = Counter(s2[i:i+window])\n if s2_c == s1_c:\n return True\n \n return False", "slug": "permutation-in-string", "post_title": "Python Sliding Window and Dictionary. Easy to understand", "user": "ParthitPatel", "upvotes": 29, "views": 3000, "problem_title": "permutation in string", "number": 567, "acceptance": 0.437, "difficulty": "Medium", "__index_level_0__": 9964, "question": "Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.\nIn other words, return true if one of s1's permutations is the substring of s2.\n Example 1:\nInput: s1 = \"ab\", s2 = \"eidbaooo\"\nOutput: true\nExplanation: s2 contains one permutation of s1 (\"ba\").\nExample 2:\nInput: s1 = \"ab\", s2 = \"eidboaoo\"\nOutput: false\n Constraints:\n1 <= s1.length, s2.length <= 104\ns1 and s2 consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/subtree-of-another-tree/discuss/265239/Python-Easy-to-Understand", "python_solutions": "class Solution:\n def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:\n if not s: \n return False\n if self.isSameTree(s, t): \n return True\n return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)\n\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n if p and q:\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n return p is q", "slug": "subtree-of-another-tree", "post_title": "Python Easy to Understand", "user": "ccparamecium", "upvotes": 83, "views": 13100, "problem_title": "subtree of another tree", "number": 572, "acceptance": 0.46, "difficulty": "Easy", "__index_level_0__": 10009, "question": "Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise.\nA subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.\n Example 1:\nInput: root = [3,4,5,1,2], subRoot = [4,1,2]\nOutput: true\nExample 2:\nInput: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\nOutput: false\n Constraints:\nThe number of nodes in the root tree is in the range [1, 2000].\nThe number of nodes in the subRoot tree is in the range [1, 1000].\n-104 <= root.val <= 104\n-104 <= subRoot.val <= 104" }, { "post_href": "https://leetcode.com/problems/distribute-candies/discuss/1088016/Python.-One-liner-Easy-understanding-solution.", "python_solutions": "class Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n return min(len(candyType) //2, len(set(candyType)))", "slug": "distribute-candies", "post_title": "Python. One-liner Easy-understanding solution.", "user": "m-d-f", "upvotes": 2, "views": 224, "problem_title": "distribute candies", "number": 575, "acceptance": 0.6609999999999999, "difficulty": "Easy", "__index_level_0__": 10043, "question": "Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.\nThe doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor's advice.\nGiven the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.\n Example 1:\nInput: candyType = [1,1,2,2,3,3]\nOutput: 3\nExplanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.\nExample 2:\nInput: candyType = [1,1,2,3]\nOutput: 2\nExplanation: Alice can only eat 4 / 2 = 2 candies. Whether she eats types [1,2], [1,3], or [2,3], she still can only eat 2 different types.\nExample 3:\nInput: candyType = [6,6,6,6]\nOutput: 1\nExplanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.\n Constraints:\nn == candyType.length\n2 <= n <= 104\nn is even.\n-105 <= candyType[i] <= 105" }, { "post_href": "https://leetcode.com/problems/out-of-boundary-paths/discuss/2288190/Python3-oror-recursion-one-grid-w-explanation-oror-TM%3A-8949", "python_solutions": "class Solution: # The plan is to accrete the number of paths from the starting cell, which\n # is the sum of (a) the number of adjacent positions that are off the grid\n # and (b) the number of paths from the adjacent cells in the grid within \n # maxMove steps. We determine (b) recursively.\n\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n\n @lru_cache(None) # <-- Many cells are revisited so we cache the previous calls\n def dp (x,y,steps = maxMove):\n if x not in range(m) or y not in range(n): # <-- Moved off the grid so increment the tally\n return 1\n if not steps: # <-- Ran out of the maxMove steps\n return 0\n\n ans, dx, dy = 0, 1, 0\n for _ in range(4):\n ans+= dp(x+dx, y+dy, steps-1) # <-- visit the adjacent cells\n dx, dy = dy,-dx # <-- iterates thru the directions:\n\t\t\t\t # south => east => north => west \n\n return ans \n\n return dp (startRow, startColumn)%1000000007\n\t\t\n\t\t# Thanks to XixiangLiu for fixing a number of my errors in the original post.", "slug": "out-of-boundary-paths", "post_title": "Python3 || recursion , one grid w/ explanation || T/M: 89%/49%", "user": "warrenruud", "upvotes": 5, "views": 371, "problem_title": "out of boundary paths", "number": 576, "acceptance": 0.4429999999999999, "difficulty": "Medium", "__index_level_0__": 10073, "question": "There is an m x n grid with a ball. The ball is initially at the position [startRow, startColumn]. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply at most maxMove moves to the ball.\nGiven the five integers m, n, maxMove, startRow, startColumn, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it modulo 109 + 7.\n Example 1:\nInput: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\nOutput: 6\nExample 2:\nInput: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\nOutput: 12\n Constraints:\n1 <= m, n <= 50\n0 <= maxMove <= 50\n0 <= startRow < m\n0 <= startColumn < n" }, { "post_href": "https://leetcode.com/problems/shortest-unsorted-continuous-subarray/discuss/2002965/Python-Simple-Two-Approaches", "python_solutions": "class Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n sorted_nums = sorted(nums)\n \n l, u = len(nums) - 1,0\n for i in range(len(nums)):\n if nums[i]!=sorted_nums[i]:\n l=min(l, i)\n u=max(u, i)\n \n \n return 0 if l>=u else u-l+1", "slug": "shortest-unsorted-continuous-subarray", "post_title": "Python Simple Two Approaches", "user": "constantine786", "upvotes": 11, "views": 828, "problem_title": "shortest unsorted continuous subarray", "number": 581, "acceptance": 0.363, "difficulty": "Medium", "__index_level_0__": 10093, "question": "Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.\nReturn the shortest such subarray and output its length.\n Example 1:\nInput: nums = [2,6,4,8,10,9,15]\nOutput: 5\nExplanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 0\nExample 3:\nInput: nums = [1]\nOutput: 0\n Constraints:\n1 <= nums.length <= 104\n-105 <= nums[i] <= 105\n Follow up: Can you solve it in O(n) time complexity?" }, { "post_href": "https://leetcode.com/problems/delete-operation-for-two-strings/discuss/2148966/Python-DP-2-approaches-using-LCS", "python_solutions": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n m,n=len(word1),len(word2)\n @cache\n def lcs(i, j): # find longest common subsequence\n if i==m or j==n:\n return 0 \n return 1 + lcs(i+1, j+1) if word1[i]==word2[j] else max(lcs(i+1, j), lcs(i,j+1)) \n # subtract the lcs length from both the strings \n # the difference is the number of characters that has to deleted\n return m + n - 2*lcs(0,0)", "slug": "delete-operation-for-two-strings", "post_title": "Python DP 2 approaches using LCS \u2705", "user": "constantine786", "upvotes": 49, "views": 3000, "problem_title": "delete operation for two strings", "number": 583, "acceptance": 0.594, "difficulty": "Medium", "__index_level_0__": 10142, "question": "Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.\nIn one step, you can delete exactly one character in either string.\n Example 1:\nInput: word1 = \"sea\", word2 = \"eat\"\nOutput: 2\nExplanation: You need one step to make \"sea\" to \"ea\" and another step to make \"eat\" to \"ea\".\nExample 2:\nInput: word1 = \"leetcode\", word2 = \"etco\"\nOutput: 4\n Constraints:\n1 <= word1.length, word2.length <= 500\nword1 and word2 consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/erect-the-fence/discuss/864619/Python-Solution-with-Monotone-Chain-Algorithm", "python_solutions": "class Solution:\n def outerTrees(self, points: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Use Monotone Chain algorithm.\n \"\"\"\n def is_clockwise(\n p0: List[int], p1: List[int], p2: List[int]) -> bool:\n \"\"\"\n Determine the orientation the slope p0p2 is on the clockwise\n orientation of the slope p0p1.\n \"\"\"\n return (p1[1] - p0[1]) * (p2[0] - p0[0]) > \\\n (p2[1] - p0[1]) * (p1[0] - p0[0])\n\n sortedPoints = sorted(points)\n\n # Scan from left to right to generate the lower part of the hull.\n hull = []\n for p in sortedPoints:\n while len(hull) > 1 and is_clockwise(hull[-2], hull[-1], p):\n hull.pop()\n\n hull.append(p)\n\n if len(hull) == len(points): # All the points are on the perimeter now.\n return hull\n\n # Scan from right to left to generate the higher part of the hull.\n # Remove the last point first as it will be scanned again.\n hull.pop()\n for p in reversed(sortedPoints):\n while len(hull) > 1 and is_clockwise(hull[-2], hull[-1], p):\n hull.pop()\n\n hull.append(p)\n\n # Pop the first point as it is already added to hull when processing\n # the lower part.\n hull.pop()\n\n return hull", "slug": "erect-the-fence", "post_title": "Python Solution with Monotone Chain Algorithm", "user": "eroneko", "upvotes": 4, "views": 542, "problem_title": "erect the fence", "number": 587, "acceptance": 0.523, "difficulty": "Hard", "__index_level_0__": 10180, "question": "You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.\nFence 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.\nReturn the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.\n Example 1:\nInput: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\nOutput: [[1,1],[2,0],[4,2],[3,3],[2,4]]\nExplanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.\nExample 2:\nInput: trees = [[1,2],[2,2],[4,2]]\nOutput: [[4,2],[2,2],[1,2]]\nExplanation: The fence forms a line that passes through all the trees.\n Constraints:\n1 <= trees.length <= 3000\ntrees[i].length == 2\n0 <= xi, yi <= 100\nAll the given positions are unique." }, { "post_href": "https://leetcode.com/problems/n-ary-tree-preorder-traversal/discuss/2496970/Very-Easy-oror-100-oror-Fully-Explained-oror-Java-C%2B%2B-Python-Python3-oror-Iterative-and-Recursive(DFS)", "python_solutions": "class Solution(object):\n def preorder(self, root):\n # To store the output result...\n output = []\n self.traverse(root, output)\n return output\n def traverse(self, root, output):\n # Base case: If root is none...\n if root is None: return\n # Append the value of the root node to the output...\n output.append(root.val)\n # Recursively traverse each node in the children array...\n for child in root.children:\n self.traverse(child, output)", "slug": "n-ary-tree-preorder-traversal", "post_title": "Very Easy || 100% || Fully Explained || Java, C++, Python, Python3 || Iterative & Recursive(DFS)", "user": "PratikSen07", "upvotes": 28, "views": 1600, "problem_title": "n ary tree preorder traversal", "number": 589, "acceptance": 0.762, "difficulty": "Easy", "__index_level_0__": 10201, "question": "Given the root of an n-ary tree, return the preorder traversal of its nodes' values.\nNary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)\n Example 1:\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [1,3,5,6,2,4]\nExample 2:\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n0 <= Node.val <= 104\nThe height of the n-ary tree is less than or equal to 1000.\n Follow up: Recursive solution is trivial, could you do it iteratively?" }, { "post_href": "https://leetcode.com/problems/n-ary-tree-postorder-traversal/discuss/355782/Python3-recursive-and-iterative-implementation", "python_solutions": "class Solution:\n def postorder(self, root: 'Node') -> List[int]:\n \n def dfs(node):\n \"\"\"Populate ans via post-order traversal.\"\"\"\n if not node: return \n for child in node.children: dfs(child)\n ans.append(node.val)\n \n ans = []\n dfs(root)\n return ans", "slug": "n-ary-tree-postorder-traversal", "post_title": "[Python3] recursive & iterative implementation", "user": "ye15", "upvotes": 2, "views": 129, "problem_title": "n ary tree postorder traversal", "number": 590, "acceptance": 0.772, "difficulty": "Easy", "__index_level_0__": 10232, "question": "Given the root of an n-ary tree, return the postorder traversal of its nodes' values.\nNary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)\n Example 1:\nInput: root = [1,null,3,2,4,null,5,6]\nOutput: [5,6,3,2,4,1]\nExample 2:\nInput: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\nOutput: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n0 <= Node.val <= 104\nThe height of the n-ary tree is less than or equal to 1000.\n Follow up: Recursive solution is trivial, could you do it iteratively?" }, { "post_href": "https://leetcode.com/problems/tag-validator/discuss/449403/Two-Python-Solution%3A(1)-linear-paring-with-stack(2)BNF-parsing-with-pyparsing", "python_solutions": "class Solution:\n def isValid(self, code: str) -> bool:\n if code[0] != '<' or code[-1] != '>': return False\n i, n = 0, len(code)\n stk = []\n while i < n:\n if code[i] == '<':\n if i != 0 and code[i: i + 9] == '': j += 1\n if code[j: j + 3] == ']]>': i = j + 3\n else: return False\n else:\n start = i\n isend = False\n i += 1\n if i >= n: return False\n if code[i] == r'/':\n isend = True\n i += 1\n if i >= n: return False\n tag = ''\n while i < n and code[i] != '>':\n if not code[i].isupper(): return False\n tag += code[i]\n i += 1\n if i >= n or len(tag) == 0 or len(tag) > 9: return False\n if isend:\n if not stk or stk[-1] != tag: return False\n stk.pop(-1)\n else:\n if start != 0 and not stk: return False\n stk.append(tag)\n i += 1\n else:\n if not stk: return False\n while i < n and code[i] != '<': i += 1\n return not stk", "slug": "tag-validator", "post_title": "Two Python Solution:(1) linear paring with stack;(2)BNF parsing with pyparsing", "user": "cava", "upvotes": 1, "views": 402, "problem_title": "tag validator", "number": 591, "acceptance": 0.371, "difficulty": "Hard", "__index_level_0__": 10250, "question": "Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.\nA code snippet is valid if all the following rules hold:\nThe code must be wrapped in a valid closed tag. Otherwise, the code is invalid.\nA closed tag (not necessarily valid) has exactly the following format : TAG_CONTENT. Among them, is the start tag, and is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.\nA valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.\nA 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.\nA 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.\nA < is unmatched if you cannot find a subsequent >. And when you find a < or should be parsed as TAG_NAME (not necessarily valid).\nThe cdata has the following format : . The range of CDATA_CONTENT is defined as the characters between .\nCDATA_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 Example 1:\nInput: code = \"
This is the first line ]]>
\"\nOutput: true\nExplanation: \nThe code is wrapped in a closed tag :
and
. \nThe TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \nAlthough CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\nSo TAG_CONTENT is valid, and then the code is valid. Thus return true.\nExample 2:\nInput: code = \"
>> ![cdata[]] ]>]]>]]>>]
\"\nOutput: true\nExplanation:\nWe first separate the code into : start_tag|tag_content|end_tag.\nstart_tag -> \"
\"\nend_tag -> \"
\"\ntag_content could also be separated into : text1|cdata|text2.\ntext1 -> \">> ![cdata[]] \"\ncdata -> \"]>]]>\", where the CDATA_CONTENT is \"
]>\"\ntext2 -> \"]]>>]\"\nThe reason why start_tag is NOT \"
>>\" is because of the rule 6.\nThe reason why cdata is NOT \"]>]]>]]>\" is because of the rule 7.\nExample 3:\nInput: code = \" \"\nOutput: false\nExplanation: Unbalanced. If \"\" is closed, then \"\" must be unmatched, and vice versa.\n Constraints:\n1 <= code.length <= 500\ncode consists of English letters, digits, '<', '>', '/', '!', '[', ']', '.', and ' '." }, { "post_href": "https://leetcode.com/problems/fraction-addition-and-subtraction/discuss/1128722/Python-Simple-Parsing-with-example", "python_solutions": "class Solution:\n def fractionAddition(self, exp: str) -> str:\n \n if not exp:\n return \"0/1\"\n \n if exp[0] != '-':\n exp = '+' + exp\n \n # Parse the expression to get the numerator and denominator of each fraction\n num = []\n den = []\n pos = True\n i = 0\n while i < len(exp):\n # Check sign\n pos = True if exp[i] == '+' else False\n \n # Get numerator\n i += 1\n n = 0\n while exp[i].isdigit():\n n = n*10 + int(exp[i])\n i += 1\n num.append(n if pos else -n)\n \n # Get denominator\n i += 1\n d = 0\n while i < len(exp) and exp[i].isdigit():\n d = d*10 + int(exp[i])\n i += 1\n den.append(d)\n \n # Multiply the numerator of all fractions so that they have the same denominator\n denominator = functools.reduce(lambda x, y: x*y, den)\n for i,(n,d) in enumerate(zip(num, den)):\n num[i] = n * denominator // d\n \n # Sum up all of the numerator values\n numerator = sum(num)\n \n # Divide numerator and denominator by the greatest common divisor (gcd)\n g = math.gcd(numerator, denominator)\n numerator = numerator // g\n denominator = denominator // g\n \n return f\"{numerator}/{denominator}\"", "slug": "fraction-addition-and-subtraction", "post_title": "[Python] Simple Parsing - with example", "user": "rowe1227", "upvotes": 6, "views": 918, "problem_title": "fraction addition and subtraction", "number": 592, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 10252, "question": "Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.\nThe final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.\n Example 1:\nInput: expression = \"-1/2+1/2\"\nOutput: \"0/1\"\nExample 2:\nInput: expression = \"-1/2+1/2+1/3\"\nOutput: \"1/3\"\nExample 3:\nInput: expression = \"1/3-1/2\"\nOutput: \"-1/6\"\n Constraints:\nThe input string only contains '0' to '9', '/', '+' and '-'. So does the output.\nEach fraction (input and output) has the format \u00b1numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.\nThe input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1, 10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.\nThe number of given fractions will be in the range [1, 10].\nThe numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int." }, { "post_href": "https://leetcode.com/problems/valid-square/discuss/931866/python-easy-to-understand-3-lines-code-beats-95", "python_solutions": "class Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n def dist(point1,point2):\n return (point1[0]-point2[0])**2+(point1[1]-point2[1])**2\n \n D=[\n dist(p1,p2),\n dist(p1,p3),\n dist(p1,p4),\n dist(p2,p3),\n dist(p2,p4),\n dist(p3,p4)\n ]\n D.sort()\n return 0 int:\n\t\ttmp = Counter(nums)\n\t\tkeys = tmp.keys()\n\t\tmax = 0\n\t\tfor num in keys:\n\t\t\tif num - 1 in keys:\n\t\t\t\tif tmp[num - 1] + tmp[num] > max:\n\t\t\t\t\tmax = tmp[num - 1] + tmp[num]\n\t\treturn max", "slug": "longest-harmonious-subsequence", "post_title": "Python. O(n), Cool, easy & clear solution.", "user": "m-d-f", "upvotes": 6, "views": 494, "problem_title": "longest harmonious subsequence", "number": 594, "acceptance": 0.532, "difficulty": "Easy", "__index_level_0__": 10275, "question": "We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.\nGiven an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.\nA subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.\n Example 1:\nInput: nums = [1,3,2,2,5,2,3,7]\nOutput: 5\nExplanation: The longest harmonious subsequence is [3,2,2,2,3].\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 2\nExample 3:\nInput: nums = [1,1,1,1]\nOutput: 0\n Constraints:\n1 <= nums.length <= 2 * 104\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/range-addition-ii/discuss/1434604/C-or-C%2B%2B-or-Python-or-Java-or-C-or-JavaScript-or-Go-Same-Simple-Solution", "python_solutions": "class Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n min_row = m\n min_col = n\n for i in range(len(ops)):\n min_row=min(min_row, ops[i][0])\n min_col=min(min_col, ops[i][1])\n return min_row*min_col", "slug": "range-addition-ii", "post_title": "[ C | C++ | Python | Java | C# | JavaScript | Go ] Same Simple Solution", "user": "HadaEn", "upvotes": 23, "views": 2000, "problem_title": "range addition ii", "number": 598, "acceptance": 0.551, "difficulty": "Easy", "__index_level_0__": 10293, "question": "You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi.\nCount and return the number of maximum integers in the matrix after performing all the operations.\n Example 1:\nInput: m = 3, n = 3, ops = [[2,2],[3,3]]\nOutput: 4\nExplanation: The maximum integer in M is 2, and there are four of it in M. So return 4.\nExample 2:\nInput: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]]\nOutput: 4\nExample 3:\nInput: m = 3, n = 3, ops = []\nOutput: 9\n Constraints:\n1 <= m, n <= 4 * 104\n0 <= ops.length <= 104\nops[i].length == 2\n1 <= ai <= m\n1 <= bi <= n" }, { "post_href": "https://leetcode.com/problems/minimum-index-sum-of-two-lists/discuss/1382036/Easy-Python-Solution-(Memory-Usage-less-than-97)", "python_solutions": "class Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n d = {}\n d2 = {}\n min_ = 5000\n ret = []\n\n for i in range(len(list1)):\n d[list1[i]] = i+1\n\n for i in range(len(list2)):\n a = d.get(list2[i], 0)\n if a:\n b = a+i-1\n if b <= min_:\n min_ = b\n d2[list2[i]] = b\n\n for k,v in d2.items():\n if v <= min_:\n ret.append(k)\n\n return ret", "slug": "minimum-index-sum-of-two-lists", "post_title": "Easy Python Solution (Memory Usage less than 97%)", "user": "the_sky_high", "upvotes": 3, "views": 454, "problem_title": "minimum index sum of two lists", "number": 599, "acceptance": 0.529, "difficulty": "Easy", "__index_level_0__": 10308, "question": "Given two arrays of strings list1 and list2, find the common strings with the least index sum.\nA common string is a string that appeared in both list1 and list2.\nA common string with the least index sum is a common string such that if it appeared at list1[i] and list2[j] then i + j should be the minimum value among all the other common strings.\nReturn all the common strings with the least index sum. Return the answer in any order.\n Example 1:\nInput: list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"Piatti\",\"The Grill at Torrey Pines\",\"Hungry Hunter Steakhouse\",\"Shogun\"]\nOutput: [\"Shogun\"]\nExplanation: The only common string is \"Shogun\".\nExample 2:\nInput: list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"KFC\",\"Shogun\",\"Burger King\"]\nOutput: [\"Shogun\"]\nExplanation: The common string with the least index sum is \"Shogun\" with index sum = (0 + 1) = 1.\nExample 3:\nInput: list1 = [\"happy\",\"sad\",\"good\"], list2 = [\"sad\",\"happy\",\"good\"]\nOutput: [\"sad\",\"happy\"]\nExplanation: There are three common strings:\n\"happy\" with index sum = (0 + 1) = 1.\n\"sad\" with index sum = (1 + 0) = 1.\n\"good\" with index sum = (2 + 2) = 4.\nThe strings with the least index sum are \"sad\" and \"happy\".\n Constraints:\n1 <= list1.length, list2.length <= 1000\n1 <= list1[i].length, list2[i].length <= 30\nlist1[i] and list2[i] consist of spaces ' ' and English letters.\nAll the strings of list1 are unique.\nAll the strings of list2 are unique.\nThere is at least a common string between list1 and list2." }, { "post_href": "https://leetcode.com/problems/non-negative-integers-without-consecutive-ones/discuss/1361794/Python3-Official-Solution-Explained-Simply-with-Diagrams", "python_solutions": "class Solution:\n def findIntegers(self, n: int) -> int:\n # f stores the fibonacci numbers\n f = [1, 2]\n for i in range(2, 30):\n f.append(f[-1]+f[-2])\n \n # last_seen tells us if there was a one right before. \n # If that is the case, we are done then and there!\n # ans is the answer\n ans, last_seen = 0, 0\n for i in reversed(range(30)):\n if (1 << i) & n: # is the ith bit set?\n ans += f[i]\n if last_seen: \n ans -= 1\n break\n last_seen = 1\n else:\n last_seen = 0\n return ans+1", "slug": "non-negative-integers-without-consecutive-ones", "post_title": "[Python3] Official Solution Explained Simply with Diagrams", "user": "chaudhary1337", "upvotes": 100, "views": 2500, "problem_title": "non negative integers without consecutive ones", "number": 600, "acceptance": 0.39, "difficulty": "Hard", "__index_level_0__": 10337, "question": "Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.\n Example 1:\nInput: n = 5\nOutput: 5\nExplanation:\nHere are the non-negative integers <= 5 with their corresponding binary representations:\n0 : 0\n1 : 1\n2 : 10\n3 : 11\n4 : 100\n5 : 101\nAmong them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \nExample 2:\nInput: n = 1\nOutput: 2\nExample 3:\nInput: n = 2\nOutput: 3\n Constraints:\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/can-place-flowers/discuss/380474/Three-Solutions-in-Python-3-(beats-~100)", "python_solutions": "class Solution:\n def canPlaceFlowers(self, f: List[int], n: int) -> bool:\n L, i, c, f = len(f)-2, -2, 0, f + [0]\n while i < L:\n \ti += 2\n \tif f[i] == 1: continue\n \tif f[i+1] == 0: c += 1\n \telse: i += 1\n return n <= c\n\t\t\n\t\t\n\t\t\n\t\t\nclass Solution:\n def canPlaceFlowers(self, f: List[int], n: int) -> bool:\n \tL, f, i, c = len(f), [0] + f + [0], 1, 0\n \twhile i <= L:\n \t\tif f[i-1:i+2] == [0,0,0]: c, i = c + 1, i + 1\n \t\ti += 1\n \treturn n <= c\n\t\t\n\t\t\n\t\t\n\t\t\nclass Solution:\n def canPlaceFlowers(self, f: List[int], n: int) -> bool:\n \tL, f, s, c = len(f), f + [0,1], 0, 1\n \tfor i in range(L+2):\n \t\tif f[i] == 1: s, c = s + max(0,c-1)//2, 0\n \t\telse: c += 1\n \treturn n <= s\n\t\t\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "can-place-flowers", "post_title": "Three Solutions in Python 3 (beats ~100%)", "user": "junaidmansuri", "upvotes": 7, "views": 1800, "problem_title": "can place flowers", "number": 605, "acceptance": 0.3289999999999999, "difficulty": "Easy", "__index_level_0__": 10341, "question": "You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in adjacent plots.\nGiven an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return true if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule and false otherwise.\n Example 1:\nInput: flowerbed = [1,0,0,0,1], n = 1\nOutput: true\nExample 2:\nInput: flowerbed = [1,0,0,0,1], n = 2\nOutput: false\n Constraints:\n1 <= flowerbed.length <= 2 * 104\nflowerbed[i] is 0 or 1.\nThere are no two adjacent flowers in flowerbed.\n0 <= n <= flowerbed.length" }, { "post_href": "https://leetcode.com/problems/construct-string-from-binary-tree/discuss/1112030/Python-recursive-solution-with-string-builder", "python_solutions": "class Solution:\n def tree2str(self, t: TreeNode) -> str:\n sb = [] # init string builder\n \n # helper function to create result\n def helper(node: TreeNode) -> None: \n if not node:\n return\n \n sb.append(str(node.val))\n \n if not node.left and not node.right:\n # leaf node, stop processing\n return\n \n sb.append('(') # always wrap left node with parenthesis when right node exist\n helper(node.left) # process left node recursively \n sb.append(')') \n\n if node.right: # adding parenthesis for the right node only if it is not empty\n sb.append('(')\n helper(node.right)\n sb.append(')') \n \n helper(t)\n\n return ''.join(sb)", "slug": "construct-string-from-binary-tree", "post_title": "Python recursive solution with string builder", "user": "ignat-s", "upvotes": 15, "views": 1200, "problem_title": "construct string from binary tree", "number": 606, "acceptance": 0.636, "difficulty": "Easy", "__index_level_0__": 10378, "question": "Given the root node of a binary tree, your task is to create a string representation of the tree following a specific set of formatting rules. The representation should be based on a preorder traversal of the binary tree and must adhere to the following guidelines:\nNode Representation: Each node in the tree should be represented by its integer value.\nParentheses for Children: If a node has at least one child (either left or right), its children should be represented inside parentheses. Specifically:\nIf a node has a left child, the value of the left child should be enclosed in parentheses immediately following the node's value.\nIf a node has a right child, the value of the right child should also be enclosed in parentheses. The parentheses for the right child should follow those of the left child.\nOmitting Empty Parentheses: Any empty parentheses pairs (i.e., ()) should be omitted from the final string representation of the tree, with one specific exception: when a node has a right child but no left child. In such cases, you must include an empty pair of parentheses to indicate the absence of the left child. This ensures that the one-to-one mapping between the string representation and the original binary tree structure is maintained.\nIn summary, empty parentheses pairs should be omitted when a node has only a left child or no children. However, when a node has a right child but no left child, an empty pair of parentheses must precede the representation of the right child to reflect the tree's structure accurately.\n Example 1:\nInput: root = [1,2,3,4]\nOutput: \"1(2(4))(3)\"\nExplanation: Originally, it needs to be \"1(2(4)())(3()())\", but you need to omit all the empty parenthesis pairs. And it will be \"1(2(4))(3)\".\nExample 2:\nInput: root = [1,2,3,null,4]\nOutput: \"1(2()(4))(3)\"\nExplanation: Almost the same as the first example, except the () after 2 is necessary to indicate the absence of a left child for 2 and the presence of a right child.\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-1000 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/find-duplicate-file-in-system/discuss/2595019/LeetCode-The-Hard-Way-Explained-Line-By-Line", "python_solutions": "class Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n m = defaultdict(list)\n for p in paths:\n # 1. split the string by ' '\n path = p.split()\n # the first string is the directory path\n # the rest of them are just file names with content\n directoryPath, rest = path[0], path[1:]\n # for each file names with content\n for f in rest:\n # we retrieve the file name and the file content\n fileName, fileContent = f.split('(')[0], f.split('(')[1][:-1]\n # then group {directoryPath}/{fileName} by file content\n m[fileContent].append(\"{}/{}\".format(directoryPath, fileName))\n # return the file list only when the size is greater than 1, meaning they are duplicate files\n return [m[k] for k in m.keys() if len(m[k]) > 1]", "slug": "find-duplicate-file-in-system", "post_title": "\ud83d\udd25 [LeetCode The Hard Way] \ud83d\udd25 Explained Line By Line", "user": "wingkwong", "upvotes": 28, "views": 1200, "problem_title": "find duplicate file in system", "number": 609, "acceptance": 0.6779999999999999, "difficulty": "Medium", "__index_level_0__": 10417, "question": "Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.\nA group of duplicate files consists of at least two files that have the same content.\nA single directory info string in the input list has the following format:\n\"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)\"\nIt means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory \"root/d1/d2/.../dm\". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.\nThe output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:\n\"directory_path/file_name.txt\"\n Example 1:\nInput: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\nOutput: [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\nExample 2:\nInput: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\nOutput: [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n Constraints:\n1 <= paths.length <= 2 * 104\n1 <= paths[i].length <= 3000\n1 <= sum(paths[i].length) <= 5 * 105\npaths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.\nYou may assume no files or directories share the same name in the same directory.\nYou may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.\n Follow up:\nImagine you are given a real file system, how will you search files? DFS or BFS?\nIf the file content is very large (GB level), how will you modify your solution?\nIf you can only read the file by 1kb each time, how will you modify your solution?\nWhat is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?\nHow to make sure the duplicated files you find are not false positive?" }, { "post_href": "https://leetcode.com/problems/valid-triangle-number/discuss/884373/Python3-O(N2)-time-solution", "python_solutions": "class Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n nums.sort()\n ans = 0\n for i in range(len(nums)): \n lo, hi = 0, i-1\n while lo < hi: \n if nums[lo] + nums[hi] > nums[i]:\n ans += hi - lo \n hi -= 1\n else: lo += 1\n return ans", "slug": "valid-triangle-number", "post_title": "[Python3] O(N^2) time solution", "user": "ye15", "upvotes": 3, "views": 222, "problem_title": "valid triangle number", "number": 611, "acceptance": 0.504, "difficulty": "Medium", "__index_level_0__": 10449, "question": "Given an integer array nums, return the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.\n Example 1:\nInput: nums = [2,2,3,4]\nOutput: 3\nExplanation: Valid combinations are: \n2,3,4 (using the first 2)\n2,3,4 (using the second 2)\n2,2,3\nExample 2:\nInput: nums = [4,2,3,4]\nOutput: 4\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/merge-two-binary-trees/discuss/1342175/Elegant-Python-Iterative-and-Recursive-solutions", "python_solutions": "class Solution:\n def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:\n if not root1: return root2\n if not root2: return root1\n queue = deque([(root1, root2)])\n while queue:\n current_root1, current_root2 = queue.pop()\n if current_root1.left and current_root2.left: queue.append((current_root1.left, current_root2.left))\n elif not current_root1.left: current_root1.left = current_root2.left\n if current_root1.right and current_root2.right: queue.append((current_root1.right, current_root2.right))\n elif not current_root1.right: current_root1.right = current_root2.right\n current_root1.val += current_root2.val\n return root1", "slug": "merge-two-binary-trees", "post_title": "Elegant Python Iterative & Recursive solutions", "user": "soma28", "upvotes": 9, "views": 453, "problem_title": "merge two binary trees", "number": 617, "acceptance": 0.7859999999999999, "difficulty": "Easy", "__index_level_0__": 10460, "question": "You are given two binary trees root1 and root2.\nImagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.\nReturn the merged tree.\nNote: The merging process must start from the root nodes of both trees.\n Example 1:\nInput: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\nOutput: [3,4,5,5,4,null,7]\nExample 2:\nInput: root1 = [1], root2 = [1,2]\nOutput: [2,2]\n Constraints:\nThe number of nodes in both trees is in the range [0, 2000].\n-104 <= Node.val <= 104" }, { "post_href": "https://leetcode.com/problems/task-scheduler/discuss/2667200/Python-O(n)-time-count-it-directly", "python_solutions": "class Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n cnt = [0] * 26\n for i in tasks: cnt[ord(i) - ord('A')] += 1\n mx, mxcnt = max(cnt), 0\n for i in cnt: \n if i == mx: mxcnt += 1\n return max((mx - 1) * (n + 1) + mxcnt, len(tasks))", "slug": "task-scheduler", "post_title": "Python O(n) time, count it directly", "user": "alex391a", "upvotes": 10, "views": 1100, "problem_title": "task scheduler", "number": 621, "acceptance": 0.5579999999999999, "difficulty": "Medium", "__index_level_0__": 10490, "question": "You are given an array of CPU tasks, each represented by letters A to Z, and a cooling time, n. Each cycle or interval allows the completion of one task. Tasks can be completed in any order, but there's a constraint: identical tasks must be separated by at least n intervals due to cooling time.\nReturn the minimum number of intervals required to complete all tasks.\n Example 1:\nInput: tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2\nOutput: 8\nExplanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.\nAfter completing task A, you must wait two cycles before doing A again. The same applies to task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th cycle, you can do A again as 2 intervals have passed.\nExample 2:\nInput: tasks = [\"A\",\"C\",\"A\",\"B\",\"D\",\"B\"], n = 1\nOutput: 6\nExplanation: A possible sequence is: A -> B -> C -> D -> A -> B.\nWith a cooling interval of 1, you can repeat a task after just one other task.\nExample 3:\nInput: tasks = [\"A\",\"A\",\"A\", \"B\",\"B\",\"B\"], n = 3\nOutput: 10\nExplanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.\nThere are only two types of tasks, A and B, which need to be separated by 3 intervals. This leads to idling twice between repetitions of these tasks.\n Constraints:\n1 <= tasks.length <= 104\ntasks[i] is an uppercase English letter.\n0 <= n <= 100" }, { "post_href": "https://leetcode.com/problems/add-one-row-to-tree/discuss/1101104/Python.-Recursive.-Easy-understanding-solution", "python_solutions": "class Solution:\n def addOneRow(self, root: TreeNode, v: int, d: int, side = \"left\") -> TreeNode:\n if d == 1:\n res = TreeNode(v)\n setattr(res, side, root)\n return res\n if root:\n root.left = self.addOneRow(root.left, v, d - 1)\n root.right = self.addOneRow(root.right, v, d - 1, 'right')\n return root", "slug": "add-one-row-to-tree", "post_title": "Python. Recursive. Easy understanding solution", "user": "m-d-f", "upvotes": 13, "views": 772, "problem_title": "add one row to tree", "number": 623, "acceptance": 0.595, "difficulty": "Medium", "__index_level_0__": 10507, "question": "Given the root of a binary tree and two integers val and depth, add a row of nodes with value val at the given depth depth.\nNote that the root node is at depth 1.\nThe adding rule is:\nGiven the integer depth, for each not null tree node cur at the depth depth - 1, create two tree nodes with value val as cur's left subtree root and right subtree root.\ncur's original left subtree should be the left subtree of the new left subtree root.\ncur's original right subtree should be the right subtree of the new right subtree root.\nIf depth == 1 that means there is no depth depth - 1 at all, then create a tree node with value val as the new root of the whole original tree, and the original tree is the new root's left subtree.\n Example 1:\nInput: root = [4,2,6,3,1,5], val = 1, depth = 2\nOutput: [4,1,1,2,null,null,6,3,1,5]\nExample 2:\nInput: root = [4,2,null,3,1], val = 1, depth = 3\nOutput: [4,2,null,1,1,3,null,null,1]\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\nThe depth of the tree is in the range [1, 104].\n-100 <= Node.val <= 100\n-105 <= val <= 105\n1 <= depth <= the depth of tree + 1" }, { "post_href": "https://leetcode.com/problems/maximum-product-of-three-numbers/discuss/356715/Python3-O(N)-and-O(NlogN)-solutions", "python_solutions": "class Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n max1 = max2 = max3 = float(\"-inf\")\n min1 = min2 = float(\"inf\")\n \n for num in nums: \n if num > max1:\n max1, max2, max3 = num, max1, max2\n elif num > max2:\n max2, max3 = num, max2\n elif num > max3:\n max3 = num\n \n if num < min1:\n min1, min2 = num, min1\n elif num < min2:\n min2 = num\n \n return max(max2*max3, min1*min2) * max1", "slug": "maximum-product-of-three-numbers", "post_title": "[Python3] O(N) and O(NlogN) solutions", "user": "ye15", "upvotes": 7, "views": 677, "problem_title": "maximum product of three numbers", "number": 628, "acceptance": 0.4629999999999999, "difficulty": "Easy", "__index_level_0__": 10533, "question": "Given an integer array nums, find three numbers whose product is maximum and return the maximum product.\n Example 1:\nInput: nums = [1,2,3]\nOutput: 6\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 24\nExample 3:\nInput: nums = [-1,-2,-3]\nOutput: -6\n Constraints:\n3 <= nums.length <= 104\n-1000 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/k-inverse-pairs-array/discuss/2293304/Python3-oror-dp1D-array-10-lines-w-explanation-oror-TM%3A-9586", "python_solutions": "class Solution:\n # A very good description of the dp solution is at\n # https://leetcode.com/problems/k-inverse-pairs-array/solution/ \n # The code below uses two 1D arrays--dp and tmp--instead if a \n # 2D array. tmp replaces dp after each i-iteration.\n def kInversePairs(self, n: int, k: int) -> int:\n dp, mod = [1]+[0] * k, 1000000007\n \n for i in range(n):\n tmp, sm = [], 0\n for j in range(k + 1):\n sm+= dp[j]\n if j-i >= 1: sm-= dp[j-i-1]\n sm%= mod\n tmp.append(sm)\n dp = tmp\n #print(dp) # <-- uncomment this line to get a sense of dp from the print output\n\t\t\t # try n = 6, k = 4; your answer should be 49.\n return dp[k]", "slug": "k-inverse-pairs-array", "post_title": "Python3 || dp,1D array, 10 lines, w/ explanation || T/M: 95%/86%", "user": "warrenruud", "upvotes": 8, "views": 657, "problem_title": "k inverse pairs array", "number": 629, "acceptance": 0.429, "difficulty": "Hard", "__index_level_0__": 10562, "question": "For an integer array nums, an inverse pair is a pair of integers [i, j] where 0 <= i < j < nums.length and nums[i] > nums[j].\nGiven two integers n and k, return the number of different arrays consisting of numbers from 1 to n such that there are exactly k inverse pairs. Since the answer can be huge, return it modulo 109 + 7.\n Example 1:\nInput: n = 3, k = 0\nOutput: 1\nExplanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\nExample 2:\nInput: n = 3, k = 1\nOutput: 2\nExplanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n Constraints:\n1 <= n <= 1000\n0 <= k <= 1000" }, { "post_href": "https://leetcode.com/problems/course-schedule-iii/discuss/2185553/Python3-oror-Heapq-oror-Faster-Solution-with-explanation", "python_solutions": "class Solution:\n def scheduleCourse(self, courses: List[List[int]]) -> int:\n courses.sort(key=lambda c: c[1])\n A, curr = [], 0\n for dur, ld in courses:\n heapq.heappush(A,-dur)\n curr += dur\n if curr > ld: curr += heapq.heappop(A)\n return len(A)", "slug": "course-schedule-iii", "post_title": "Python3 || Heapq || Faster Solution with explanation", "user": "bvian", "upvotes": 28, "views": 1000, "problem_title": "course schedule iii", "number": 630, "acceptance": 0.402, "difficulty": "Hard", "__index_level_0__": 10570, "question": "There are n different online courses numbered from 1 to n. You are given an array courses where courses[i] = [durationi, lastDayi] indicate that the ith course should be taken continuously for durationi days and must be finished before or on lastDayi.\nYou will start on the 1st day and you cannot take two or more courses simultaneously.\nReturn the maximum number of courses that you can take.\n Example 1:\nInput: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\nOutput: 3\nExplanation: \nThere are totally 4 courses, but you can take 3 courses at most:\nFirst, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\nSecond, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \nThird, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \nThe 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\nExample 2:\nInput: courses = [[1,2]]\nOutput: 1\nExample 3:\nInput: courses = [[3,2],[4,3]]\nOutput: 0\n Constraints:\n1 <= courses.length <= 104\n1 <= durationi, lastDayi <= 104" }, { "post_href": "https://leetcode.com/problems/smallest-range-covering-elements-from-k-lists/discuss/1495460/PYTHON-SOLUTION-FASTER-THAN-88.58-OF-PYTHON-SUBMISSIONS", "python_solutions": "class Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n k=len(nums)\n maxx=-float('inf')\n ans=[0,float('inf')]\n heap=[]\n for i in range(k):\n heap.append((nums[i][0],i,0))\n if nums[i][0]>maxx:maxx=nums[i][0]\n heapq.heapify(heap)\n while True:\n val,row,col= heapq.heappop(heap)\n tmp=maxx-val\n if tmpmaxx:maxx=nums[row][col+1]\n heapq.heappush(heap,(nums[row][col+1],row,col+1))\n return ans", "slug": "smallest-range-covering-elements-from-k-lists", "post_title": "PYTHON SOLUTION FASTER THAN 88.58% OF PYTHON SUBMISSIONS", "user": "reaper_27", "upvotes": 1, "views": 113, "problem_title": "smallest range covering elements from k lists", "number": 632, "acceptance": 0.606, "difficulty": "Hard", "__index_level_0__": 10585, "question": "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.\nWe 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 Example 1:\nInput: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nOutput: [20,24]\nExplanation: \nList 1: [4, 10, 15, 24,26], 24 is in range [20,24].\nList 2: [0, 9, 12, 20], 20 is in range [20,24].\nList 3: [5, 18, 22, 30], 22 is in range [20,24].\nExample 2:\nInput: nums = [[1,2,3],[1,2,3],[1,2,3]]\nOutput: [1,1]\n Constraints:\nnums.length == k\n1 <= k <= 3500\n1 <= nums[i].length <= 50\n-105 <= nums[i][j] <= 105\nnums[i] is sorted in non-decreasing order." }, { "post_href": "https://leetcode.com/problems/sum-of-square-numbers/discuss/2203194/Python3-solution-using-two-pointers", "python_solutions": "class Solution:\n def judgeSquareSum(self, c: int) -> bool:\n low = 0\n high = int(sqrt(c))\n \n if high**2 == c:\n return True\n \n while low<=high:\n x = low **2 + high **2\n if x == c:\n return True\n if x > c:\n high-=1\n else:\n low+=1\n return False", "slug": "sum-of-square-numbers", "post_title": "\ud83d\udccc Python3 solution using two pointers", "user": "Dark_wolf_jss", "upvotes": 6, "views": 89, "problem_title": "sum of square numbers", "number": 633, "acceptance": 0.346, "difficulty": "Medium", "__index_level_0__": 10592, "question": "Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.\n Example 1:\nInput: c = 5\nOutput: true\nExplanation: 1 * 1 + 2 * 2 = 5\nExample 2:\nInput: c = 3\nOutput: false\n Constraints:\n0 <= c <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/exclusive-time-of-functions/discuss/863039/Python-3-or-Clean-Simple-Stack-or-Explanation", "python_solutions": "class Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n helper = lambda log: (int(log[0]), log[1], int(log[2])) # to covert id and time to integer\n logs = [helper(log.split(':')) for log in logs] # convert [string] to [(,,)]\n ans, s = [0] * n, [] # initialize answer and stack\n for (i, status, timestamp) in logs: # for each record\n if status == 'start': # if it's start\n if s: ans[s[-1][0]] += timestamp - s[-1][1] # if s is not empty, update time spent on previous id (s[-1][0])\n s.append([i, timestamp]) # then add to top of stack\n else: # if it's end\n ans[i] += timestamp - s.pop()[1] + 1 # update time spend on `i`\n if s: s[-1][1] = timestamp+1 # if s is not empty, udpate start time of previous id; \n return ans", "slug": "exclusive-time-of-functions", "post_title": "Python 3 | Clean, Simple Stack | Explanation", "user": "idontknoooo", "upvotes": 15, "views": 1100, "problem_title": "exclusive time of functions", "number": 636, "acceptance": 0.611, "difficulty": "Medium", "__index_level_0__": 10614, "question": "On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.\nFunction calls are stored in a call stack: when a function call starts, its ID is pushed onto the stack, and when a function call ends, its ID is popped off the stack. The function whose ID is at the top of the stack is the current function being executed. Each time a function starts or ends, we write a log with the ID, whether it started or ended, and the timestamp.\nYou are given a list logs, where logs[i] represents the ith log message formatted as a string \"{function_id}:{\"start\" | \"end\"}:{timestamp}\". For example, \"0:start:3\" means a function call with function ID 0 started at the beginning of timestamp 3, and \"1:end:2\" means a function call with function ID 1 ended at the end of timestamp 2. Note that a function can be called multiple times, possibly recursively.\nA function's exclusive time is the sum of execution times for all function calls in the program. For example, if a function is called twice, one call executing for 2 time units and another call executing for 1 time unit, the exclusive time is 2 + 1 = 3.\nReturn the exclusive time of each function in an array, where the value at the ith index represents the exclusive time for the function with ID i.\n Example 1:\nInput: n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]\nOutput: [3,4]\nExplanation:\nFunction 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\nFunction 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\nFunction 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\nSo function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\nExample 2:\nInput: n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]\nOutput: [8]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls itself again.\nFunction 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\nFunction 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\nSo function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\nExample 3:\nInput: n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]\nOutput: [7,1]\nExplanation:\nFunction 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\nFunction 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\nFunction 0 (initial call) resumes execution then immediately calls function 1.\nFunction 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\nFunction 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\nSo function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n Constraints:\n1 <= n <= 100\n1 <= logs.length <= 500\n0 <= function_id < n\n0 <= timestamp <= 109\nNo two start events will happen at the same timestamp.\nNo two end events will happen at the same timestamp.\nEach function has an \"end\" log for each \"start\" log." }, { "post_href": "https://leetcode.com/problems/average-of-levels-in-binary-tree/discuss/492462/PythonGo-O(n)-by-level-order-traversal.-w-Explanation", "python_solutions": "class Solution:\n def averageOfLevels(self, root: TreeNode) -> List[float]:\n \n if not root:\n \n # Quick response for empty tree\n return []\n \n traversal_q = [root]\n \n average = []\n \n while traversal_q:\n \n # compute current level average\n cur_avg = sum( (node.val for node in traversal_q if node) ) / len(traversal_q)\n \n # add to result\n average.append( cur_avg )\n \n # update next level queue\n next_level_q = [ child for node in traversal_q for child in (node.left, node.right) if child ]\n \n # update traversal queue as next level's\n traversal_q = next_level_q\n \n return average", "slug": "average-of-levels-in-binary-tree", "post_title": "Python/Go O(n) by level-order-traversal. [ w/ Explanation ]", "user": "brianchiang_tw", "upvotes": 10, "views": 1300, "problem_title": "average of levels in binary tree", "number": 637, "acceptance": 0.7170000000000001, "difficulty": "Easy", "__index_level_0__": 10629, "question": "Given the root of a binary tree, return the average value of the nodes on each level in the form of an array. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [3.00000,14.50000,11.00000]\nExplanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\nHence return [3, 14.5, 11].\nExample 2:\nInput: root = [3,9,20,15,7]\nOutput: [3.00000,14.50000,11.00000]\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-231 <= Node.val <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/shopping-offers/discuss/783072/Python-3-DFS-%2B-Memoization-(lru_cache)", "python_solutions": "class Solution:\n def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n n = len(price)\n @lru_cache(maxsize=None)\n def dfs(needs):\n ans = sum([i*j for i, j in zip(price, needs)]) \n cur = sys.maxsize\n for s in special:\n new_needs, ok = [], True\n for i in range(n):\n need, give = needs[i], s[i]\n if need < give: # if over purchase, ignore this combination\n ok = False\n break\n new_needs.append(need-give) \n if ok: cur = min(cur, dfs(tuple(new_needs)) + s[-1])\n return min(ans, cur)\n return dfs(tuple(needs))", "slug": "shopping-offers", "post_title": "Python 3 DFS + Memoization (lru_cache)", "user": "idontknoooo", "upvotes": 2, "views": 292, "problem_title": "shopping offers", "number": 638, "acceptance": 0.541, "difficulty": "Medium", "__index_level_0__": 10657, "question": "In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.\nYou are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.\nYou are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.\nReturn the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.\n Example 1:\nInput: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\nOutput: 14\nExplanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \nIn special offer 1, you can pay $5 for 3A and 0B\nIn special offer 2, you can pay $10 for 1A and 2B. \nYou need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.\nExample 2:\nInput: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\nOutput: 11\nExplanation: The price of A is $2, and $3 for B, $4 for C. \nYou may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \nYou need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. \nYou cannot add more items, though only $9 for 2A ,2B and 1C.\n Constraints:\nn == price.length == needs.length\n1 <= n <= 6\n0 <= price[i], needs[i] <= 10\n1 <= special.length <= 100\nspecial[i].length == n + 1\n0 <= special[i][j] <= 50" }, { "post_href": "https://leetcode.com/problems/decode-ways-ii/discuss/2509952/Best-Python3-implementation-(Top-93.7)-oror-Clean-code", "python_solutions": "class Solution:\n def numDecodings(self, s: str) -> int:\n non_zero = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n first_incl, second_incl = 1, 0\n first_excl, second_excl = 0, 0\n \n if s[0] in non_zero:\n second_incl = 1\n if s[0] == '*':\n second_incl = 9\n \n for i in range(1, len(s)):\n new_incl, new_excl = 0, 0\n if s[i] == '*':\n new_incl = 9 * (second_incl + second_excl)\n \n if s[i-1] == '1':\n # number is of type (1, *)\n new_excl = 9 * (first_incl + first_excl)\n \n elif s[i-1] == '2':\n # number is of type (2, *)\n new_excl = 6 * (first_incl + first_excl)\n \n elif s[i-1] == '*':\n # number is of type (*, *)\n new_excl = 15 * (first_incl + first_excl)\n else:\n if s[i] in non_zero:\n new_incl = second_incl + second_excl\n \n if s[i-1] == '*':\n # number is of type (*,digit)\n if int(s[i]) <= 6:\n new_excl = 2 * (first_excl + first_incl)\n else:\n new_excl = first_incl + first_excl\n \n else:\n # number is of type (digit,digit)\n val = int(s[i-1:i+1])\n if 10 <= val <= 26:\n new_excl = first_incl + first_excl\n else:\n new_excl = 0\n first_incl, first_excl = second_incl, second_excl\n second_incl, second_excl = new_incl, new_excl\n return (second_incl + second_excl) % (10**9 + 7)", "slug": "decode-ways-ii", "post_title": "\u2714\ufe0f Best Python3 implementation (Top 93.7%) || Clean code", "user": "UpperNoot", "upvotes": 0, "views": 25, "problem_title": "decode ways ii", "number": 639, "acceptance": 0.304, "difficulty": "Hard", "__index_level_0__": 10662, "question": "A message containing letters from A-Z can be encoded into numbers using the following mapping:\n'A' -> \"1\"\n'B' -> \"2\"\n...\n'Z' -> \"26\"\nTo decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\n\"AAJF\" with the grouping (1 1 10 6)\n\"KJF\" with the grouping (11 10 6)\nNote that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\nIn addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\". Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent.\nGiven a string s consisting of digits and '*' characters, return the number of ways to decode it.\nSince the answer may be very large, return it modulo 109 + 7.\n Example 1:\nInput: s = \"*\"\nOutput: 9\nExplanation: The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\nEach of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\nHence, there are a total of 9 ways to decode \"*\".\nExample 2:\nInput: s = \"1*\"\nOutput: 18\nExplanation: The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\nEach of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\nHence, there are a total of 9 * 2 = 18 ways to decode \"1*\".\nExample 3:\nInput: s = \"2*\"\nOutput: 15\nExplanation: The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n\"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\nHence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".\n Constraints:\n1 <= s.length <= 105\ns[i] is a digit or '*'." }, { "post_href": "https://leetcode.com/problems/solve-the-equation/discuss/837106/Python-or-No-Regex-or-Simple-Logic-or-Probably-better-for-interviews-or-Commented", "python_solutions": "class Solution:\n def solveEquation(self, equation: str) -> str:\n def helper(l,r): # left inclusive and right exclusive\n constant = unknown = 0\n sign,val = 1,''\n while l < r:\n if equation[l].isnumeric():\n val += equation[l]\n elif equation[l] == 'x':\n unknown += sign*int(val or '1') # in case the coefficient is 1\n val = ''\n else: # meet a +/-\n if val:\n constant += sign*int(val)\n sign = 1 if equation[l]=='+' else -1\n val = ''\n l += 1\n if val: # if the last digit is a number\n constant += sign*i\n return constant,unknown\n \n mid = equation.find('=')\n constant1,unknown1 = helper(0,mid)\n constant2,unknown2 = helper(mid+1,len(equation))\n const,var = constant2-constant1,unknown1-unknown2\n # print(a,b)\n if var == 0:\n if const == 0: return \"Infinite solutions\"\n else: return \"No solution\"\n else: return 'x={}'.format(const//var)", "slug": "solve-the-equation", "post_title": "Python | No Regex | Simple Logic | Probably better for interviews | Commented", "user": "since2020", "upvotes": 6, "views": 299, "problem_title": "solve the equation", "number": 640, "acceptance": 0.434, "difficulty": "Medium", "__index_level_0__": 10664, "question": "Solve a given equation and return the value of 'x' in the form of a string \"x=#value\". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return \"No solution\" if there is no solution for the equation, or \"Infinite solutions\" if there are infinite solutions for the equation.\nIf there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.\n Example 1:\nInput: equation = \"x+5-3+x=6+x-2\"\nOutput: \"x=2\"\nExample 2:\nInput: equation = \"x=x\"\nOutput: \"Infinite solutions\"\nExample 3:\nInput: equation = \"2x=x\"\nOutput: \"x=0\"\n Constraints:\n3 <= equation.length <= 1000\nequation has exactly one '='.\nequation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'." }, { "post_href": "https://leetcode.com/problems/maximum-average-subarray-i/discuss/336428/Solution-in-Python-3-(beats-100)", "python_solutions": "class Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float:\n \tM = d = 0\n \tfor i in range(len(nums)-k):\n \t\td += nums[i+k] - nums[i]\n \t\tif d > M: M = d\n \treturn (sum(nums[:k])+M)/k\n\t\t\n\t\t\n- Python 3\n- Junaid Mansuri", "slug": "maximum-average-subarray-i", "post_title": "Solution in Python 3 (beats 100%)", "user": "junaidmansuri", "upvotes": 11, "views": 2100, "problem_title": "maximum average subarray i", "number": 643, "acceptance": 0.4379999999999999, "difficulty": "Easy", "__index_level_0__": 10672, "question": "You are given an integer array nums consisting of n elements, and an integer k.\nFind a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.\n Example 1:\nInput: nums = [1,12,-5,-6,50,3], k = 4\nOutput: 12.75000\nExplanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75\nExample 2:\nInput: nums = [5], k = 1\nOutput: 5.00000\n Constraints:\nn == nums.length\n1 <= k <= n <= 105\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/set-mismatch/discuss/2733971/Easy-Python-Solution", "python_solutions": "class Solution:\n def findErrorNums(self, nums: List[int]) -> List[int]:\n c=Counter(nums)\n l=[0,0]\n for i in range(1,len(nums)+1):\n if c[i]==2:\n l[0]=i\n if c[i]==0:\n l[1]=i\n return l", "slug": "set-mismatch", "post_title": "Easy Python Solution", "user": "Vistrit", "upvotes": 14, "views": 966, "problem_title": "set mismatch", "number": 645, "acceptance": 0.43, "difficulty": "Easy", "__index_level_0__": 10705, "question": "You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.\nYou are given an integer array nums representing the data status of this set after the error.\nFind the number that occurs twice and the number that is missing and return them in the form of an array.\n Example 1:\nInput: nums = [1,2,2,4]\nOutput: [2,3]\nExample 2:\nInput: nums = [1,1]\nOutput: [1,2]\n Constraints:\n2 <= nums.length <= 104\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/maximum-length-of-pair-chain/discuss/1564508/Fast-O(NlogN)-and-simple-Python-3-solution", "python_solutions": "class Solution:\n def findLongestChain(self, pairs: List[List[int]]) -> int:\n pairs.sort()\n rt = 1\n l = pairs[0]\n for r in range(1,len(pairs)):\n if l[1] < pairs[r][0]:\n rt += 1 \n l = pairs[r]\n elif pairs[r][1] [3,4].\nExample 2:\nInput: pairs = [[1,2],[7,8],[4,5]]\nOutput: 3\nExplanation: The longest chain is [1,2] -> [4,5] -> [7,8].\n Constraints:\nn == pairs.length\n1 <= n <= 1000\n-1000 <= lefti < righti <= 1000" }, { "post_href": "https://leetcode.com/problems/palindromic-substrings/discuss/392119/Solution-in-Python-3-(beats-~94)-(six-lines)-(With-Detaiiled-Explanation)", "python_solutions": "class Solution:\n def countSubstrings(self, s: str) -> int:\n\t L, r = len(s), 0\n\t for i in range(L):\n\t \tfor a,b in [(i,i),(i,i+1)]:\n\t \t\twhile a >= 0 and b < L and s[a] == s[b]: a -= 1; b += 1\n\t \t\tr += (b-a)//2\n\t return r\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "palindromic-substrings", "post_title": "Solution in Python 3 (beats ~94%) (six lines) (With Detaiiled Explanation)", "user": "junaidmansuri", "upvotes": 67, "views": 8100, "problem_title": "palindromic substrings", "number": 647, "acceptance": 0.664, "difficulty": "Medium", "__index_level_0__": 10781, "question": "Given a string s, return the number of palindromic substrings in it.\nA string is a palindrome when it reads the same backward as forward.\nA substring is a contiguous sequence of characters within the string.\n Example 1:\nInput: s = \"abc\"\nOutput: 3\nExplanation: Three palindromic strings: \"a\", \"b\", \"c\".\nExample 2:\nInput: s = \"aaa\"\nOutput: 6\nExplanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".\n Constraints:\n1 <= s.length <= 1000\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/replace-words/discuss/1576514/Fast-solution-beats-97-submissions", "python_solutions": "class Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n d = {w:len(w) for w in dictionary}\n mini, maxi = min(d.values()), max(d.values())\n wd = sentence.split()\n rt = []\n for s in wd:\n c = s \n for k in range(mini,min(maxi,len(s))+1):\n ss = s[:k]\n if ss in d:\n c = ss \n break \n rt.append(c)\n return \" \".join(rt)", "slug": "replace-words", "post_title": "Fast solution beats 97% submissions", "user": "cyrille-k", "upvotes": 3, "views": 118, "problem_title": "replace words", "number": 648, "acceptance": 0.627, "difficulty": "Medium", "__index_level_0__": 10832, "question": "In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root \"help\" is followed by the successor word \"ful\", we can form a new word \"helpful\".\nGiven a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.\nReturn the sentence after the replacement.\n Example 1:\nInput: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\nOutput: \"the cat was rat by the bat\"\nExample 2:\nInput: dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\nOutput: \"a a b c\"\n Constraints:\n1 <= dictionary.length <= 1000\n1 <= dictionary[i].length <= 100\ndictionary[i] consists of only lower-case letters.\n1 <= sentence.length <= 106\nsentence consists of only lower-case letters and spaces.\nThe number of words in sentence is in the range [1, 1000]\nThe length of each word in sentence is in the range [1, 1000]\nEvery two consecutive words in sentence will be separated by exactly one space.\nsentence does not have leading or trailing spaces." }, { "post_href": "https://leetcode.com/problems/dota2-senate/discuss/845912/Python-3-or-Greedy-Simulation-or-Explanantion", "python_solutions": "class Solution:\n def predictPartyVictory(self, senate: str) -> str:\n n = len(senate)\n s, banned = set(), [False] * n\n ban_d = ban_r = 0\n while len(s) != 1:\n s = set()\n for i, p in enumerate(senate):\n if banned[i]: continue\n if p == 'R':\n if ban_r > 0: # current R being banned\n ban_r -= 1\n banned[i] = True\n else: # if current R is valid, it will ban D\n ban_d += 1\n s.add('R')\n else: \n if ban_d > 0: # current D being banned\n ban_d -= 1\n banned[i] = True\n else: # if current D is valid, it will ban R\n ban_r += 1\n s.add('D')\n return 'Radiant' if s.pop() == 'R' else 'Dire'", "slug": "dota2-senate", "post_title": "Python 3 | Greedy, Simulation | Explanantion", "user": "idontknoooo", "upvotes": 8, "views": 690, "problem_title": "dota2 senate", "number": 649, "acceptance": 0.4039999999999999, "difficulty": "Medium", "__index_level_0__": 10852, "question": "In the world of Dota2, there are two parties: the Radiant and the Dire.\nThe Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise one of the two rights:\nBan one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.\nAnnounce the victory: If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.\nGiven a string senate representing each senator's party belonging. The character 'R' and 'D' represent the Radiant party and the Dire party. Then if there are n senators, the size of the given string will be n.\nThe round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.\nSuppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be \"Radiant\" or \"Dire\".\n Example 1:\nInput: senate = \"RD\"\nOutput: \"Radiant\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\nExample 2:\nInput: senate = \"RDD\"\nOutput: \"Dire\"\nExplanation: \nThe first senator comes from Radiant and he can just ban the next senator's right in round 1. \nAnd the second senator can't exercise any rights anymore since his right has been banned. \nAnd the third senator comes from Dire and he can ban the first senator's right in round 1. \nAnd in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n Constraints:\nn == senate.length\n1 <= n <= 104\nsenate[i] is either 'R' or 'D'." }, { "post_href": "https://leetcode.com/problems/2-keys-keyboard/discuss/727856/Python3-Dynamic-Programming-Beginners", "python_solutions": "class Solution:\n def minSteps(self, n: int) -> int:\n \n dp = [float('inf')] * (n+1)\t\n\t\t## Intialize a dp array to store the solutions of sub problems i.e. number of steps needed\n\t\n dp[1] = 0\n\t\t## Intially first element of dp array with 0 as 'A' is already present and we haven't consumed any steps yet. \n\t\t## As the value of n is from [1,3000] and initally 'A' is already present so we don't need to bother about the dp[0]\n \n divisors = []\n\t\t## This is to store the divisors of N\n\t\t\n for i in range(1, n//2 + 1):\n if n % i == 0:\n divisors.append(i)\n\t\t## We have stored all the divisors. For n = 10, divisors = [1,2,5]\n \n for j in divisors:\n dp[j] += 1\n\t\t\t##To copy the current number of A's, we add one step\n\t\t\t\n for i in range(j+1, n+1):\n if i % j == 0:\n\t\t\t\t## We can only form the string length which is divisible by j \n dp[i] = min(dp[i], dp[i-j] + 1)\n\t\t\t\t\t## Compare with previous number of steps and update with the minimum\n return dp[-1]\n\t\t#Return last value of dp i.e. N", "slug": "2-keys-keyboard", "post_title": "Python3 Dynamic Programming - Beginners", "user": "ayushjain94", "upvotes": 12, "views": 1000, "problem_title": "2 keys keyboard", "number": 650, "acceptance": 0.532, "difficulty": "Medium", "__index_level_0__": 10857, "question": "There is only one character 'A' on the screen of a notepad. You can perform one of two operations on this notepad for each step:\nCopy All: You can copy all the characters present on the screen (a partial copy is not allowed).\nPaste: You can paste the characters which are copied last time.\nGiven an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.\n Example 1:\nInput: n = 3\nOutput: 3\nExplanation: Initially, we have one character 'A'.\nIn step 1, we use Copy All operation.\nIn step 2, we use Paste operation to get 'AA'.\nIn step 3, we use Paste operation to get 'AAA'.\nExample 2:\nInput: n = 1\nOutput: 0\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/find-duplicate-subtrees/discuss/1178526/Easy-%2B-Clean-%2B-Straightforward-Python-Recursive", "python_solutions": "class Solution:\n def findDuplicateSubtrees(self, root: TreeNode) -> List[TreeNode]:\n \n seen = collections.defaultdict(int)\n res = []\n \n def helper(node):\n if not node:\n return\n sub = tuple([helper(node.left), node.val, helper(node.right)])\n if sub in seen and seen[sub] == 1:\n res.append(node)\n seen[sub] += 1\n return sub\n \n helper(root)\n return res", "slug": "find-duplicate-subtrees", "post_title": "Easy + Clean + Straightforward Python Recursive", "user": "Pythagoras_the_3rd", "upvotes": 15, "views": 1100, "problem_title": "find duplicate subtrees", "number": 652, "acceptance": 0.565, "difficulty": "Medium", "__index_level_0__": 10880, "question": "Given the root of a binary tree, return all duplicate subtrees.\nFor each kind of duplicate subtrees, you only need to return the root node of any one of them.\nTwo trees are duplicate if they have the same structure with the same node values.\n Example 1:\nInput: root = [1,2,3,4,null,2,4,null,null,4]\nOutput: [[2,4],[4]]\nExample 2:\nInput: root = [2,1,1]\nOutput: [[1]]\nExample 3:\nInput: root = [2,2,2,3,null,3,null]\nOutput: [[2,3],[3]]\n Constraints:\nThe number of the nodes in the tree will be in the range [1, 5000]\n-200 <= Node.val <= 200" }, { "post_href": "https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1011974/BFS-two-pointers-and-recursive", "python_solutions": "class Solution:\n def findTarget(self, root: TreeNode, k: int) -> bool:\n queue = [root]\n unique_set = set()\n \n while len(queue) > 0:\n current = queue.pop()\n if k - current.val in unique_set: return True\n unique_set.add(current.val)\n if current.left: queue.append(current.left)\n if current.right: queue.append(current.right)\n \n return False", "slug": "two-sum-iv-input-is-a-bst", "post_title": "BFS, two pointers and recursive", "user": "borodayev", "upvotes": 2, "views": 213, "problem_title": "two sum iv input is a bst", "number": 653, "acceptance": 0.61, "difficulty": "Easy", "__index_level_0__": 10886, "question": "Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.\n Example 1:\nInput: root = [5,3,6,2,4,null,7], k = 9\nOutput: true\nExample 2:\nInput: root = [5,3,6,2,4,null,7], k = 28\nOutput: false\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-104 <= Node.val <= 104\nroot is guaranteed to be a valid binary search tree.\n-105 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-binary-tree/discuss/944324/simple-python3-solution-with-recursion", "python_solutions": "class Solution:\n def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:\n \n # base case\n if not nums:\n return None\n \n max_val = max(nums)\n max_idx = nums.index(max_val)\n root = TreeNode(max_val)\n \n root.left = self.constructMaximumBinaryTree(nums[:max_idx])\n root.right = self.constructMaximumBinaryTree(nums[max_idx+1:])\n \n return root", "slug": "maximum-binary-tree", "post_title": "simple python3 solution with recursion", "user": "Gushen88", "upvotes": 2, "views": 100, "problem_title": "maximum binary tree", "number": 654, "acceptance": 0.845, "difficulty": "Medium", "__index_level_0__": 10922, "question": "You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:\nCreate a root node whose value is the maximum value in nums.\nRecursively build the left subtree on the subarray prefix to the left of the maximum value.\nRecursively build the right subtree on the subarray suffix to the right of the maximum value.\nReturn the maximum binary tree built from nums.\n Example 1:\nInput: nums = [3,2,1,6,0,5]\nOutput: [6,3,5,null,2,0,null,null,1]\nExplanation: The recursive calls are as follow:\n- The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.\nExample 2:\nInput: nums = [3,2,1]\nOutput: [3,null,2,null,1]\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] <= 1000\nAll integers in nums are unique." }, { "post_href": "https://leetcode.com/problems/print-binary-tree/discuss/1384379/Python-3-or-DFS-%2B-BFS-(Level-order-traversal)-or-Explanation", "python_solutions": "class Solution:\n def printTree(self, root: TreeNode) -> List[List[str]]:\n height = 0\n def dfs(node, h): # Find height\n nonlocal height\n height = max(height, h)\n if node.left:\n dfs(node.left, h+1)\n if node.right: \n dfs(node.right, h+1)\n dfs(root, 0)\n n = 2 ** (height + 1) - 1 # Get `n`\n offset = (n - 1) // 2 # Column for root node\n ans = [[''] * n for _ in range(height + 1)]\n q = [(root, 0, offset)]\n for i in range(height+1): # BFS\n tmp_q = []\n while q:\n cur, r, c = q.pop()\n ans[r][c] = str(cur.val)\n if cur.left:\n tmp_q.append((cur.left, r+1, c-2 ** (height - r - 1)))\n if cur.right: \n tmp_q.append((cur.right, r+1, c+2 ** (height - r - 1)))\n q = tmp_q\n return ans", "slug": "print-binary-tree", "post_title": "Python 3 | DFS + BFS (Level-order-traversal) | Explanation", "user": "idontknoooo", "upvotes": 2, "views": 256, "problem_title": "print binary tree", "number": 655, "acceptance": 0.614, "difficulty": "Medium", "__index_level_0__": 10937, "question": "Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules:\nThe height of the tree is height and the number of rows m should be equal to height + 1.\nThe number of columns n should be equal to 2height+1 - 1.\nPlace the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).\nFor each node that has been placed in the matrix at position res[r][c], place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].\nContinue this process until all the nodes in the tree have been placed.\nAny empty cells should contain the empty string \"\".\nReturn the constructed matrix res.\n Example 1:\nInput: root = [1,2]\nOutput: \n[[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]\nExample 2:\nInput: root = [1,2,3,null,4]\nOutput: \n[[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]\n Constraints:\nThe number of nodes in the tree is in the range [1, 210].\n-99 <= Node.val <= 99\nThe depth of the tree will be in the range [1, 10]." }, { "post_href": "https://leetcode.com/problems/robot-return-to-origin/discuss/342078/Solution-in-Python-3-(~beats-99)-(-one-line-)", "python_solutions": "class Solution:\n def judgeCircle(self, moves: str) -> bool:\n return moves.count('L') == moves.count('R') and moves.count('U') == moves.count('D')\n\n\n- Python 3\n- Junaid Mansuri", "slug": "robot-return-to-origin", "post_title": "Solution in Python 3 (~beats 99%) ( one line )", "user": "junaidmansuri", "upvotes": 11, "views": 1600, "problem_title": "robot return to origin", "number": 657, "acceptance": 0.753, "difficulty": "Easy", "__index_level_0__": 10943, "question": "There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.\nYou are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).\nReturn true if the robot returns to the origin after it finishes all of its moves, or false otherwise.\nNote: The way that the robot is \"facing\" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.\n Example 1:\nInput: moves = \"UD\"\nOutput: true\nExplanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.\nExample 2:\nInput: moves = \"LL\"\nOutput: false\nExplanation: The robot moves left twice. It ends up two \"moves\" to the left of the origin. We return false because it is not at the origin at the end of its moves.\n Constraints:\n1 <= moves.length <= 2 * 104\nmoves only contains the characters 'U', 'D', 'L' and 'R'." }, { "post_href": "https://leetcode.com/problems/find-k-closest-elements/discuss/1310805/Python-Solution", "python_solutions": "class Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n\t\t# first binary search where the value 'x' should be in the sorted array\n n = len(arr)\n low, high = 0, n - 1\n while low <= high:\n mid = low + (high - low) // 2\n if arr[mid] == x:\n start, end = mid - 1, mid + 1\n k -= 1\n break\n elif arr[mid] < x:\n low = mid + 1\n else:\n high = mid - 1\n \n if low > high:\n start = high\n end = low\n # after we found where 'x' should be in the sorted array we expand to the left and to the right to find the next values until k (using two pointers start, end)\n while k > 0:\n if start == -1:\n end += 1\n elif end == n:\n start -= 1\n else:\n if abs(arr[start] - x) <= abs(arr[end] - x):\n start -= 1\n else:\n end += 1\n k -= 1\n return arr[start + 1:end]", "slug": "find-k-closest-elements", "post_title": "Python Solution", "user": "mariandanaila01", "upvotes": 13, "views": 1000, "problem_title": "find k closest elements", "number": 658, "acceptance": 0.4679999999999999, "difficulty": "Medium", "__index_level_0__": 10973, "question": "Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.\nAn integer a is closer to x than an integer b if:\n|a - x| < |b - x|, or\n|a - x| == |b - x| and a < b\n Example 1:\nInput: arr = [1,2,3,4,5], k = 4, x = 3\nOutput: [1,2,3,4]\nExample 2:\nInput: arr = [1,2,3,4,5], k = 4, x = -1\nOutput: [1,2,3,4]\n Constraints:\n1 <= k <= arr.length\n1 <= arr.length <= 104\narr is sorted in ascending order.\n-104 <= arr[i], x <= 104" }, { "post_href": "https://leetcode.com/problems/split-array-into-consecutive-subsequences/discuss/2446738/Python-524ms-98.3-Faster-Multiple-solutions-94-memory-efficient", "python_solutions": "class Solution:\n\t\tdef isPossible(self, nums: List[int]) -> bool:\n\t\t\tlen1 = len2 = absorber = 0\n\t\t\tprev_num = nums[0] - 1\n\t\t\tfor streak_len, streak_num in Solution.get_streaks(nums):\n\t\t\t\tif streak_num == prev_num + 1:\n\t\t\t\t\tspillage = streak_len - len1 - len2\n\t\t\t\t\tif spillage < 0:\n\t\t\t\t\t\treturn False\n\t\t\t\t\tabsorber = min(absorber, spillage)\n\t\t\t\t\tlen1, len2, absorber = spillage - absorber, len1, absorber + len2\n\t\t\t\telse:\n\t\t\t\t\tif len1 or len2:\n\t\t\t\t\t\treturn False\n\t\t\t\t\tabsorber = 0\n\t\t\t\tprev_num = streak_num\n\t\t\treturn len1 == len2 == 0\n\n\t\t@staticmethod\n\t\tdef get_streaks(nums: List[int]):\n\t\t\tstreak_num = nums[0]\n\t\t\tstreak_len = 0\n\t\t\tfor num in nums:\n\t\t\t\tif num == streak_num:\n\t\t\t\t\tstreak_len += 1\n\t\t\t\telse:\n\t\t\t\t\tyield streak_len, streak_num\n\t\t\t\t\tstreak_num = num\n\t\t\t\t\tstreak_len = 1\n\t\t\tyield streak_len, streak_num", "slug": "split-array-into-consecutive-subsequences", "post_title": "Python 524ms 98.3% Faster Multiple solutions 94% memory efficient", "user": "anuvabtest", "upvotes": 44, "views": 2900, "problem_title": "split array into consecutive subsequences", "number": 659, "acceptance": 0.506, "difficulty": "Medium", "__index_level_0__": 11024, "question": "You are given an integer array nums that is sorted in non-decreasing order.\nDetermine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:\nEach subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).\nAll subsequences have a length of 3 or more.\nReturn true if you can split nums according to the above conditions, or false otherwise.\nA subsequence of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., [1,3,5] is a subsequence of [1,2,3,4,5] while [1,3,2] is not).\n Example 1:\nInput: nums = [1,2,3,3,4,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,5] --> 1, 2, 3\n[1,2,3,3,4,5] --> 3, 4, 5\nExample 2:\nInput: nums = [1,2,3,3,4,4,5,5]\nOutput: true\nExplanation: nums can be split into the following subsequences:\n[1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n[1,2,3,3,4,4,5,5] --> 3, 4, 5\nExample 3:\nInput: nums = [1,2,3,4,4,5]\nOutput: false\nExplanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n Constraints:\n1 <= nums.length <= 104\n-1000 <= nums[i] <= 1000\nnums is sorted in non-decreasing order." }, { "post_href": "https://leetcode.com/problems/image-smoother/discuss/454951/Python3-simple-solution", "python_solutions": "class Solution:\n def imageSmoother(self, M: List[List[int]]) -> List[List[int]]:\n row, col = len(M), len(M[0])\n res = [[0]*col for i in range(row)]\n dirs = [[0,0],[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1],[-1,1],[1,-1]]\n for i in range(row):\n for j in range(col):\n temp = [M[i+m][j+n] for m,n in dirs if 0<=i+m int:\n Q = collections.deque()\n Q.append((root,0))\n ans = 0\n while Q:\n length = len(Q)\n _, start = Q[0]\n for i in range(length):\n node, index = Q.popleft()\n if node.left:\n Q.append((node.left, 2*index))\n if node.right:\n Q.append((node.right, 2*index+1))\n ans = max(ans, index-start+1)\n return ans", "slug": "maximum-width-of-binary-tree", "post_title": "Python solution - O(N) BFS traversal", "user": "realslimshady", "upvotes": 4, "views": 489, "problem_title": "maximum width of binary tree", "number": 662, "acceptance": 0.407, "difficulty": "Medium", "__index_level_0__": 11045, "question": "Given the root of a binary tree, return the maximum width of the given tree.\nThe maximum width of a tree is the maximum width among all levels.\nThe width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.\nIt is guaranteed that the answer will in the range of a 32-bit signed integer.\n Example 1:\nInput: root = [1,3,2,5,3,null,9]\nOutput: 4\nExplanation: The maximum width exists in the third level with length 4 (5,3,null,9).\nExample 2:\nInput: root = [1,3,2,5,null,null,9,6,null,7]\nOutput: 7\nExplanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).\nExample 3:\nInput: root = [1,3,2,5]\nOutput: 2\nExplanation: The maximum width exists in the second level with length 2 (3,2).\n Constraints:\nThe number of nodes in the tree is in the range [1, 3000].\n-100 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/strange-printer/discuss/1492420/Python3-dp", "python_solutions": "class Solution:\n def strangePrinter(self, s: str) -> int:\n s = \"\".join(ch for i, ch in enumerate(s) if i == 0 or s[i-1] != ch)\n \n @cache\n def fn(lo, hi): \n \"\"\"Return min ops to print s[lo:hi].\"\"\"\n if lo == hi: return 0\n ans = 1 + fn(lo+1, hi)\n for mid in range(lo+1, hi): \n if s[lo] == s[mid]: \n ans = min(ans, fn(lo, mid) + fn(mid+1, hi))\n return ans \n \n return fn(0, len(s))", "slug": "strange-printer", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 3, "views": 378, "problem_title": "strange printer", "number": 664, "acceptance": 0.4679999999999999, "difficulty": "Hard", "__index_level_0__": 11066, "question": "There is a strange printer with the following two special properties:\nThe printer can only print a sequence of the same character each time.\nAt each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.\nGiven a string s, return the minimum number of turns the printer needed to print it.\n Example 1:\nInput: s = \"aaabbb\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"bbb\".\nExample 2:\nInput: s = \"aba\"\nOutput: 2\nExplanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n Constraints:\n1 <= s.length <= 100\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/non-decreasing-array/discuss/2193030/Python-Easy-Greedy-w-explanation-O(1)-space", "python_solutions": "class Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n cnt_violations=0 \n for i in range(1, len(nums)): \n if nums[i]=2 and nums[i-2]>nums[i]:\n nums[i]=nums[i-1] \n return True", "slug": "non-decreasing-array", "post_title": "Python Easy Greedy w/ explanation - O(1) space", "user": "constantine786", "upvotes": 52, "views": 2800, "problem_title": "non decreasing array", "number": 665, "acceptance": 0.242, "difficulty": "Medium", "__index_level_0__": 11067, "question": "Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.\nWe define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).\n Example 1:\nInput: nums = [4,2,3]\nOutput: true\nExplanation: You could modify the first 4 to 1 to get a non-decreasing array.\nExample 2:\nInput: nums = [4,2,1]\nOutput: false\nExplanation: You cannot get a non-decreasing array by modifying at most one element.\n Constraints:\nn == nums.length\n1 <= n <= 104\n-105 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/beautiful-arrangement-ii/discuss/1158414/Python3-greedy", "python_solutions": "class Solution:\n def constructArray(self, n: int, k: int) -> List[int]:\n lo, hi = 1, n \n ans = []\n while lo <= hi: \n if k&1: \n ans.append(lo)\n lo += 1\n else: \n ans.append(hi)\n hi -= 1\n if k > 1: k -= 1\n return ans", "slug": "beautiful-arrangement-ii", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 1, "views": 57, "problem_title": "beautiful arrangement ii", "number": 667, "acceptance": 0.597, "difficulty": "Medium", "__index_level_0__": 11096, "question": "Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:\nSuppose this list is answer = [a1, a2, a3, ... , an], then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.\nReturn the list answer. If there multiple valid answers, return any of them.\n Example 1:\nInput: n = 3, k = 1\nOutput: [1,2,3]\nExplanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\nExample 2:\nInput: n = 3, k = 2\nOutput: [1,3,2]\nExplanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.\n Constraints:\n1 <= k < n <= 104" }, { "post_href": "https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/discuss/1581461/Binary-Search-Solution-with-detailed-explanation-beating-98-in-time-and-86-in-space", "python_solutions": "class Solution:\n def findKthNumber(self, m: int, n: int, k: int) -> int:\n\t\t# special cases: k == 1, k == m * n\n if k == 1: \n return 1\n if k == m * n: \n return m * n\n\t\t# make the matrix a tall one - height >= width \n\t\t# because later I will loop along the width. This will reduce the time\n if n >= m: \n m, n = n, m\n \n\t\t# set the left, right boundaries and the ranks (the largest ranks for the values)\n\t\t# e.g. in a 3 * 3 table, number 2 shows up twice, taking up ranks from 2 to 3\n\t\t# so the largest rank here is 3 for number 2. \n left = 1\n # left_rank = 1\n right = m * n\n # right_rank = m * n\n \n\t\t# binary search loop\n while right - left > 1: \n mid = (left + right) // 2\n\t\t\t# mid_rank is the largest rank of the number\n mid_rank = 0\n\t\t\t\n\t\t\t# find the number of columns whose maximum < mid\n\t\t\t# (mid - 1) is to prevent counting the column with maximum == mid.\n num_cols = (mid - 1) // m\n residual = mid - num_cols * m\n mid_rank += num_cols * m\n \n\t\t\t# flag to track if mid is a valid value in the table\n flag = 0\n for i in range(num_cols + 1, n + 1): \n if i == mid: \n mid_rank += 1\n break\n else: \n mid_rank += mid // i\n if mid % i == 0: \n flag = 1\n if flag == 1: \n\t\t\t\t# mid is a valid number in the table\n\t\t\t\t# if mid_rank == k: mid's largest rank is k and mid is the kth number\n\t\t\t\t# if mid_rank < k: kth number > mid, so left = mid\n\t\t\t\t# if mid_rank > k: mid's largest rank > k but mid still can be the kth number but kth number can be no larger than mid, so right = mid\n if mid_rank == k: \n return mid\n elif mid_rank > k: \n right = mid\n else: \n left = mid\n else: \n\t\t\t\t# mid is not a valid number in the table\n\t\t\t\t# if mid_rank == k, it means there are k values in the table smaller than mid\n\t\t\t\t# so there is a number smaller than mid ranking the kth. \n\t\t\t\t# mid_rank > k or mid_rank < k: similar operation as above\n if mid_rank >= k: \n right = mid\n else: \n left = mid\n \n\t\t# In case the while loop breaks out without returning\n\t\t# let's assume when right - left == 2 and mid == left + 1. The solution must be among the three. \n\t\t# right with its largest rank > k\n\t\t# left with its largest rank < k\n\t\t# Scenario 1. if mid is a valid number in the table\n\t\t## 1a. if mid_rank < k: right has its rank from mid_rank + 1 (<= k) till right_rank (> k)\n\t\t## 1b. if mid_rank > k: right = mid. Now right (== mid) has its rank from left_rank + 1 (<= k) till mid_rank (> k)\n\t\t## in both cases, right is the solution\n\t\t# Scenario 2. if mid is not a valid number in the table then we can just ignore mid and imply the solution is right. \n\t\t## But step by step, as mid is not in the table, mid_rank == left_rank, so left = mid. \n\t\t## So right has its rank from mid_rank + 1 (i.e. left_rank + 1) (<= k) till right_rank (> k). right is the solution. \n return right", "slug": "kth-smallest-number-in-multiplication-table", "post_title": "Binary Search Solution with detailed explanation, beating 98% in time and 86% in space", "user": "leonine9", "upvotes": 1, "views": 83, "problem_title": "kth smallest number in multiplication table", "number": 668, "acceptance": 0.515, "difficulty": "Hard", "__index_level_0__": 11104, "question": "Nearly everyone has used the Multiplication Table. The multiplication table of size m x n is an integer matrix mat where mat[i][j] == i * j (1-indexed).\nGiven three integers m, n, and k, return the kth smallest element in the m x n multiplication table.\n Example 1:\nInput: m = 3, n = 3, k = 5\nOutput: 3\nExplanation: The 5th smallest number is 3.\nExample 2:\nInput: m = 2, n = 3, k = 6\nOutput: 6\nExplanation: The 6th smallest number is 6.\n Constraints:\n1 <= m, n <= 3 * 104\n1 <= k <= m * n" }, { "post_href": "https://leetcode.com/problems/trim-a-binary-search-tree/discuss/1046286/Python.-faster-than-98.05.-recursive.-6-lines.-DFS.", "python_solutions": "class Solution:\n\tdef trimBST(self, root: TreeNode, low: int, high: int) -> TreeNode:\n\t\tif not root: return root\n\t\tif root.val < low: return self.trimBST(root.right, low, high)\n\t\tif root.val > high: return self.trimBST(root.left, low, high)\n\t\troot.left = self.trimBST(root.left, low, high)\n\t\troot.right = self.trimBST(root.right, low, high)\n\t\treturn root", "slug": "trim-a-binary-search-tree", "post_title": "Python. faster than 98.05%. recursive. 6 lines. DFS.", "user": "m-d-f", "upvotes": 24, "views": 1000, "problem_title": "trim a binary search tree", "number": 669, "acceptance": 0.6629999999999999, "difficulty": "Medium", "__index_level_0__": 11107, "question": "Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.\nReturn the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.\n Example 1:\nInput: root = [1,0,2], low = 1, high = 2\nOutput: [1,null,2]\nExample 2:\nInput: root = [3,0,4,null,2,null,null,1], low = 1, high = 3\nOutput: [3,2,null,1]\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n0 <= Node.val <= 104\nThe value of each node in the tree is unique.\nroot is guaranteed to be a valid binary search tree.\n0 <= low <= high <= 104" }, { "post_href": "https://leetcode.com/problems/maximum-swap/discuss/846837/Python-3-or-Greedy-Math-or-Explanations", "python_solutions": "class Solution:\n def maximumSwap(self, num: int) -> int:\n s = list(str(num))\n n = len(s)\n for i in range(n-1): # find index where s[i] < s[i+1], meaning a chance to flip\n if s[i] < s[i+1]: break\n else: return num # if nothing find, return num\n max_idx, max_val = i+1, s[i+1] # keep going right, find the maximum value index\n for j in range(i+1, n):\n if max_val <= s[j]: max_idx, max_val = j, s[j]\n left_idx = i # going right from i, find most left value that is less than max_val\n for j in range(i, -1, -1): \n if s[j] < max_val: left_idx = j\n s[max_idx], s[left_idx] = s[left_idx], s[max_idx] # swap maximum after i and most left less than max\n return int(''.join(s)) # re-create the integer", "slug": "maximum-swap", "post_title": "Python 3 | Greedy, Math | Explanations", "user": "idontknoooo", "upvotes": 43, "views": 3600, "problem_title": "maximum swap", "number": 670, "acceptance": 0.479, "difficulty": "Medium", "__index_level_0__": 11137, "question": "You are given an integer num. You can swap two digits at most once to get the maximum valued number.\nReturn the maximum valued number you can get.\n Example 1:\nInput: num = 2736\nOutput: 7236\nExplanation: Swap the number 2 and the number 7.\nExample 2:\nInput: num = 9973\nOutput: 9973\nExplanation: No swap.\n Constraints:\n0 <= num <= 108" }, { "post_href": "https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/discuss/405721/Beats-100-Python-Solution", "python_solutions": "class Solution:\n\tdef findSecondMinimumValue(self, root: TreeNode) -> int:\n\t\tdef inorderTraversal(root):\n\t\t\tif not root:\n\t\t\t\treturn []\n\t\t\telse:\n\t\t\t\treturn inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)\n\t\tr = set(inorderTraversal(root))\n\t\tif len(r)>=2:\n\t\t\treturn sorted(list(r))[1]\n\t\telse:\n\t\t\treturn -1", "slug": "second-minimum-node-in-a-binary-tree", "post_title": "Beats 100% Python Solution", "user": "saffi", "upvotes": 2, "views": 424, "problem_title": "second minimum node in a binary tree", "number": 671, "acceptance": 0.44, "difficulty": "Easy", "__index_level_0__": 11162, "question": "Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.\nGiven such a binary tree, you need to output the second minimum value in the set made of all the nodes' value in the whole tree.\nIf no such second minimum value exists, output -1 instead.\n Example 1:\nInput: root = [2,2,5,null,null,5,7]\nOutput: 5\nExplanation: The smallest value is 2, the second smallest value is 5.\nExample 2:\nInput: root = [2,2,2]\nOutput: -1\nExplanation: The smallest value is 2, but there isn't any second smallest value.\n Constraints:\nThe number of nodes in the tree is in the range [1, 25].\n1 <= Node.val <= 231 - 1\nroot.val == min(root.left.val, root.right.val) for each internal node of the tree." }, { "post_href": "https://leetcode.com/problems/bulb-switcher-ii/discuss/897976/Python3-O(1)", "python_solutions": "class Solution:\n def flipLights(self, n: int, m: int) -> int:\n \n def fn(n, m): \n \"\"\"Return number of different status.\"\"\"\n if m * n == 0: return 1\n return fn(n-1, m-1) + fn(n-1, m)\n \n return fn(min(n, 3), min(m, 3))", "slug": "bulb-switcher-ii", "post_title": "[Python3] O(1)", "user": "ye15", "upvotes": 4, "views": 462, "problem_title": "bulb switcher ii", "number": 672, "acceptance": 0.51, "difficulty": "Medium", "__index_level_0__": 11168, "question": "There is a room with n bulbs labeled from 1 to n that all are turned on initially, and four buttons on the wall. Each of the four buttons has a different functionality where:\nButton 1: Flips the status of all the bulbs.\nButton 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...).\nButton 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...).\nButton 4: Flips the status of all the bulbs with a label j = 3k + 1 where k = 0, 1, 2, ... (i.e., 1, 4, 7, 10, ...).\nYou must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press.\nGiven the two integers n and presses, return the number of different possible statuses after performing all presses button presses.\n Example 1:\nInput: n = 1, presses = 1\nOutput: 2\nExplanation: Status can be:\n- [off] by pressing button 1\n- [on] by pressing button 2\nExample 2:\nInput: n = 2, presses = 1\nOutput: 3\nExplanation: Status can be:\n- [off, off] by pressing button 1\n- [on, off] by pressing button 2\n- [off, on] by pressing button 3\nExample 3:\nInput: n = 3, presses = 1\nOutput: 4\nExplanation: Status can be:\n- [off, off, off] by pressing button 1\n- [off, on, off] by pressing button 2\n- [on, off, on] by pressing button 3\n- [off, on, on] by pressing button 4\n Constraints:\n1 <= n <= 1000\n0 <= presses <= 1000" }, { "post_href": "https://leetcode.com/problems/number-of-longest-increasing-subsequence/discuss/1881188/Python-DP-solution-explained", "python_solutions": "class Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n dp = [1] * len(nums)\n ct = [1] * len(nums)\n maxLen, maxCt = 0, 0\n \n # same as the LIS code, iterate\n # over all the elements once and then\n # from 0 -> i again to compute LISs\n for i in range(len(nums)):\n for j in range(i):\n # If it's a valid LIS\n if nums[i] > nums[j]:\n # and if the length\n # of LIS at i wrt j\n # is going to be increased\n # update the length dp\n # and since this is just one\n # continous LIS, count of i\n # will become same as that of j\n if dp[j]+1 > dp[i]:\n dp[i] = dp[j] + 1\n ct[i] = ct[j]\n # if on the other hand, the\n # length of the LIS at i becomes\n # the same as it was, it means\n # there's another LIS of this same\n # length, in this case, add the LIS\n # count of j to i, because the current\n # LIS count at i consists of ways to get\n # to this LIS from another path, and now\n # we're at a new path, so sum thse up\n # there's no point\n # in updating the length LIS here.\n elif dp[i] == dp[j] + 1:\n ct[i] += ct[j]\n \n # at any point, keep track\n # of the maxLen and maxCt\n # we'll use it to compute our result\n if dp[i] > maxLen:\n maxLen = dp[i]\n \n # now, we have the maxLength\n # of the given nums, we can iterate\n # over all 3 arrays (hypothetically)\n # and just add up the count of all those\n # LIS which are the longest (maxLen)\n # and that's the result\n for i in range(len(nums)):\n if maxLen == dp[i]:\n maxCt += ct[i]\n \n \n return maxCt", "slug": "number-of-longest-increasing-subsequence", "post_title": "[Python] DP solution explained", "user": "buccatini", "upvotes": 2, "views": 182, "problem_title": "number of longest increasing subsequence", "number": 673, "acceptance": 0.423, "difficulty": "Medium", "__index_level_0__": 11171, "question": "Given an integer array nums, return the number of longest increasing subsequences.\nNotice that the sequence has to be strictly increasing.\n Example 1:\nInput: nums = [1,3,5,4,7]\nOutput: 2\nExplanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\nExample 2:\nInput: nums = [2,2,2,2,2]\nOutput: 5\nExplanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n Constraints:\n1 <= nums.length <= 2000\n-106 <= nums[i] <= 106" }, { "post_href": "https://leetcode.com/problems/longest-continuous-increasing-subsequence/discuss/2445685/Two-python-solutions-using-dp-and-a-straightforward-soln", "python_solutions": "class Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n counter=1\n temp=1\n for i in range(0,len(nums)-1):\n if nums[i]counter:\n counter=temp\n else:\n temp=1\n return counter", "slug": "longest-continuous-increasing-subsequence", "post_title": "Two python solutions using dp and a straightforward soln", "user": "guneet100", "upvotes": 3, "views": 182, "problem_title": "longest continuous increasing subsequence", "number": 674, "acceptance": 0.491, "difficulty": "Easy", "__index_level_0__": 11178, "question": "Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.\nA continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].\n Example 1:\nInput: nums = [1,3,5,4,7]\nOutput: 3\nExplanation: The longest continuous increasing subsequence is [1,3,5] with length 3.\nEven though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n4.\nExample 2:\nInput: nums = [2,2,2,2,2]\nOutput: 1\nExplanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\nincreasing.\n Constraints:\n1 <= nums.length <= 104\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/cut-off-trees-for-golf-event/discuss/1204000/Python-normal-and-priority-BFS-faster-than-99-and-faster-than-77", "python_solutions": "class Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n forest.append([0] * len(forest[0]))\n for row in forest: row.append(0)\n def bfs(end, start):\n if end == start: return 0\n visited, queue = set(), {start}\n visited.add(start)\n step = 0\n while queue:\n s = set()\n step += 1\n for p in queue: \n for dr, dc in ((-1, 0), (1, 0), (0, 1), (0, -1)):\n r, c = p[0] + dr, p[1] + dc\n if not forest[r][c] or (r, c) in visited: continue\n if (r, c) == end: return step\n visited.add((r, c))\n s.add((r, c))\n queue = s\n\n trees = [(height, r, c) for r, row in enumerate(forest) for c, height in enumerate(row) if forest[r][c] > 1]\n # check\n queue = [(0, 0)]\n reached = set()\n reached.add((0, 0))\n while queue:\n r, c = queue.pop()\n for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n row, col = r + dr, c + dc\n if forest[row][col] and (row, col) not in reached:\n queue.append((row, col))\n reached.add((row,col))\n if not all([(i, j) in reached for (height, i, j) in trees]): return -1\n trees.sort()\n return sum([bfs((I,J),(i,j)) for (_, i, j), (_, I, J) in zip([(0, 0, 0)] + trees, trees)])", "slug": "cut-off-trees-for-golf-event", "post_title": "Python, normal and priority BFS, faster than 99% and faster than 77%", "user": "dustlihy", "upvotes": 4, "views": 681, "problem_title": "cut off trees for golf event", "number": 675, "acceptance": 0.342, "difficulty": "Hard", "__index_level_0__": 11200, "question": "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:\n0 means the cell cannot be walked through.\n1 represents an empty cell that can be walked through.\nA number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.\nIn one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\nYou must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).\nStarting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.\nNote: The input is generated such that no two trees have the same height, and there is at least one tree needs to be cut off.\n Example 1:\nInput: forest = [[1,2,3],[0,0,4],[7,6,5]]\nOutput: 6\nExplanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\nExample 2:\nInput: forest = [[1,2,3],[0,0,0],[7,6,5]]\nOutput: -1\nExplanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\nExample 3:\nInput: forest = [[2,3,4],[0,0,5],[8,7,6]]\nOutput: 6\nExplanation: You can follow the same path as Example 1 to cut off all the trees.\nNote that you can cut off the first tree at (0, 0) before making any steps.\n Constraints:\nm == forest.length\nn == forest[i].length\n1 <= m, n <= 50\n0 <= forest[i][j] <= 109\nHeights of all trees are distinct." }, { "post_href": "https://leetcode.com/problems/valid-parenthesis-string/discuss/584655/Python-O(n)-by-stack.-85%2B-w-Comment", "python_solutions": "class Solution:\n def checkValidString(self, s: str) -> bool:\n \n # store the indices of '('\n stk = []\n \n # store the indices of '*'\n star = []\n \n \n for idx, char in enumerate(s):\n \n if char == '(':\n stk.append( idx )\n \n elif char == ')':\n \n if stk:\n stk.pop()\n elif star:\n star.pop()\n else:\n return False\n \n else:\n star.append( idx )\n \n \n # cancel ( and * with valid positions, i.e., '(' must be on the left hand side of '*'\n while stk and star:\n if stk[-1] > star[-1]:\n return False\n \n stk.pop()\n star.pop()\n \n \n # Accept when stack is empty, which means all braces are paired\n # Reject, otherwise.\n return len(stk) == 0", "slug": "valid-parenthesis-string", "post_title": "Python O(n) by stack. 85%+ [w/ Comment]", "user": "brianchiang_tw", "upvotes": 23, "views": 813, "problem_title": "valid parenthesis string", "number": 678, "acceptance": 0.3389999999999999, "difficulty": "Medium", "__index_level_0__": 11206, "question": "Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.\nThe following rules define a valid string:\nAny left parenthesis '(' must have a corresponding right parenthesis ')'.\nAny right parenthesis ')' must have a corresponding left parenthesis '('.\nLeft parenthesis '(' must go before the corresponding right parenthesis ')'.\n'*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string \"\".\n Example 1:\nInput: s = \"()\"\nOutput: true\nExample 2:\nInput: s = \"(*)\"\nOutput: true\nExample 3:\nInput: s = \"(*))\"\nOutput: true\n Constraints:\n1 <= s.length <= 100\ns[i] is '(', ')' or '*'." }, { "post_href": "https://leetcode.com/problems/valid-palindrome-ii/discuss/1409641/Python-3-oror-Two-Pointer-Approach-oror-Self-Understandable", "python_solutions": "class Solution:\n def validPalindrome(self, s: str) -> bool:\n p1=0\n p2=len(s)-1\n while p1<=p2:\n if s[p1]!=s[p2]:\n string1=s[:p1]+s[p1+1:]\n string2=s[:p2]+s[p2+1:]\n return string1==string1[::-1] or string2==string2[::-1]\n p1+=1\n p2-=1\n return True", "slug": "valid-palindrome-ii", "post_title": "Python 3 || Two Pointer Approach || Self-Understandable", "user": "bug_buster", "upvotes": 85, "views": 5500, "problem_title": "valid palindrome ii", "number": 680, "acceptance": 0.3929999999999999, "difficulty": "Easy", "__index_level_0__": 11223, "question": "Given a string s, return true if the s can be palindrome after deleting at most one character from it.\n Example 1:\nInput: s = \"aba\"\nOutput: true\nExample 2:\nInput: s = \"abca\"\nOutput: true\nExplanation: You could delete the character 'c'.\nExample 3:\nInput: s = \"abc\"\nOutput: false\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/baseball-game/discuss/380544/Two-Solutions-in-Python-3-(beats-~99)", "python_solutions": "class Solution:\n def calPoints(self, s: List[str]) -> int:\n \tp = []\n \tfor i in s:\n \t\tif i == 'C': p.pop()\n \t\telif i == 'D': p.append(2*p[-1])\n \t\telif i == '+': p.append(p[-1]+p[-2])\n \t\telse: p.append(int(i))\n \treturn sum(p)", "slug": "baseball-game", "post_title": "Two Solutions in Python 3 (beats ~99%)", "user": "junaidmansuri", "upvotes": 7, "views": 928, "problem_title": "baseball game", "number": 682, "acceptance": 0.737, "difficulty": "Easy", "__index_level_0__": 11273, "question": "You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.\nYou are given a list of strings operations, where operations[i] is the ith operation you must apply to the record and is one of the following:\nAn integer x.\nRecord a new score of x.\n'+'.\nRecord a new score that is the sum of the previous two scores.\n'D'.\nRecord a new score that is the double of the previous score.\n'C'.\nInvalidate the previous score, removing it from the record.\nReturn the sum of all the scores on the record after applying all the operations.\nThe test cases are generated such that the answer and all intermediate calculations fit in a 32-bit integer and that all operations are valid.\n Example 1:\nInput: ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\nOutput: 30\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"2\" - Add 2 to the record, record is now [5, 2].\n\"C\" - Invalidate and remove the previous score, record is now [5].\n\"D\" - Add 2 * 5 = 10 to the record, record is now [5, 10].\n\"+\" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].\nThe total sum is 5 + 10 + 15 = 30.\nExample 2:\nInput: ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\nOutput: 27\nExplanation:\n\"5\" - Add 5 to the record, record is now [5].\n\"-2\" - Add -2 to the record, record is now [5, -2].\n\"4\" - Add 4 to the record, record is now [5, -2, 4].\n\"C\" - Invalidate and remove the previous score, record is now [5, -2].\n\"D\" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].\n\"9\" - Add 9 to the record, record is now [5, -2, -4, 9].\n\"+\" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].\n\"+\" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].\nThe total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\nExample 3:\nInput: ops = [\"1\",\"C\"]\nOutput: 0\nExplanation:\n\"1\" - Add 1 to the record, record is now [1].\n\"C\" - Invalidate and remove the previous score, record is now [].\nSince the record is empty, the total sum is 0.\n Constraints:\n1 <= operations.length <= 1000\noperations[i] is \"C\", \"D\", \"+\", or a string representing an integer in the range [-3 * 104, 3 * 104].\nFor operation \"+\", there will always be at least two previous scores on the record.\nFor operations \"C\" and \"D\", there will always be at least one previous score on the record." }, { "post_href": "https://leetcode.com/problems/redundant-connection/discuss/2755933/Python-Union-Find-Easy", "python_solutions": "class Solution(object):\n def findRedundantConnection(self, edges):\n self.parent = dict()\n \n for e in edges:\n \n f0 = self.find(e[0])\n f1 = self.find(e[1])\n if f0 == f1:\n return e\n \n self.parent[f0] = f1\n \n def find(self, x):\n if x not in self.parent:\n return x\n \n return self.find(self.parent[x])", "slug": "redundant-connection", "post_title": "Python - Union Find - Easy", "user": "lokeshsenthilkumar", "upvotes": 1, "views": 8, "problem_title": "redundant connection", "number": 684, "acceptance": 0.62, "difficulty": "Medium", "__index_level_0__": 11323, "question": "In this problem, a tree is an undirected graph that is connected and has no cycles.\nYou are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.\nReturn an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.\n Example 1:\nInput: edges = [[1,2],[1,3],[2,3]]\nOutput: [2,3]\nExample 2:\nInput: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\nOutput: [1,4]\n Constraints:\nn == edges.length\n3 <= n <= 1000\nedges[i].length == 2\n1 <= ai < bi <= edges.length\nai != bi\nThere are no repeated edges.\nThe given graph is connected." }, { "post_href": "https://leetcode.com/problems/repeated-string-match/discuss/330741/Simple-Python3-Solution-(beats-~100)-(my-first-post-on-LeetCode-!!!)", "python_solutions": "class Solution:\n def repeatedStringMatch(self, A: str, B: str) -> int:\n \tif set(B).issubset(set(A)) == False: return -1\n \tfor i in range(1,int(len(B)/len(A))+3):\n \t\tif B in A*i: return i\n \treturn -1\n\t\t\n\t- Python3\n\t- Junaid Mansuri", "slug": "repeated-string-match", "post_title": "Simple Python3 Solution (beats ~100%) (my first post on LeetCode !!!)", "user": "junaidmansuri", "upvotes": 15, "views": 1600, "problem_title": "repeated string match", "number": 686, "acceptance": 0.34, "difficulty": "Medium", "__index_level_0__": 11336, "question": "Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1.\nNotice: string \"abc\" repeated 0 times is \"\", repeated 1 time is \"abc\" and repeated 2 times is \"abcabc\".\n Example 1:\nInput: a = \"abcd\", b = \"cdabcdab\"\nOutput: 3\nExplanation: We return 3 because by repeating a three times \"abcdabcdabcd\", b is a substring of it.\nExample 2:\nInput: a = \"a\", b = \"aa\"\nOutput: 2\n Constraints:\n1 <= a.length, b.length <= 104\na and b consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/longest-univalue-path/discuss/902315/Python3-dfs-(post-order)", "python_solutions": "class Solution:\n def longestUnivaluePath(self, root: TreeNode) -> int:\n \n def dfs(node): \n \"\"\"Return longest univalue branch and longest univalue path (post-order traversal).\"\"\"\n if not node: return 0, 0\n (lx, llup), (rx, rlup) = dfs(node.left), dfs(node.right) \n if not node.left or node.left.val != node.val: lx = 0\n if not node.right or node.right.val != node.val: rx = 0 \n return 1 + max(lx, rx), max(llup, rlup, 1 + lx + rx)\n \n return max(0, dfs(root)[-1]-1)", "slug": "longest-univalue-path", "post_title": "[Python3] dfs (post order)", "user": "ye15", "upvotes": 4, "views": 215, "problem_title": "longest univalue path", "number": 687, "acceptance": 0.402, "difficulty": "Medium", "__index_level_0__": 11345, "question": "Given the root of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.\nThe length of the path between two nodes is represented by the number of edges between them.\n Example 1:\nInput: root = [5,4,5,1,1,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 5).\nExample 2:\nInput: root = [1,4,5,4,4,null,5]\nOutput: 2\nExplanation: The shown image shows that the longest path of the same value (i.e. 4).\n Constraints:\nThe number of nodes in the tree is in the range [0, 104].\n-1000 <= Node.val <= 1000\nThe depth of the tree will not exceed 1000." }, { "post_href": "https://leetcode.com/problems/knight-probability-in-chessboard/discuss/2193242/Python3-DFS-with-DP-beats-99-()()-Explained", "python_solutions": "class Solution:\n def knightProbability(self, n: int, k: int, row0: int, col0: int) -> float:\n\t\n\t\t# precalculate possible moves\n adj_list = defaultdict(list)\n d = ((-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2))\n for row in range(n):\n for col in range(n):\n for dx, dy in d:\n pos = (row + dx, col + dy)\n if 0 <= pos[0] < n and 0 <= pos[1] < n:\n adj_list[(row, col)].append(pos)\n\n @cache\n def get_leafs_num(pos, h):\n if h == k:\n return 1\n \n res = 0\n for next_pos in adj_list[pos]:\n res += get_leafs_num(next_pos, h + 1)\n \n return res \n \n leafs_num = get_leafs_num((row0, col0), 0)\n\n return leafs_num / 8**k", "slug": "knight-probability-in-chessboard", "post_title": "\u2714\ufe0f [Python3] DFS with DP, beats 99% \u0669(\u0e51\uff65\u0e34\u1d17\uff65\u0e34)\u06f6\u0669(\uff65\u0e34\u1d17\uff65\u0e34\u0e51)\u06f6, Explained", "user": "artod", "upvotes": 6, "views": 164, "problem_title": "knight probability in chessboard", "number": 688, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 11351, "question": "On an n x n chessboard, a knight starts at the cell (row, column) and attempts to make exactly k moves. The rows and columns are 0-indexed, so the top-left cell is (0, 0), and the bottom-right cell is (n - 1, n - 1).\nA chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.\nEach time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.\nThe knight continues moving until it has made exactly k moves or has moved off the chessboard.\nReturn the probability that the knight remains on the board after it has stopped moving.\n Example 1:\nInput: n = 3, k = 2, row = 0, column = 0\nOutput: 0.06250\nExplanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\nFrom each of those positions, there are also two moves that will keep the knight on the board.\nThe total probability the knight stays on the board is 0.0625.\nExample 2:\nInput: n = 1, k = 0, row = 0, column = 0\nOutput: 1.00000\n Constraints:\n1 <= n <= 25\n0 <= k <= 100\n0 <= row, column <= n - 1" }, { "post_href": "https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/discuss/1342651/Python3-dp", "python_solutions": "class Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n @cache\n def fn(i, n): \n \"\"\"Return max sum of 3 non-overlapping subarrays.\"\"\"\n if n == 0: return []\n if i+k >= len(prefix): return []\n return max([i] + fn(i+k, n-1), fn(i+1, n), key=lambda x: sum(prefix[xx+k] - prefix[xx] for xx in x))\n \n return fn(0, 3)", "slug": "maximum-sum-of-3-non-overlapping-subarrays", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 1, "views": 73, "problem_title": "maximum sum of 3 non overlapping subarrays", "number": 689, "acceptance": 0.489, "difficulty": "Hard", "__index_level_0__": 11367, "question": "Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.\nReturn the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.\n Example 1:\nInput: nums = [1,2,1,2,6,7,5,1], k = 2\nOutput: [0,3,5]\nExplanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\nWe could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.\nExample 2:\nInput: nums = [1,2,1,2,1,2,1,2,1], k = 2\nOutput: [0,2,4]\n Constraints:\n1 <= nums.length <= 2 * 104\n1 <= nums[i] < 216\n1 <= k <= floor(nums.length / 3)" }, { "post_href": "https://leetcode.com/problems/employee-importance/discuss/332600/Iterative-Python-beats-99.73", "python_solutions": "class Solution:\n def getImportance(self, employees, id):\n \"\"\"\n :type employees: Employee\n :type id: int\n :rtype: int\n \"\"\"\n id_to_emp = {employee.id: employee for employee in employees}\n importance = 0\n stack = [id_to_emp[id]]\n while stack:\n cur_emp = stack.pop()\n importance += cur_emp.importance\n stack.extend([id_to_emp[new_emp] for new_emp in cur_emp.subordinates])\n return importance", "slug": "employee-importance", "post_title": "Iterative Python, beats 99.73%", "user": "hgrsd", "upvotes": 5, "views": 962, "problem_title": "employee importance", "number": 690, "acceptance": 0.652, "difficulty": "Medium", "__index_level_0__": 11373, "question": "You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.\nYou are given an array of employees employees where:\nemployees[i].id is the ID of the ith employee.\nemployees[i].importance is the importance value of the ith employee.\nemployees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.\nGiven an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates.\n Example 1:\nInput: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\nOutput: 11\nExplanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\nThey both have an importance value of 3.\nThus, the total importance value of employee 1 is 5 + 3 + 3 = 11.\nExample 2:\nInput: employees = [[1,2,[5]],[5,-3,[]]], id = 5\nOutput: -3\nExplanation: Employee 5 has an importance value of -3 and has no direct subordinates.\nThus, the total importance value of employee 5 is -3.\n Constraints:\n1 <= employees.length <= 2000\n1 <= employees[i].id <= 2000\nAll employees[i].id are unique.\n-100 <= employees[i].importance <= 100\nOne employee has at most one direct leader and may have several subordinates.\nThe IDs in employees[i].subordinates are valid IDs." }, { "post_href": "https://leetcode.com/problems/stickers-to-spell-word/discuss/1366983/Python3-dp", "python_solutions": "class Solution:\n def minStickers(self, stickers: List[str], target: str) -> int:\n freqs = [Counter(x) for x in stickers]\n \n @cache\n def fn(x):\n \"\"\"Return min sticks to give x.\"\"\"\n if not x: return 0 \n ans = inf\n freq = Counter(x)\n for cnt in freqs: \n if x[0] in cnt: \n xx = \"\".join(k*v for k, v in (freq - cnt).items())\n ans = min(ans, 1 + fn(xx))\n return ans \n \n ans = fn(target)\n return ans if ans < inf else -1", "slug": "stickers-to-spell-word", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 4, "views": 234, "problem_title": "stickers to spell word", "number": 691, "acceptance": 0.4629999999999999, "difficulty": "Hard", "__index_level_0__": 11388, "question": "We are given n different types of stickers. Each sticker has a lowercase English word on it.\nYou would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.\nReturn the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.\nNote: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.\n Example 1:\nInput: stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\nOutput: 3\nExplanation:\nWe can use 2 \"with\" stickers, and 1 \"example\" sticker.\nAfter cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\nAlso, this is the minimum number of stickers necessary to form the target string.\nExample 2:\nInput: stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\nOutput: -1\nExplanation:\nWe cannot form the target \"basicbasic\" from cutting letters from the given stickers.\n Constraints:\nn == stickers.length\n1 <= n <= 50\n1 <= stickers[i].length <= 10\n1 <= target.length <= 15\nstickers[i] and target consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/top-k-frequent-words/discuss/1657648/Simple-or-4-lines-or-using-heap-or-With-explanation", "python_solutions": "class Solution:\n def topKFrequent(self, words: List[str], k: int) -> List[str]:\n #Have a dict of word and its freq\n counts = collections.Counter(words)\n \n #get a array wchich will have a tuple of word and count\n heap = [(-count, word) for word, count in counts.items()]\n \n #as default heap structure in python min heap and we want max heap\n # to get top frequent word, we will do a make the counter negative\n #so that the topmost element will come up (i.e -8 < -2 so in min heap -8 will come up wich is actually 8)\n \n heapq.heapify(heap) #creating heap in place\n #by deualt it will sort by fre then word\n \n return [heapq.heappop(heap)[1] for _ in range(k)]", "slug": "top-k-frequent-words", "post_title": "Simple | 4 lines | using heap | With explanation", "user": "shraddhapp", "upvotes": 25, "views": 2000, "problem_title": "top k frequent words", "number": 692, "acceptance": 0.569, "difficulty": "Medium", "__index_level_0__": 11394, "question": "Given an array of strings words and an integer k, return the k most frequent strings.\nReturn the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.\n Example 1:\nInput: words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\nOutput: [\"i\",\"love\"]\nExplanation: \"i\" and \"love\" are the two most frequent words.\nNote that \"i\" comes before \"love\" due to a lower alphabetical order.\nExample 2:\nInput: words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\nOutput: [\"the\",\"is\",\"sunny\",\"day\"]\nExplanation: \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n Constraints:\n1 <= words.length <= 500\n1 <= words[i].length <= 10\nwords[i] consists of lowercase English letters.\nk is in the range [1, The number of unique words[i]]\n Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?" }, { "post_href": "https://leetcode.com/problems/binary-number-with-alternating-bits/discuss/1095502/Python3-simple-solution", "python_solutions": "class Solution:\n def hasAlternatingBits(self, n: int) -> bool:\n s = bin(n).replace('0b','')\n for i in range(len(s)-1):\n if s[i] == s[i+1]:\n return False\n return True", "slug": "binary-number-with-alternating-bits", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 2, "views": 54, "problem_title": "binary number with alternating bits", "number": 693, "acceptance": 0.613, "difficulty": "Easy", "__index_level_0__": 11432, "question": "Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n Example 1:\nInput: n = 5\nOutput: true\nExplanation: The binary representation of 5 is: 101\nExample 2:\nInput: n = 7\nOutput: false\nExplanation: The binary representation of 7 is: 111.\nExample 3:\nInput: n = 11\nOutput: false\nExplanation: The binary representation of 11 is: 1011.\n Constraints:\n1 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/max-area-of-island/discuss/1459194/python-Simple-and-intuitive-DFS-approach-!!!", "python_solutions": "class Solution:\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n if not grid:\n return 0\n \n maxArea = 0\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1: # run dfs only when we find a land\n maxArea = max(maxArea, self.dfs(grid, i, j))\n \n return maxArea\n \n \n def dfs(self, grid, i, j):\n\t\t# conditions for out of bound and when we encounter water\n if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != 1:\n return 0\n \n maxArea = 1\n grid[i][j] = '#' # this will act as visited set\n maxArea += self.dfs(grid, i+1, j)\n maxArea += self.dfs(grid, i-1, j)\n maxArea += self.dfs(grid, i, j+1)\n maxArea += self.dfs(grid, i, j-1)\n \n return maxArea", "slug": "max-area-of-island", "post_title": "[python] Simple and intuitive DFS approach !!!", "user": "nandanabhishek", "upvotes": 15, "views": 1400, "problem_title": "max area of island", "number": 695, "acceptance": 0.7170000000000001, "difficulty": "Medium", "__index_level_0__": 11454, "question": "You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.\nThe area of an island is the number of cells with a value 1 in the island.\nReturn the maximum area of an island in grid. If there is no island, return 0.\n Example 1:\nInput: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]\nOutput: 6\nExplanation: The answer is not 11, because the island must be connected 4-directionally.\nExample 2:\nInput: grid = [[0,0,0,0,0,0,0,0]]\nOutput: 0\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 50\ngrid[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/count-binary-substrings/discuss/384054/Only-using-stack-with-one-iteration-logic-solution-in-Python-O(N)", "python_solutions": "class Solution:\n def countBinarySubstrings(self, s: str) -> int:\n stack = [[], []]\n latest = int(s[0])\n stack[latest].append(latest)\n result = 0\n for i in range(1,len(s)):\n v = int(s[i])\n if v != latest:\n stack[v].clear()\n latest = v\n stack[v].append(v)\n if len(stack[1-v]) > 0:\n stack[1-v].pop()\n result += 1\n return result", "slug": "count-binary-substrings", "post_title": "Only using stack with one iteration, logic solution in Python O(N)", "user": "zouqiwu09", "upvotes": 7, "views": 994, "problem_title": "count binary substrings", "number": 696, "acceptance": 0.6559999999999999, "difficulty": "Easy", "__index_level_0__": 11505, "question": "Given a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.\nSubstrings that occur multiple times are counted the number of times they occur.\n Example 1:\nInput: s = \"00110011\"\nOutput: 6\nExplanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\nNotice that some of these substrings repeat and are counted the number of times they occur.\nAlso, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\nExample 2:\nInput: s = \"10101\"\nOutput: 4\nExplanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n Constraints:\n1 <= s.length <= 105\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/degree-of-an-array/discuss/349801/Solution-in-Python-3-(beats-~98)", "python_solutions": "class Solution:\n def findShortestSubArray(self, nums: List[int]) -> int:\n \tC = {}\n \tfor i, n in enumerate(nums):\n \t\tif n in C: C[n].append(i)\n \t\telse: C[n] = [i]\n \tM = max([len(i) for i in C.values()])\n \treturn min([i[-1]-i[0] for i in C.values() if len(i) == M]) + 1\n\t\t\n\t\t\n- Junaid Mansuri", "slug": "degree-of-an-array", "post_title": "Solution in Python 3 (beats ~98%)", "user": "junaidmansuri", "upvotes": 43, "views": 3000, "problem_title": "degree of an array", "number": 697, "acceptance": 0.5589999999999999, "difficulty": "Easy", "__index_level_0__": 11520, "question": "Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.\nYour task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.\n Example 1:\nInput: nums = [1,2,2,3,1]\nOutput: 2\nExplanation: \nThe input array has a degree of 2 because both elements 1 and 2 appear twice.\nOf the subarrays that have the same degree:\n[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]\nThe shortest length is 2. So return 2.\nExample 2:\nInput: nums = [1,2,2,3,1,4,2]\nOutput: 6\nExplanation: \nThe degree is 3 because the element 2 is repeated 3 times.\nSo [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n Constraints:\nnums.length will be between 1 and 50,000.\nnums[i] will be an integer between 0 and 49,999." }, { "post_href": "https://leetcode.com/problems/partition-to-k-equal-sum-subsets/discuss/1627241/python-simple-with-detailed-explanation-or-96.13", "python_solutions": "class Solution:\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n if k==1:\n return True\n total = sum(nums)\n n = len(nums)\n if total%k!=0:\n return False\n nums.sort(reverse=True)\n average = total//k\n if nums[0]>average:\n return False\n \n visited = [False]*n\n def dfs(cur, begin, k):\n if k==0:\n return True\n if cur>average:\n return False\n elif cur==average:\n return dfs(0, 0, k-1)\n for i in range(begin, n):\n if not visited[i]:\n visited[i] = True\n if dfs(cur + nums[i], i+1, k):\n return True\n visited[i] = False\n return False\n \n return dfs(0, 0, k)", "slug": "partition-to-k-equal-sum-subsets", "post_title": "python simple with detailed explanation | 96.13%", "user": "1579901970cg", "upvotes": 5, "views": 563, "problem_title": "partition to k equal sum subsets", "number": 698, "acceptance": 0.408, "difficulty": "Medium", "__index_level_0__": 11531, "question": "Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.\n Example 1:\nInput: nums = [4,3,2,3,5,2,1], k = 4\nOutput: true\nExplanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\nExample 2:\nInput: nums = [1,2,3,4], k = 3\nOutput: false\n Constraints:\n1 <= k <= nums.length <= 16\n1 <= nums[i] <= 104\nThe frequency of each element is in the range [1, 4]." }, { "post_href": "https://leetcode.com/problems/falling-squares/discuss/2397036/faster-than-90.37-or-python-or-solution-or-explained", "python_solutions": "class Solution:\n def fallingSquares(self, positions):\n height, pos, max_h,res = [0],[0],0,[]\n for left, side in positions:\n i = bisect.bisect_right(pos, left)\n j = bisect.bisect_left(pos, left + side)\n high = max(height[i - 1:j] or [0]) + side \n pos[i:j] = [left, left + side]\n height[i:j] = [high, height[j - 1]]\n max_h = max(max_h, high)\n res.append(max_h)\n return res", "slug": "falling-squares", "post_title": "faster than 90.37% | python | solution | explained", "user": "vimla_kushwaha", "upvotes": 1, "views": 57, "problem_title": "falling squares", "number": 699, "acceptance": 0.444, "difficulty": "Hard", "__index_level_0__": 11556, "question": "There are several squares being dropped onto the X-axis of a 2D plane.\nYou are given a 2D integer array positions where positions[i] = [lefti, sideLengthi] represents the ith square with a side length of sideLengthi that is dropped with its left edge aligned with X-coordinate lefti.\nEach square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands on the top side of another square or on the X-axis. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.\nAfter each square is dropped, you must record the height of the current tallest stack of squares.\nReturn an integer array ans where ans[i] represents the height described above after dropping the ith square.\n Example 1:\nInput: positions = [[1,2],[2,3],[6,1]]\nOutput: [2,5,5]\nExplanation:\nAfter the first drop, the tallest stack is square 1 with a height of 2.\nAfter the second drop, the tallest stack is squares 1 and 2 with a height of 5.\nAfter the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\nThus, we return an answer of [2, 5, 5].\nExample 2:\nInput: positions = [[100,100],[200,100]]\nOutput: [100,100]\nExplanation:\nAfter the first drop, the tallest stack is square 1 with a height of 100.\nAfter the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\nThus, we return an answer of [100, 100].\nNote that square 2 only brushes the right side of square 1, which does not count as landing on it.\n Constraints:\n1 <= positions.length <= 1000\n1 <= lefti <= 108\n1 <= sideLengthi <= 106" }, { "post_href": "https://leetcode.com/problems/search-in-a-binary-search-tree/discuss/943397/Python-Simple-Solution", "python_solutions": "class Solution:\n def searchBST(self, root: TreeNode, val: int) -> TreeNode:\n if not root:\n return\n if root.val==val:\n return root\n if root.val Optional[TreeNode]:\n if not root: return TreeNode(val)\n \n cur, next = None, root\n while next:\n cur = next\n next = cur.left if val < cur.val else cur.right\n \n if val < cur.val: \n cur.left = TreeNode(val)\n else: \n cur.right = TreeNode(val)\n \n return root", "slug": "insert-into-a-binary-search-tree", "post_title": "\u2714\ufe0f [Python3] ITERATIVE (\u3065\uffe3 \u00b3\uffe3)\u3065 \u2764, Explained", "user": "artod", "upvotes": 26, "views": 1300, "problem_title": "insert into a binary search tree", "number": 701, "acceptance": 0.746, "difficulty": "Medium", "__index_level_0__": 11594, "question": "You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.\nNotice that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.\n Example 1:\nInput: root = [4,2,7,1,3], val = 5\nOutput: [4,2,7,1,3,5]\nExplanation: Another accepted tree is:\nExample 2:\nInput: root = [40,20,60,10,30,50,70], val = 25\nOutput: [40,20,60,10,30,50,70,null,null,25]\nExample 3:\nInput: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\nOutput: [4,2,7,1,3,5]\n Constraints:\nThe number of nodes in the tree will be in the range [0, 104].\n-108 <= Node.val <= 108\nAll the values Node.val are unique.\n-108 <= val <= 108\nIt's guaranteed that val does not exist in the original BST." }, { "post_href": "https://leetcode.com/problems/binary-search/discuss/2700642/Python-Classic-Binary-Search-Problem-or-99-Faster-or-Fastest-Solution", "python_solutions": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums)-1\n \n while left<=right:\n mid = (left+right)//2\n if nums[mid]==target:\n return mid\n elif nums[mid]>target:\n right = mid-1\n else:\n left = mid+1\n \n return -1", "slug": "binary-search", "post_title": "\u2714\ufe0f Python Classic Binary Search Problem | 99% Faster | Fastest Solution", "user": "pniraj657", "upvotes": 47, "views": 6000, "problem_title": "binary search", "number": 704, "acceptance": 0.551, "difficulty": "Easy", "__index_level_0__": 11628, "question": "Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.\nYou must write an algorithm with O(log n) runtime complexity.\n Example 1:\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\nExample 2:\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n Constraints:\n1 <= nums.length <= 104\n-104 < nums[i], target < 104\nAll the integers in nums are unique.\nnums is sorted in ascending order." }, { "post_href": "https://leetcode.com/problems/design-hashset/discuss/1947672/Python3-Linked-List-Solution-(faster-than-83)", "python_solutions": "# Linked List Solution\nclass MyHashSet(object):\n \n def __init__(self):\n self.keyRange = 769\n self.bucketArray = [LinkedList() for i in range(self.keyRange)]\n \n def _hash(self, key):\n return key % self.keyRange\n \n def add(self, key):\n bucketIndex = self._hash(key)\n self.bucketArray[bucketIndex].append(key)\n \n def remove(self, key):\n bucketIndex = self._hash(key)\n self.bucketArray[bucketIndex].deleteNodeKeyAll(key)\n # while self.bucketArray[bucketIndex].search(key):\n # self.bucketArray[bucketIndex].deleteNodeKeyOne(key)\n \n def contains(self, key):\n bucketIndex = self._hash(key)\n return self.bucketArray[bucketIndex].search(key)\n \n# ---------------------------------------------------------\n## Define a linked list\n\nclass Node:\n \n def __init__(self, val, next = None):\n self.val = val\n self.next = next\n \nclass LinkedList:\n \n def __init__(self):\n self.head = None\n\n# ---------------------------------------------------------\n## Insert a new node\n\n### Insert the new node at the front of the linked list\n def push(self, new_val):\n new_node = Node(new_val)\n new_node.next = self.head\n self.head = new_node\n \n### Insert the new node at the end of the linked list\n def append(self, new_val):\n new_node = Node(new_val)\n if self.head is None:\n self.head = new_node\n return\n # Traverse till the end of the linked list\n last = self.head\n while last.next:\n last = last.next\n last.next = new_node\n\n### Insert the new node after a given node\n def insertAfter(self, new_val, prev_node):\n if prev_node is None:\n print(\"Please enter the node which is the previous node of the inserted node.\")\n return\n new_node = Node(new_val)\n new_node.next = prev_node.next\n prev_node.next = new_node\n \n# ---------------------------------------------------------\n## Delete a node\n\n### Delete a node by value\n# Iterative Method\n def deleteNodeKeyOne(self, key): # delete a single node\n temp = self.head\n if temp is None:\n return\n if temp.val == key:\n self.head = temp.next\n temp = None\n return\n while temp is not None:\n if temp.val == key:\n break\n prev = temp\n temp = temp.next\n if temp is None:\n return\n prev.next = temp.next\n temp = None\n \n def deleteNodeKeyAll(self, key): # delete all the nodes with value key\n temp = self.head\n if temp is None:\n return\n while temp.val == key:\n deletedNode = temp\n self.head = temp.next\n temp = self.head\n deletedNode = None\n if temp is None:\n return\n nxt = temp.next\n while nxt is not None:\n if nxt.val == key:\n deletedNode = nxt\n temp.next = nxt.next\n deletedNode = None\n temp = nxt\n nxt = nxt.next\n\n### Delete a node by position and return the value of the deleted node\n def deleteNodePosition(self, position):\n if self.head is None:\n return\n if position == 0:\n temp = self.head\n self.head = self.head.next\n temp = None\n return\n idx = 0\n current = self.head\n prev = self.head\n nxt = self.head\n while current is not None:\n if idx == position:\n nxt = current.next\n break\n prev = current\n current = current.next\n idx += 1\n prev.next = nxt\n current = None\n \n# ---------------------------------------------------------\n# Print a linked list\n def printList(self):\n temp = self.head\n while temp:\n print (\" %d\" %(temp.val))\n temp = temp.next\n\n# ---------------------------------------------------------\n## Search an element in a linked list\n def search(self, x):\n current = self.head\n while current is not None:\n if current.val == x:\n return True\n current = current.next\n return False", "slug": "design-hashset", "post_title": "Python3 Linked List Solution (faster than 83%)", "user": "Mr_Watermelon", "upvotes": 0, "views": 105, "problem_title": "design hashset", "number": 705, "acceptance": 0.659, "difficulty": "Easy", "__index_level_0__": 11682, "question": "Design a HashSet without using any built-in hash table libraries.\nImplement MyHashSet class:\nvoid add(key) Inserts the value key into the HashSet.\nbool contains(key) Returns whether the value key exists in the HashSet or not.\nvoid remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.\n Example 1:\nInput\n[\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n[[], [1], [2], [1], [3], [2], [2], [2], [2]]\nOutput\n[null, null, null, true, false, null, true, null, false]\n\nExplanation\nMyHashSet myHashSet = new MyHashSet();\nmyHashSet.add(1); // set = [1]\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(1); // return True\nmyHashSet.contains(3); // return False, (not found)\nmyHashSet.add(2); // set = [1, 2]\nmyHashSet.contains(2); // return True\nmyHashSet.remove(2); // set = [1]\nmyHashSet.contains(2); // return False, (already removed)\n Constraints:\n0 <= key <= 106\nAt most 104 calls will be made to add, remove, and contains." }, { "post_href": "https://leetcode.com/problems/to-lower-case/discuss/2411462/Python3-ToLowerCase-Explanation-using-ASCII", "python_solutions": "class Solution:\n def toLowerCase(self, s: str) -> str:\n # Instead of using .lower(), let's implement with ASCII\n # ord() returns the ascii value of a passed character\n \n # Uncomment the line below to see the ASCII value of some important characters\n # print(ord('a'), ord('z'), ord('A'), ord('Z'))\n \n # Notice 'a'=97, and 'A'=65\n # This can be used to tell whether a character is upper/lower case, and can help us convert between them\n \n # First, make the string a list so we can change each char individually\n s = list(s)\n \n # Then, loop through the characters, and if their ascii value is <= 90 and >= 65, they must be upper case\n # Use the difference (97 - 65 = 32) to convert it from upper to lower, then use chr() to convert from ascii to char\n # - ord('A') + 32 = 97 = ord('a')\n for i in range(len(s)):\n if ord(s[i]) <= 90 and ord(s[i]) >= 65:\n s[i] = chr(ord(s[i])+32)\n return ''.join(s)", "slug": "to-lower-case", "post_title": "[Python3] ToLowerCase - Explanation - using ASCII", "user": "connorthecrowe", "upvotes": 2, "views": 84, "problem_title": "to lower case", "number": 709, "acceptance": 0.82, "difficulty": "Easy", "__index_level_0__": 11684, "question": "Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.\n Example 1:\nInput: s = \"Hello\"\nOutput: \"hello\"\nExample 2:\nInput: s = \"here\"\nOutput: \"here\"\nExample 3:\nInput: s = \"LOVELY\"\nOutput: \"lovely\"\n Constraints:\n1 <= s.length <= 100\ns consists of printable ASCII characters." }, { "post_href": "https://leetcode.com/problems/random-pick-with-blacklist/discuss/2389935/faster-than-99.73-or-Python3-or-solution", "python_solutions": "class Solution:\n\n def __init__(self, n: int, blacklist: List[int]):\n self.hashmap={}\n for b in blacklist:\n self.hashmap[b]=-1\n self.length=n-len(blacklist)\n flag=n-1\n for b in blacklist:\n if b int:\n seed=random.randrange(self.length)\n return self.hashmap.get(seed,seed)\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(n, blacklist)\n# param_1 = obj.pick()", "slug": "random-pick-with-blacklist", "post_title": "faster than 99.73% | Python3 | solution", "user": "vimla_kushwaha", "upvotes": 1, "views": 152, "problem_title": "random pick with blacklist", "number": 710, "acceptance": 0.337, "difficulty": "Hard", "__index_level_0__": 11729, "question": "You are given an integer n and an array of unique integers blacklist. Design an algorithm to pick a random integer in the range [0, n - 1] that is not in blacklist. Any integer that is in the mentioned range and not in blacklist should be equally likely to be returned.\nOptimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.\nImplement the Solution class:\nSolution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist.\nint pick() Returns a random integer in the range [0, n - 1] and not in blacklist.\n Example 1:\nInput\n[\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n[[7, [2, 3, 5]], [], [], [], [], [], [], []]\nOutput\n[null, 0, 4, 1, 6, 1, 0, 4]\n\nExplanation\nSolution solution = new Solution(7, [2, 3, 5]);\nsolution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick,\n // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4).\nsolution.pick(); // return 4\nsolution.pick(); // return 1\nsolution.pick(); // return 6\nsolution.pick(); // return 1\nsolution.pick(); // return 0\nsolution.pick(); // return 4\n Constraints:\n1 <= n <= 109\n0 <= blacklist.length <= min(105, n - 1)\n0 <= blacklist[i] < n\nAll the values of blacklist are unique.\nAt most 2 * 104 calls will be made to pick." }, { "post_href": "https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/discuss/1516574/Greedy-oror-DP-oror-Same-as-LCS", "python_solutions": "class Solution:\ndef minimumDeleteSum(self, s1: str, s2: str) -> int:\n \n def lcs(s,p):\n m,n = len(s),len(p)\n dp = [[0 for _ in range(n+1)] for _ in range(m+1)]\n for i in range(m):\n for j in range(n):\n if s[i]==p[j]:\n dp[i+1][j+1] = dp[i][j]+ord(s[i])\n else:\n dp[i+1][j+1] = max(dp[i+1][j],dp[i][j+1])\n \n return dp[-1][-1]\n \n common = lcs(s1,s2)\n total,res = 0,0\n for c in s1:\n total+=ord(c)\n for c in s2:\n total+=ord(c)\n \n res = total - common*2\n return res", "slug": "minimum-ascii-delete-sum-for-two-strings", "post_title": "\ud83d\udccc\ud83d\udccc Greedy || DP || Same as LCS \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 4, "views": 94, "problem_title": "minimum ascii delete sum for two strings", "number": 712, "acceptance": 0.623, "difficulty": "Medium", "__index_level_0__": 11736, "question": "Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.\n Example 1:\nInput: s1 = \"sea\", s2 = \"eat\"\nOutput: 231\nExplanation: Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\nDeleting \"t\" from \"eat\" adds 116 to the sum.\nAt the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\nExample 2:\nInput: s1 = \"delete\", s2 = \"leet\"\nOutput: 403\nExplanation: Deleting \"dee\" from \"delete\" to turn the string into \"let\",\nadds 100[d] + 101[e] + 101[e] to the sum.\nDeleting \"e\" from \"leet\" adds 101[e] to the sum.\nAt the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\nIf instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which are higher.\n Constraints:\n1 <= s1.length, s2.length <= 1000\ns1 and s2 consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/subarray-product-less-than-k/discuss/481917/Python-sol.-based-on-sliding-window.-run-time-90%2B-w-Explanation", "python_solutions": "class Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n \n if k <= 1:\n # Quick response for invalid k on product of positive numbers\n return 0\n \n else:\n left_sentry = 0\n\n num_of_subarray = 0\n product_of_subarry = 1\n\n # update right bound of sliding window\n for right_sentry in range( len(nums) ):\n\n product_of_subarry *= nums[right_sentry]\n\n # update left bound of sliding window\n while product_of_subarry >= k:\n product_of_subarry //= nums[left_sentry]\n left_sentry += 1\n\n # Note:\n # window size = right_sentry - left_sentry + 1\n\n # update number of subarrary with product < k\n num_of_subarray += right_sentry - left_sentry + 1\n\n return num_of_subarray", "slug": "subarray-product-less-than-k", "post_title": "Python sol. based on sliding window. run-time 90%+ [ w/ Explanation ]", "user": "brianchiang_tw", "upvotes": 3, "views": 723, "problem_title": "subarray product less than k", "number": 713, "acceptance": 0.452, "difficulty": "Medium", "__index_level_0__": 11743, "question": "Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.\n Example 1:\nInput: nums = [10,5,2,6], k = 100\nOutput: 8\nExplanation: The 8 subarrays that have product less than 100 are:\n[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\nNote that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\nExample 2:\nInput: nums = [1,2,3], k = 0\nOutput: 0\n Constraints:\n1 <= nums.length <= 3 * 104\n1 <= nums[i] <= 1000\n0 <= k <= 106" }, { "post_href": "https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/1532323/Python3-dp", "python_solutions": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n buy, sell = inf, 0\n for x in prices:\n buy = min(buy, x)\n sell = max(sell, x - buy)\n return sell", "slug": "best-time-to-buy-and-sell-stock-with-transaction-fee", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 4, "views": 78, "problem_title": "best time to buy and sell stock with transaction fee", "number": 714, "acceptance": 0.644, "difficulty": "Medium", "__index_level_0__": 11758, "question": "You are given an array prices where prices[i] is the price of a given stock on the ith day, and an integer fee representing a transaction fee.\nFind the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.\nNote:\nYou may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\nThe transaction fee is only charged once for each stock purchase and sale.\n Example 1:\nInput: prices = [1,3,2,8,4,9], fee = 2\nOutput: 8\nExplanation: The maximum profit can be achieved by:\n- Buying at prices[0] = 1\n- Selling at prices[3] = 8\n- Buying at prices[4] = 4\n- Selling at prices[5] = 9\nThe total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\nExample 2:\nInput: prices = [1,3,7,5,10,3], fee = 3\nOutput: 6\n Constraints:\n1 <= prices.length <= 5 * 104\n1 <= prices[i] < 5 * 104\n0 <= fee < 5 * 104" }, { "post_href": "https://leetcode.com/problems/1-bit-and-2-bit-characters/discuss/2012976/Python-Clean-and-Simple!", "python_solutions": "class Solution:\n def isOneBitCharacter(self, bits):\n i, n, numBits = 0, len(bits), 0\n while i < n:\n bit = bits[i]\n if bit == 1:\n i += 2\n numBits = 2\n else:\n i += 1\n numBits = 1\n return numBits == 1", "slug": "1-bit-and-2-bit-characters", "post_title": "Python - Clean and Simple!", "user": "domthedeveloper", "upvotes": 2, "views": 146, "problem_title": "1 bit and 2 bit characters", "number": 717, "acceptance": 0.46, "difficulty": "Easy", "__index_level_0__": 11781, "question": "We have two special characters:\nThe first character can be represented by one bit 0.\nThe second character can be represented by two bits (10 or 11).\nGiven a binary array bits that ends with 0, return true if the last character must be a one-bit character.\n Example 1:\nInput: bits = [1,0,0]\nOutput: true\nExplanation: The only way to decode it is two-bit character and one-bit character.\nSo the last character is one-bit character.\nExample 2:\nInput: bits = [1,1,1,0]\nOutput: false\nExplanation: The only way to decode it is two-bit character and two-bit character.\nSo the last character is not one-bit character.\n Constraints:\n1 <= bits.length <= 1000\nbits[i] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/maximum-length-of-repeated-subarray/discuss/2599501/LeetCode-The-Hard-Way-Explained-Line-By-Line", "python_solutions": "class Solution:\n # DP Approach - Similar to 1143. Longest Common Subsequence\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n n, m = len(nums1), len(nums2)\n # dp[i][j] means the length of repeated subarray of nums1[:i] and nums2[:j]\n dp = [[0] * (m + 1) for _ in range(n + 1)]\n ans = 0\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n # if both character is same\n if nums1[i - 1] == nums2[j - 1]:\n # then we add 1 to the previous state, which is dp[i - 1][j - 1]\n # in other word, we extend the repeated subarray by 1\n # e.g. a = [1], b = [1], length of repeated array is 1\n # a = [1,2], b = [1,2], length of repeated array is the previous result + 1 = 2\n dp[i][j] = dp[i - 1][j - 1] + 1\n # record the max ans here\n ans = max(ans, dp[i][j])\n # else:\n # if you are looking for longest common sequence,\n # then you put dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); here\n # however, this problem is looking for subarray,\n # since both character is not equal, which means we need to break it here\n # hence, set dp[i][j] to 0\n return ans", "slug": "maximum-length-of-repeated-subarray", "post_title": "\ud83d\udd25 [LeetCode The Hard Way] \ud83d\udd25 Explained Line By Line", "user": "wingkwong", "upvotes": 32, "views": 2000, "problem_title": "maximum length of repeated subarray", "number": 718, "acceptance": 0.515, "difficulty": "Medium", "__index_level_0__": 11796, "question": "Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.\n Example 1:\nInput: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\nOutput: 3\nExplanation: The repeated subarray with maximum length is [3,2,1].\nExample 2:\nInput: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\nOutput: 5\nExplanation: The repeated subarray with maximum length is [0,0,0,0,0].\n Constraints:\n1 <= nums1.length, nums2.length <= 1000\n0 <= nums1[i], nums2[i] <= 100" }, { "post_href": "https://leetcode.com/problems/find-k-th-smallest-pair-distance/discuss/2581420/Simple-python-binary-search", "python_solutions": "class Solution:\n\tdef smallestDistancePair(self, nums: List[int], k: int) -> int:\n\n\t\tdef getPairs(diff):\n\t\t\tl = 0\n\t\t\tcount = 0\n\n\t\t\tfor r in range(len(nums)):\n\t\t\t\twhile nums[r] - nums[l] > diff:\n\t\t\t\t\tl += 1\n\t\t\t\tcount += r - l\n\n\t\t\treturn count\n\n\n\t\tnums.sort()\n\t\tl, r = 0, nums[-1] - nums[0]\n\n\t\twhile l < r:\n\t\t\tmid = (l + r) // 2\n\t\t\tres = getPairs(mid)\n\n\t\t\tif res >= k:\n\t\t\t\tr = mid\n\t\t\telse:\n\t\t\t\tl = mid + 1\n\n\t\treturn l", "slug": "find-k-th-smallest-pair-distance", "post_title": "Simple python binary search", "user": "shubhamnishad25", "upvotes": 1, "views": 123, "problem_title": "find k th smallest pair distance", "number": 719, "acceptance": 0.364, "difficulty": "Hard", "__index_level_0__": 11831, "question": "The distance of a pair of integers a and b is defined as the absolute difference between a and b.\nGiven an integer array nums and an integer k, return the kth smallest distance among all the pairs nums[i] and nums[j] where 0 <= i < j < nums.length.\n Example 1:\nInput: nums = [1,3,1], k = 1\nOutput: 0\nExplanation: Here are all the pairs:\n(1,3) -> 2\n(1,1) -> 0\n(3,1) -> 2\nThen the 1st smallest distance pair is (1,1), and its distance is 0.\nExample 2:\nInput: nums = [1,1,1], k = 2\nOutput: 0\nExample 3:\nInput: nums = [1,6,1], k = 3\nOutput: 5\n Constraints:\nn == nums.length\n2 <= n <= 104\n0 <= nums[i] <= 106\n1 <= k <= n * (n - 1) / 2" }, { "post_href": "https://leetcode.com/problems/longest-word-in-dictionary/discuss/2075147/Python-O(n-log(n))-Time-O(n)-Space-Faster-Than-95", "python_solutions": "class Solution:\n def longestWord(self, words: List[str]) -> str:\n words.sort() # for smallest lexicographical order\n visited = {\"\"} # hashset to keep a track of visited words\n res = ''\n \n for word in words:\n if word[:-1] in visited: # check previous word ie. word[:len(word)-1] visited or not\n visited.add(word) # add this word to the set\n if len(word) > len(res): # current word have greater lenght and lexicographically smaller\n res = word # update res\n \n return res\n \n \n \n# Time: O(n log(n)) # for sorting the words\n# Space: O(n) # for making the set visited", "slug": "longest-word-in-dictionary", "post_title": "[Python] O(n log(n)) Time, O(n) Space Faster Than 95%", "user": "samirpaul1", "upvotes": 4, "views": 217, "problem_title": "longest word in dictionary", "number": 720, "acceptance": 0.518, "difficulty": "Medium", "__index_level_0__": 11834, "question": "Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.\nIf there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.\nNote that the word should be built from left to right with each additional character being added to the end of a previous word. \n Example 1:\nInput: words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\nOutput: \"world\"\nExplanation: The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\nExample 2:\nInput: words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\nOutput: \"apple\"\nExplanation: Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".\n Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length <= 30\nwords[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/accounts-merge/discuss/2014051/Python-easy-to-read-and-understand-or-DFS", "python_solutions": "class Solution:\n def dfs(self, graph, node, visit):\n visit.add(node)\n for nei in graph[node]:\n if nei not in visit:\n self.dfs(graph, nei, visit)\n self.res.append(node)\n \n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n graph = collections.defaultdict(set)\n for account in accounts:\n for email in account[1:]:\n graph[account[1]].add(email)\n graph[email].add(account[1])\n #print(graph.items())\n \n visit = set()\n ans = []\n for account in accounts:\n name = account[0]\n for email in account[1:]:\n if email not in visit:\n self.res = []\n self.dfs(graph, email, visit)\n ans.append([name]+sorted(self.res))\n return ans", "slug": "accounts-merge", "post_title": "Python easy to read and understand | DFS", "user": "sanial2001", "upvotes": 7, "views": 507, "problem_title": "accounts merge", "number": 721, "acceptance": 0.564, "difficulty": "Medium", "__index_level_0__": 11844, "question": "Given a list of accounts where each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emails representing emails of the account.\nNow, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.\nAfter merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.\n Example 1:\nInput: accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nOutput: [[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\nExplanation:\nThe first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\nThe third John and Mary are different people as none of their email addresses are used by other accounts.\nWe could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.\nExample 2:\nInput: accounts = [[\"Gabe\",\"Gabe0@m.co\",\"Gabe3@m.co\",\"Gabe1@m.co\"],[\"Kevin\",\"Kevin3@m.co\",\"Kevin5@m.co\",\"Kevin0@m.co\"],[\"Ethan\",\"Ethan5@m.co\",\"Ethan4@m.co\",\"Ethan0@m.co\"],[\"Hanzo\",\"Hanzo3@m.co\",\"Hanzo1@m.co\",\"Hanzo0@m.co\"],[\"Fern\",\"Fern5@m.co\",\"Fern1@m.co\",\"Fern0@m.co\"]]\nOutput: [[\"Ethan\",\"Ethan0@m.co\",\"Ethan4@m.co\",\"Ethan5@m.co\"],[\"Gabe\",\"Gabe0@m.co\",\"Gabe1@m.co\",\"Gabe3@m.co\"],[\"Hanzo\",\"Hanzo0@m.co\",\"Hanzo1@m.co\",\"Hanzo3@m.co\"],[\"Kevin\",\"Kevin0@m.co\",\"Kevin3@m.co\",\"Kevin5@m.co\"],[\"Fern\",\"Fern0@m.co\",\"Fern1@m.co\",\"Fern5@m.co\"]]\n Constraints:\n1 <= accounts.length <= 1000\n2 <= accounts[i].length <= 10\n1 <= accounts[i][j].length <= 30\naccounts[i][0] consists of English letters.\naccounts[i][j] (for j > 0) is a valid email." }, { "post_href": "https://leetcode.com/problems/remove-comments/discuss/2446606/Easy-to-understand-using-Python", "python_solutions": "class Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n ans, inComment = [], False\n new_str = \"\"\n for c in source:\n if not inComment: new_str = \"\"\n i, n = 0, len(c)\n # inComment, we find */\n while i < n:\n if inComment:\n if c[i:i + 2] == '*/' and i + 1 < n:\n i += 2\n inComment = False\n continue\n i += 1\n # not in Comment, we find /* // and common character\n else:\n if c[i:i + 2] == '/*' and i + 1 < n:\n i += 2\n inComment = True\n continue\n if c[i:i + 2] == '//' and i + 1 < n:\n break\n new_str += c[i]\n i += 1\n if new_str and not inComment:\n ans.append(new_str)\n \n\n return ans", "slug": "remove-comments", "post_title": "Easy to understand using Python", "user": "fguo10", "upvotes": 3, "views": 567, "problem_title": "remove comments", "number": 722, "acceptance": 0.38, "difficulty": "Medium", "__index_level_0__": 11857, "question": "Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith line of the source code. This represents the result of splitting the original source code string by the newline character '\\n'.\nIn C++, there are two types of comments, line comments, and block comments.\nThe string \"//\" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.\nThe string \"/*\" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of \"*/\" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string \"/*/\" does not yet end the block comment, as the ending would be overlapping the beginning.\nThe first effective comment takes precedence over others.\nFor example, if the string \"//\" occurs in a block comment, it is ignored.\nSimilarly, if the string \"/*\" occurs in a line or block comment, it is also ignored.\nIf a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.\nThere will be no control characters, single quote, or double quote characters.\nFor example, source = \"string s = \"/* Not a comment. */\";\" will not be a test case.\nAlso, nothing else such as defines or macros will interfere with the comments.\nIt is guaranteed that every open block comment will eventually be closed, so \"/*\" outside of a line or block comment always starts a new comment.\nFinally, implicit newline characters can be deleted by block comments. Please see the examples below for details.\nAfter removing the comments from the source code, return the source code in the same format.\n Example 1:\nInput: source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]\nOutput: [\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]\nExplanation: The line by line code is visualized as below:\n/*Test program */\nint main()\n{ \n // variable declaration \nint a, b, c;\n/* This is a test\n multiline \n comment for \n testing */\na = b + c;\n}\nThe string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\nThe line by line output code is visualized as below:\nint main()\n{ \n \nint a, b, c;\na = b + c;\n}\nExample 2:\nInput: source = [\"a/*comment\", \"line\", \"more_comment*/b\"]\nOutput: [\"ab\"]\nExplanation: The original source string is \"a/*comment\\nline\\nmore_comment*/b\", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string \"ab\", which when delimited by newline characters becomes [\"ab\"].\n Constraints:\n1 <= source.length <= 100\n0 <= source[i].length <= 80\nsource[i] consists of printable ASCII characters.\nEvery open block comment is eventually closed.\nThere are no single-quote or double-quote in the input." }, { "post_href": "https://leetcode.com/problems/find-pivot-index/discuss/2321669/Python-99.85-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Prefix-Sum", "python_solutions": "class Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]\n right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]\n\n for i, num in enumerate(nums): # we can use normal for loop as well.\n right -= num # as we are trying to find out pivot index so iteratively we`ll reduce the value of right to find the pivot index\n if left == right: # comparing the values for finding out the pivot index.\n return i # if there is any return the index whixh will be our required index.\n left += num # we have to add the num iteratively. \n\n return -1", "slug": "find-pivot-index", "post_title": "Python 99.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum", "user": "rlakshay14", "upvotes": 9, "views": 725, "problem_title": "find pivot index", "number": 724, "acceptance": 0.535, "difficulty": "Easy", "__index_level_0__": 11865, "question": "Given an array of integers nums, calculate the pivot index of this array.\nThe pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right.\nIf the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array.\nReturn the leftmost pivot index. If no such index exists, return -1.\n Example 1:\nInput: nums = [1,7,3,6,5,6]\nOutput: 3\nExplanation:\nThe pivot index is 3.\nLeft sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\nRight sum = nums[4] + nums[5] = 5 + 6 = 11\nExample 2:\nInput: nums = [1,2,3]\nOutput: -1\nExplanation:\nThere is no index that satisfies the conditions in the problem statement.\nExample 3:\nInput: nums = [2,1,-1]\nOutput: 0\nExplanation:\nThe pivot index is 0.\nLeft sum = 0 (no elements to the left of index 0)\nRight sum = nums[1] + nums[2] = 1 + -1 = 0\n Constraints:\n1 <= nums.length <= 104\n-1000 <= nums[i] <= 1000\n Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/" }, { "post_href": "https://leetcode.com/problems/split-linked-list-in-parts/discuss/1322974/Clean-Python-and-Java", "python_solutions": "class Solution:\n def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:\n size = self.get_size(head)\n min_len, one_more = divmod(size, k)\n res = []\n current = ListNode()\n current.next = head\n for i in range(k):\n ans = current\n for _ in range(min_len + int(i < one_more)):\n current = current.next\n res.append(ans.next)\n ans.next = None\n return res\n\n def get_size(self, head: ListNode) -> int:\n size = 0\n while head is not None:\n size += 1\n head = head.next\n return size", "slug": "split-linked-list-in-parts", "post_title": "Clean Python and Java", "user": "aquafie", "upvotes": 4, "views": 456, "problem_title": "split linked list in parts", "number": 725, "acceptance": 0.5720000000000001, "difficulty": "Medium", "__index_level_0__": 11919, "question": "Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.\nThe length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.\nThe parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.\nReturn an array of the k parts.\n Example 1:\nInput: head = [1,2,3], k = 5\nOutput: [[1],[2],[3],[],[]]\nExplanation:\nThe first element output[0] has output[0].val = 1, output[0].next = null.\nThe last element output[4] is null, but its string representation as a ListNode is [].\nExample 2:\nInput: head = [1,2,3,4,5,6,7,8,9,10], k = 3\nOutput: [[1,2,3,4],[5,6,7],[8,9,10]]\nExplanation:\nThe input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.\n Constraints:\nThe number of nodes in the list is in the range [0, 1000].\n0 <= Node.val <= 1000\n1 <= k <= 50" }, { "post_href": "https://leetcode.com/problems/number-of-atoms/discuss/1335787/efficient-O(N)-python3-solution-using-stack-of-stacks-with-explanation-of-code-and-approach", "python_solutions": "class Solution:\n def countOfAtoms(self, formula: str) -> str:\n # constant declarations\n upper=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n lower=upper.lower()\n digits = \"0123456789\"\n \n # variables\n count=defaultdict(int)\n element_name = None\n element_name_parse_start=False\n element_count =\"\"\n bracket_stacks = [[]]\n buffer = []\n \n # function to parse out the complete number if a digit is seen, \n # the function takes the character, that was seen as a digit and \n # the generator object to get the remaining (yet to be read) part of formula\n def parseout_number(ch,gen):\n nonlocal buffer\n num=\"\"\n try:\n while ch in digits:\n num += ch\n ch = next(gen)\n # after number is parsed out and a non-number character is seen, \n # add that non-number character to the buffer to be read next, dont miss parsing it\n buffer.append(ch)\n except StopIteration:\n # while iterating to find the end digit of the number, we have reached the end of the formula, \n # meaning the digit ch and subsequent characters were numbers and were the last thing in the formula\n\t\t\t\t# the code, outside of try-catch handles all the possible scenerios of parsing the number out, \n\t\t\t\t# so do nothing here. move along\n pass\n # if we saw a number, return it as integer, else return empty string\n if num != \"\":\n return int(num)\n else:\n return \"\"\n \n #generator expression\n formula_chars = (ch for ch in formula)\n \n # iterate over all characters\n for char in formula_chars:\n \n # add the character emitted by generator into buffer for processing\n buffer.append(char)\n \n # process what ever is in the buffer queue\n while buffer:\n ch = buffer.pop(0)\n \n # if the character is an upper case character\n # set the a flag to indicate start of a new element name\n # check if the previous elementname was added to the processing_stack (bracket_stacks)\n # if not then add it, noting one atom for that element\n # set the character to element_name variable\n if ch in upper:\n element_name_parse_start=True\n if element_name is not None and element_count == \"\":\n bracket_stacks[-1].append([element_name,1])\n element_name = ch\n # if character is lowercase, just concat it to the element_name\n elif ch in lower:\n element_name += ch\n # if character is a numerical digit, then parse that number out completely as integer\n # set the flag to indicate the reading the element name is done\n # store the element name and it's corresponding count into the processing_stack\n # reset the variables element_name and element_count, ready for next element\n elif ch in digits:\n element_name_parse_start=False\n element_count = parseout_number(ch,formula_chars)\n bracket_stacks[-1].append([element_name,element_count])\n element_count = \"\"\n element_name = None\n # if open bracket is seen, check if reading the element_name flag is still True\n # if it is then that element has one atom only\n # add it to the processing stack\n # set the flag to indicate that reading the 'element_name' is done and \n # add another processing stack top the top of the 'bracket_stacks'\n # this new processing stack will have the atom details within the bracket\n # finally, reset all other variables to ensure \n\t\t\t\t# clean slate for the new child 'processing-stack' before exiting the code-block\n elif ch == \"(\":\n if element_name_parse_start:\n bracket_stacks[-1].append([element_name,1])\n element_name_parse_start=False\n element_count = \"\"\n bracket_stacks.append([]) # new processing stack\n element_name = None\n \n # if a bracket is closed\n # make sure we account for one atom of element, if a number was not seen before closing the bracket\n # set the flag to indicate we are done reading element_name\n # check what is the next character after the bracket close char. \n\t\t\t\t# if it's a digit, then parse that number out \n # that number is the multiplier for the current processing stack\n # which means we will need to multiply every atom/element count by the multiplier\n # at this point the current processing stack \n\t\t\t\t# which was created as part of opening the bracket is processed\n # so, merge what we found into the parent processing stack by \n # extending the parent processing stack with the results of the child stack\n elif ch == \")\":\n if element_name_parse_start:\n bracket_stacks[-1].append([element_name,1])\n element_name = None\n element_name_parse_start=False\n braket_multiplier = \"\"\n try:\n next_ch= next(formula_chars)\n braket_multiplier = parseout_number(next_ch,formula_chars)\n except StopIteration:\n pass\n \n if braket_multiplier == \"\":\n braket_multiplier = 1\n\t\t\t\t\t# pop the child processing - stack to be processed\n process_this = bracket_stacks.pop()\n \n\t\t\t\t\t#processing\n for idx,_ in enumerate(process_this):\n process_this[idx][1] = process_this[idx][1]*braket_multiplier\n\t\t\t\t\t\n\t\t\t\t\t#merging processed child stack with the parent stack\n bracket_stacks[-1].extend(process_this)\n \n # if the new element name seen flag is set then process that \n # atom by adding it's element-name and atom count to the current processing stack\n if element_name_parse_start:\n if element_name is not None:\n if element_count != \"\":\n bracket_stacks[-1].append([element_name,int(element_count)])\n else:\n bracket_stacks[-1].append([element_name,1])\n \n # pop the top-level processing-stack, this should contain a 'flattened' version of the atoms and their counts\n # note that the counts of elements are not aggregated yet, \n # eg:If Oxygen was seen within a bracket and also seen outside that bracket, \n # then we'll have two entries for Oxygen. We'll aggregate them next...\n count_pairs = bracket_stacks.pop()\n \n # aggregate all the 'flattened' data in 'count_pairs' variable, using a dictionary\n for element_name,element_count in count_pairs:\n count[element_name]+= element_count\n \n # preparing the output string...\n # create a list meant to hold the 'words' of the output string, based on the description\n output=[]\n \n # fetch the keylist\n elements_list = list(count.keys())\n \n #sort it\n elements_list.sort()\n \n # for each element in the sorted keylist, if the element has more \n # than 1 atom, append the atom and it's count\n # if element has only 1 atom only append the atom name, \n # but don't append the atom's count (which is 1)\n for element in elements_list:\n if count[element] > 1:\n output.append(element)\n output.append(str(count[element]))\n else:\n output.append(element)\n \n # output will now have an list of words representation of what we need. turn the list into a string and return it\n return \"\".join(output)", "slug": "number-of-atoms", "post_title": "efficient O(N) python3 solution, using stack of stacks with explanation of code and approach", "user": "anupamkumar", "upvotes": 2, "views": 258, "problem_title": "number of atoms", "number": 726, "acceptance": 0.522, "difficulty": "Hard", "__index_level_0__": 11932, "question": "Given a string formula representing a chemical formula, return the count of each atom.\nThe atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\nOne or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.\nFor example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible.\nTwo formulas are concatenated together to produce another formula.\nFor example, \"H2O2He3Mg4\" is also a formula.\nA formula placed in parentheses, and a count (optionally added) is also a formula.\nFor example, \"(H2O2)\" and \"(H2O2)3\" are formulas.\nReturn the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\nThe test cases are generated so that all the values in the output fit in a 32-bit integer.\n Example 1:\nInput: formula = \"H2O\"\nOutput: \"H2O\"\nExplanation: The count of elements are {'H': 2, 'O': 1}.\nExample 2:\nInput: formula = \"Mg(OH)2\"\nOutput: \"H2MgO2\"\nExplanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\nExample 3:\nInput: formula = \"K4(ON(SO3)2)2\"\nOutput: \"K4N2O14S4\"\nExplanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n Constraints:\n1 <= formula.length <= 1000\nformula consists of English letters, digits, '(', and ')'.\nformula is always valid." }, { "post_href": "https://leetcode.com/problems/self-dividing-numbers/discuss/1233710/WEEB-DOES-PYTHON(BEATS-91.49)", "python_solutions": "class Solution:\n\tdef selfDividingNumbers(self, left: int, right: int) -> List[int]:\n\t\tresult = []\n\n\t\tfor i in range(left, right+ 1):\n\t\t\tif \"0\" in str(i): continue\n\t\t\tval = i\n\t\t\twhile val > 0:\n\t\t\t\tn = val % 10\n\t\t\t\tif i % n != 0:\n\t\t\t\t\tval = -1\n\t\t\t\tval = val // 10\n\n\t\t\tif val != -1: result.append(i)\n\n\t\treturn result", "slug": "self-dividing-numbers", "post_title": "WEEB DOES PYTHON(BEATS 91.49%)", "user": "Skywalker5423", "upvotes": 4, "views": 278, "problem_title": "self dividing numbers", "number": 728, "acceptance": 0.7759999999999999, "difficulty": "Easy", "__index_level_0__": 11934, "question": "A self-dividing number is a number that is divisible by every digit it contains.\nFor example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\nA self-dividing number is not allowed to contain the digit zero.\nGiven two integers left and right, return a list of all the self-dividing numbers in the range [left, right].\n Example 1:\nInput: left = 1, right = 22\nOutput: [1,2,3,4,5,6,7,8,9,11,12,15,22]\nExample 2:\nInput: left = 47, right = 85\nOutput: [48,55,66,77]\n Constraints:\n1 <= left <= right <= 104" }, { "post_href": "https://leetcode.com/problems/my-calendar-i/discuss/2731671/Fastest-Python-solution-greater-Create-a-Binary-Search-Tree", "python_solutions": "# Binary Search Tree Solution -> If exact matching of intervals found then return False\n# Else you can add this interval to that particular node's left or right\nclass Node:\n def __init__(self, s, e):\n self.s = s\n self.e = e\n self.left = None\n self.right = None\nclass MyCalendar:\n def __init__(self):\n self.head = None\n \n def insert(self, s, e, node):\n if s >= node.e:\n if node.right: return self.insert(s, e, node.right)\n else: \n nn = Node(s, e)\n node.right = nn\n return True\n elif e <= node.s:\n if node.left: return self.insert(s, e, node.left)\n else:\n nn = Node(s, e)\n node.left = nn\n return True\n else: return False\n \n def book(self, s: int, e: int) -> bool:\n if self.head == None:\n nn = Node(s, e)\n self.head = nn\n return True\n return self.insert(s, e, self.head)", "slug": "my-calendar-i", "post_title": "Fastest Python solution -> Create a Binary Search Tree\ud83e\udd76", "user": "shiv-codes", "upvotes": 0, "views": 17, "problem_title": "my calendar i", "number": 729, "acceptance": 0.5720000000000001, "difficulty": "Medium", "__index_level_0__": 11969, "question": "You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a double booking.\nA double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).\nThe event can be represented as a pair of integers start and end that represents a booking on the half-open interval [start, end), the range of real numbers x such that start <= x < end.\nImplement the MyCalendar class:\nMyCalendar() Initializes the calendar object.\nboolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar.\n Example 1:\nInput\n[\"MyCalendar\", \"book\", \"book\", \"book\"]\n[[], [10, 20], [15, 25], [20, 30]]\nOutput\n[null, true, false, true]\n\nExplanation\nMyCalendar myCalendar = new MyCalendar();\nmyCalendar.book(10, 20); // return True\nmyCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\nmyCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.\n Constraints:\n0 <= start < end <= 109\nAt most 1000 calls will be made to book." }, { "post_href": "https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/1612723/DP-Python", "python_solutions": "class Solution:\n def countPalindromicSubsequences(self, s:str) -> int:\n \n @cache\n def fn(ch, i, j):\n if i > j:\n return 0\n \n if i == j and s[i] == ch:\n return 1\n \n if s[i] == s[j] == ch:\n return 2 + fn('a', i+1, j-1) + fn('b', i+1, j-1) + fn('c', i+1, j-1) + fn('d', i+1, j-1)\n elif s[i] != ch:\n return fn(ch, i+1, j)\n elif s[j] != ch:\n return fn(ch, i, j-1)\n \n \n n = len(s)\n return (fn('a', 0, n-1) + fn('b', 0, n-1) + fn('c', 0, n-1) + fn('d', 0, n-1)) % (10**9+7)", "slug": "count-different-palindromic-subsequences", "post_title": "DP Python", "user": "yshawn", "upvotes": 2, "views": 469, "problem_title": "count different palindromic subsequences", "number": 730, "acceptance": 0.445, "difficulty": "Hard", "__index_level_0__": 11970, "question": "Given a string s, return the number of different non-empty palindromic subsequences in s. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence of a string is obtained by deleting zero or more characters from the string.\nA sequence is palindromic if it is equal to the sequence reversed.\nTwo sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.\n Example 1:\nInput: s = \"bccb\"\nOutput: 6\nExplanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\nNote that 'bcb' is counted only once, even though it occurs twice.\nExample 2:\nInput: s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"\nOutput: 104860361\nExplanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.\n Constraints:\n1 <= s.length <= 1000\ns[i] is either 'a', 'b', 'c', or 'd'." }, { "post_href": "https://leetcode.com/problems/flood-fill/discuss/626424/PythonJSGoC%2B%2B-sol-by-DFS-w-Comment", "python_solutions": "class Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:\n \n h, w = len(image), len(image[0])\n \n\t\t\n def dfs( r, c, src_color):\n \n if r < 0 or c < 0 or r >= h or c >= w or image[r][c] == newColor or image[r][c] != src_color:\n # Reject for invalid coordination, repeated traversal, or different color\n return\n \n # update color\n image[r][c] = newColor\n \n \n # DFS to 4-connected neighbors\n dfs( r-1, c, src_color )\n dfs( r+1, c, src_color )\n dfs( r, c-1, src_color )\n dfs( r, c+1, src_color )\n \n # ---------------------------------------------------------------------------\n \n dfs(sr, sc, src_color = image[sr][sc] )\n \n return image", "slug": "flood-fill", "post_title": "Python/JS/Go/C++ sol by DFS [w/ Comment]", "user": "brianchiang_tw", "upvotes": 17, "views": 4300, "problem_title": "flood fill", "number": 733, "acceptance": 0.607, "difficulty": "Easy", "__index_level_0__": 11975, "question": "An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.\nYou are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].\nTo perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.\nReturn the modified image after performing the flood fill.\n Example 1:\nInput: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2\nOutput: [[2,2,2],[2,2,0],[2,0,1]]\nExplanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.\nNote the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.\nExample 2:\nInput: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0\nOutput: [[0,0,0],[0,0,0]]\nExplanation: The starting pixel is already colored 0, so no changes are made to the image.\n Constraints:\nm == image.length\nn == image[i].length\n1 <= m, n <= 50\n0 <= image[i][j], color < 216\n0 <= sr < m\n0 <= sc < n" }, { "post_href": "https://leetcode.com/problems/asteroid-collision/discuss/646757/Python3-concise-solution-Asteroid-Collision", "python_solutions": "class Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for a in asteroids:\n if a > 0:\n stack.append(a)\n else:\n while stack and stack[-1] > 0 and stack[-1] + a < 0:\n stack.pop()\n if not stack or stack[-1] < 0:\n stack.append(a)\n elif stack[-1] + a == 0:\n stack.pop()\n return stack", "slug": "asteroid-collision", "post_title": "Python3 concise solution - Asteroid Collision", "user": "r0bertz", "upvotes": 5, "views": 426, "problem_title": "asteroid collision", "number": 735, "acceptance": 0.444, "difficulty": "Medium", "__index_level_0__": 12030, "question": "We are given an array asteroids of integers representing asteroids in a row.\nFor each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.\nFind out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.\n Example 1:\nInput: asteroids = [5,10,-5]\nOutput: [5,10]\nExplanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.\nExample 2:\nInput: asteroids = [8,-8]\nOutput: []\nExplanation: The 8 and -8 collide exploding each other.\nExample 3:\nInput: asteroids = [10,2,-5]\nOutput: [10]\nExplanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.\n Constraints:\n2 <= asteroids.length <= 104\n-1000 <= asteroids[i] <= 1000\nasteroids[i] != 0" }, { "post_href": "https://leetcode.com/problems/parse-lisp-expression/discuss/2149196/Python3-Solution", "python_solutions": "class Solution:\n def evaluate(self, expression: str) -> int:\n stack = []\n parenEnd = {}\n \n # Get the end parenthesis location \n for idx, ch in enumerate(expression):\n if ch == '(':\n stack.append(idx)\n if ch == ')':\n parenEnd[stack.pop()] = idx\n\n # Parses the expression into a list, each new sublist is a set of parenthesis\n # Example: \n # Input: \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\n # Output: ['let', 'x', '2', ['mult', 'x', ['let', 'x', '3', 'y', '4', ['add', 'x', 'y']]]]\n def parse(lo, hi):\n arr = []\n word = []\n\n i = lo\n while i < hi:\n if expression[i] == '(':\n arr.append(parse(i + 1, parenEnd[i]))\n i = parenEnd[i]\n elif expression[i] == ' ' or expression[i] == ')' and word != []:\n if ''.join(word) != '':\n arr.append(''.join(word))\n word = []\n i += 1\n elif expression[i] != ')':\n word.append(expression[i])\n i += 1\n else:\n i += 1\n\n\n if word != []:\n arr.append(''.join(word))\n\n return arr\n\n # Change string expression into the list expression\n expressionList = parse(1, len(expression) - 1)\n\n # Eval expression with starting scope (variables)\n return self.genEval(expressionList, {})\n \n def genEval(self, expression, scope):\n if type(expression) != list:\n # If expression is just a variable or int\n try:\n return int(expression)\n except:\n return scope[expression]\n else:\n if expression[0] == 'let':\n # Remove \"let\" from expression list\n expression = expression[1:]\n \n # This loop updates the scope (variables)\n while len(expression) > 2:\n scope = self.letEval(expression, scope.copy())\n expression = expression[2:]\n \n # Return the last value\n return self.genEval(expression[0], scope.copy())\n \n if expression[0] == 'add':\n return self.addEval(expression, scope.copy())\n \n if expression[0] == 'mult':\n return self.multEval(expression, scope.copy())\n\n\n \n def letEval(self, expression, scope):\n scope[expression[0]] = self.genEval(expression[1], scope)\n return scope\n \n def addEval(self, expression, scope):\n return self.genEval(expression[1], scope) + self.genEval(expression[2], scope)\n \n def multEval(self, expression, scope):\n return self.genEval(expression[1], scope) * self.genEval(expression[2], scope)", "slug": "parse-lisp-expression", "post_title": "Python3 Solution", "user": "krzys2194", "upvotes": 1, "views": 113, "problem_title": "parse lisp expression", "number": 736, "acceptance": 0.515, "difficulty": "Hard", "__index_level_0__": 12056, "question": "You are given a string expression representing a Lisp-like expression to return the integer value of.\nThe syntax for these expressions is given as follows.\nAn expression is either an integer, let expression, add expression, mult expression, or an assigned variable. Expressions always evaluate to a single integer.\n(An integer could be positive or negative.)\nA let expression takes the form \"(let v1 e1 v2 e2 ... vn en expr)\", where let is always the string \"let\", then there are one 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.\nAn add expression takes the form \"(add e1 e2)\" where add is always the string \"add\", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.\nA mult expression takes the form \"(mult e1 e2)\" where mult is always the string \"mult\", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.\nFor 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\", and \"mult\" are protected and will never be used as variable names.\nFinally, 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 the scope.\n Example 1:\nInput: expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\nOutput: 14\nExplanation: In the expression (add x y), when checking for the value of the variable x,\nwe check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\nSince x = 3 is found first, the value of x is 3.\nExample 2:\nInput: expression = \"(let x 3 x 2 x)\"\nOutput: 2\nExplanation: Assignment in let statements is processed sequentially.\nExample 3:\nInput: expression = \"(let x 1 y 2 x (add x y) (add x y))\"\nOutput: 5\nExplanation: The first (add x y) evaluates as 3, and is assigned to x.\nThe second (add x y) evaluates as 3+2 = 5.\n Constraints:\n1 <= expression.length <= 2000\nThere are no leading or trailing spaces in expression.\nAll tokens are separated by a single space in expression.\nThe answer and all intermediate calculations of that answer are guaranteed to fit in a 32-bit integer.\nThe expression is guaranteed to be legal and evaluate to an integer." }, { "post_href": "https://leetcode.com/problems/monotone-increasing-digits/discuss/921119/Python3-O(N)-via-stack", "python_solutions": "class Solution:\n def monotoneIncreasingDigits(self, N: int) -> int:\n nums = [int(x) for x in str(N)] # digits \n stack = []\n for i, x in enumerate(nums): \n while stack and stack[-1] > x: x = stack.pop() - 1\n stack.append(x) \n if len(stack) <= i: break \n return int(\"\".join(map(str, stack)).ljust(len(nums), \"9\")) # right padding with \"9\"", "slug": "monotone-increasing-digits", "post_title": "[Python3] O(N) via stack", "user": "ye15", "upvotes": 1, "views": 126, "problem_title": "monotone increasing digits", "number": 738, "acceptance": 0.471, "difficulty": "Medium", "__index_level_0__": 12058, "question": "An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.\nGiven an integer n, return the largest number that is less than or equal to n with monotone increasing digits.\n Example 1:\nInput: n = 10\nOutput: 9\nExample 2:\nInput: n = 1234\nOutput: 1234\nExample 3:\nInput: n = 332\nOutput: 299\n Constraints:\n0 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/daily-temperatures/discuss/2506436/Python-Stack-97.04-faster-or-Simplest-solution-with-explanation-or-Beg-to-Adv-or-Monotonic-Stack", "python_solutions": "class Solution:\n def dailyTemperatures(self, temperatures: List[int]) -> List[int]:\n result = [0] * len(temperatures) # having list with 0`s elements of same lenght as temperature array.\n stack = [] # taking empty stack. \n for index, temp in enumerate(temperatures): # Traversing through provided list. \n while stack and temperatures[stack[-1]] < temp: # stack should not be empty and checking previous temp with current temp. \n # the above while loop and taking stack for saving index is very common practice in monotonic stack questions. Suggestion: understand it properly. \n prev_temp = stack.pop() # stack.pop() will provide index of prev temp, taking in separate var as we are using it more then on place. \n result[prev_temp] = index - prev_temp #at the index of prev_temp and i - prev_temp by this we`ll get how many step we moved to have greater temp. \n stack.append(index) # in case stack is empty we`ll push index in it. \n\n return result # returing the list of number of days to wait.", "slug": "daily-temperatures", "post_title": "Python Stack 97.04% faster | Simplest solution with explanation | Beg to Adv | Monotonic Stack", "user": "rlakshay14", "upvotes": 6, "views": 473, "problem_title": "daily temperatures", "number": 739, "acceptance": 0.6659999999999999, "difficulty": "Medium", "__index_level_0__": 12066, "question": "Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.\n Example 1:\nInput: temperatures = [73,74,75,71,69,72,76,73]\nOutput: [1,1,4,2,1,1,0,0]\nExample 2:\nInput: temperatures = [30,40,50,60]\nOutput: [1,1,1,0]\nExample 3:\nInput: temperatures = [30,60,90]\nOutput: [1,1,0]\n Constraints:\n1 <= temperatures.length <= 105\n30 <= temperatures[i] <= 100" }, { "post_href": "https://leetcode.com/problems/delete-and-earn/discuss/916859/Python3-top-down-dp", "python_solutions": "class Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n mp = {}\n for x in nums: mp[x] = x + mp.get(x, 0)\n \n @lru_cache(None)\n def fn(i): \n \"\"\"Return maximum points one can earn from nums[i:].\"\"\"\n if i >= len(nums): return 0 \n if nums[i] + 1 not in mp: return mp[nums[i]] + fn(i+1)\n return max(mp[nums[i]] + fn(i+2), fn(i+1))\n \n nums = sorted(set(nums))\n return fn(0)", "slug": "delete-and-earn", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 7, "views": 273, "problem_title": "delete and earn", "number": 740, "acceptance": 0.573, "difficulty": "Medium", "__index_level_0__": 12113, "question": "You are given an integer array nums. You want to maximize the number of points you get by performing the following operation any number of times:\nPick any nums[i] and delete it to earn nums[i] points. Afterwards, you must delete every element equal to nums[i] - 1 and every element equal to nums[i] + 1.\nReturn the maximum number of points you can earn by applying the above operation some number of times.\n Example 1:\nInput: nums = [3,4,2]\nOutput: 6\nExplanation: You can perform the following operations:\n- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = [2].\n- Delete 2 to earn 2 points. nums = [].\nYou earn a total of 6 points.\nExample 2:\nInput: nums = [2,2,3,3,3,4]\nOutput: 9\nExplanation: You can perform the following operations:\n- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = [3,3].\n- Delete a 3 again to earn 3 points. nums = [3].\n- Delete a 3 once more to earn 3 points. nums = [].\nYou earn a total of 9 points.\n Constraints:\n1 <= nums.length <= 2 * 104\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/cherry-pickup/discuss/699169/Python3-dp", "python_solutions": "class Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n n = len(grid)\n \n @lru_cache(None)\n def fn(t, i, ii): \n \"\"\"Return maximum cherries collected at kth step when two robots are at ith and iith row\"\"\"\n j, jj = t - i, t - ii #columns\n if not (0 <= i < n and 0 <= j < n) or t < i or grid[ i][ j] == -1: return -inf #robot 1 not at proper location\n if not (0 <= ii < n and 0 <= jj < n) or t < ii or grid[ii][jj] == -1: return -inf #robot 2 not at proper location\n if t == 0: return grid[0][0] #starting from 0,0\n return grid[i][j] + (i != ii)*grid[ii][jj] + max(fn(t-1, x, y) for x in (i-1, i) for y in (ii-1, ii))\n \n return max(0, fn(2*n-2, n-1, n-1))", "slug": "cherry-pickup", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 2, "views": 241, "problem_title": "cherry pickup", "number": 741, "acceptance": 0.363, "difficulty": "Hard", "__index_level_0__": 12161, "question": "You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.\n0 means the cell is empty, so you can pass through,\n1 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.\nReturn the maximum number of cherries you can collect by following the rules below:\nStarting 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).\nAfter reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.\nWhen passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.\nIf there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.\n Example 1:\nInput: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\nOutput: 5\nExplanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\nThen, the player went left, up, up, left to return home, picking up one more cherry.\nThe total number of cherries picked up is 5, and this is the maximum possible.\nExample 2:\nInput: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\nOutput: 0\n Constraints:\nn == grid.length\nn == grid[i].length\n1 <= n <= 50\ngrid[i][j] is -1, 0, or 1.\ngrid[0][0] != -1\ngrid[n - 1][n - 1] != -1" }, { "post_href": "https://leetcode.com/problems/network-delay-time/discuss/2036405/Python-Simple-Dijkstra-Beats-~90", "python_solutions": "class Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: \n adj_list = defaultdict(list)\n \n for x,y,w in times:\n adj_list[x].append((w, y))\n \n visited=set()\n heap = [(0, k)]\n while heap:\n travel_time, node = heapq.heappop(heap)\n visited.add(node)\n \n if len(visited)==n:\n return travel_time\n \n for time, adjacent_node in adj_list[node]:\n if adjacent_node not in visited:\n heapq.heappush(heap, (travel_time+time, adjacent_node))\n \n return -1", "slug": "network-delay-time", "post_title": "Python Simple Dijkstra Beats ~90%", "user": "constantine786", "upvotes": 39, "views": 2200, "problem_title": "network delay time", "number": 743, "acceptance": 0.515, "difficulty": "Medium", "__index_level_0__": 12164, "question": "You are given a network of n nodes, labeled from 1 to n. You are also given times, a list of travel times as directed edges times[i] = (ui, vi, wi), where ui is the source node, vi is the target node, and wi is the time it takes for a signal to travel from source to target.\nWe will send a signal from a given node k. Return the minimum time it takes for all the n nodes to receive the signal. If it is impossible for all the n nodes to receive the signal, return -1.\n Example 1:\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\nOutput: 2\nExample 2:\nInput: times = [[1,2,1]], n = 2, k = 1\nOutput: 1\nExample 3:\nInput: times = [[1,2,1]], n = 2, k = 2\nOutput: -1\n Constraints:\n1 <= k <= n <= 100\n1 <= times.length <= 6000\ntimes[i].length == 3\n1 <= ui, vi <= n\nui != vi\n0 <= wi <= 100\nAll the pairs (ui, vi) are unique. (i.e., no multiple edges.)" }, { "post_href": "https://leetcode.com/problems/find-smallest-letter-greater-than-target/discuss/1568523/Python-easy-solution-with-detail-explanation-(modified-binary-search)", "python_solutions": "class Solution(object):\n def nextGreatestLetter(self, letters, target):\n \"\"\"\n :type letters: List[str]\n :type target: str\n :rtype: str\n \"\"\"\n \n # if the number is out of bound\n if target >= letters[-1] or target < letters[0]:\n return letters[0]\n \n low = 0\n high = len(letters)-1\n while low <= high:\n mid = (high+low)//2\n \n if target >= letters[mid]: # in binary search this would be only greater than\n low = mid+1\n \n if target < letters[mid]:\n high = mid-1\n \n return letters[low]", "slug": "find-smallest-letter-greater-than-target", "post_title": "Python easy solution with detail explanation (modified binary search)", "user": "Abeni", "upvotes": 71, "views": 3300, "problem_title": "find smallest letter greater than target", "number": 744, "acceptance": 0.4479999999999999, "difficulty": "Easy", "__index_level_0__": 12197, "question": "You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters.\nReturn the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters.\n Example 1:\nInput: letters = [\"c\",\"f\",\"j\"], target = \"a\"\nOutput: \"c\"\nExplanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.\nExample 2:\nInput: letters = [\"c\",\"f\",\"j\"], target = \"c\"\nOutput: \"f\"\nExplanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.\nExample 3:\nInput: letters = [\"x\",\"x\",\"y\",\"y\"], target = \"z\"\nOutput: \"x\"\nExplanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].\n Constraints:\n2 <= letters.length <= 104\nletters[i] is a lowercase English letter.\nletters is sorted in non-decreasing order.\nletters contains at least two different characters.\ntarget is a lowercase English letter." }, { "post_href": "https://leetcode.com/problems/min-cost-climbing-stairs/discuss/2260902/94-FASTER-97-Space-Efficient-Python-solutions-Different-approaches", "python_solutions": "class Solution:\n\tdef minCostClimbingStairs(self, cost: List[int]) -> int:\n\t\tcur = 0 \n\t\tdp0 = cost[0]\n\t\tif len(cost) >= 2:\n\t\t\tdp1 = cost[1]\n\n\t\tfor i in range(2, len(cost)):\n\t\t\tcur = cost[i] + min(dp0, dp1)\n\t\t\tdp0 = dp1\n\t\t\tdp1 = cur\n\n\t\treturn min(dp0, dp1)", "slug": "min-cost-climbing-stairs", "post_title": "94% FASTER 97% Space Efficient Python solutions Different approaches", "user": "anuvabtest", "upvotes": 34, "views": 2300, "problem_title": "min cost climbing stairs", "number": 746, "acceptance": 0.625, "difficulty": "Easy", "__index_level_0__": 12252, "question": "You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.\nYou can either start from the step with index 0, or the step with index 1.\nReturn the minimum cost to reach the top of the floor.\n Example 1:\nInput: cost = [10,15,20]\nOutput: 15\nExplanation: You will start at index 1.\n- Pay 15 and climb two steps to reach the top.\nThe total cost is 15.\nExample 2:\nInput: cost = [1,100,1,1,1,100,1,1,100,1]\nOutput: 6\nExplanation: You will start at index 0.\n- Pay 1 and climb two steps to reach index 2.\n- Pay 1 and climb two steps to reach index 4.\n- Pay 1 and climb two steps to reach index 6.\n- Pay 1 and climb one step to reach index 7.\n- Pay 1 and climb two steps to reach index 9.\n- Pay 1 and climb one step to reach the top.\nThe total cost is 6.\n Constraints:\n2 <= cost.length <= 1000\n0 <= cost[i] <= 999" }, { "post_href": "https://leetcode.com/problems/largest-number-at-least-twice-of-others/discuss/2069691/no-loops", "python_solutions": "class Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n if len(nums) is 1:\n return 0\n dom = max(nums)\n i = nums.index(dom)\n nums.remove(dom)\n if max(nums) * 2 <= dom:\n return i\n return -1", "slug": "largest-number-at-least-twice-of-others", "post_title": "no loops", "user": "andrewnerdimo", "upvotes": 3, "views": 90, "problem_title": "largest number at least twice of others", "number": 747, "acceptance": 0.465, "difficulty": "Easy", "__index_level_0__": 12316, "question": "You are given an integer array nums where the largest integer is unique.\nDetermine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise.\n Example 1:\nInput: nums = [3,6,1,0]\nOutput: 1\nExplanation: 6 is the largest integer.\nFor every other number in the array x, 6 is at least twice as big as x.\nThe index of value 6 is 1, so we return 1.\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: -1\nExplanation: 4 is less than twice the value of 3, so we return -1.\n Constraints:\n2 <= nums.length <= 50\n0 <= nums[i] <= 100\nThe largest element in nums is unique." }, { "post_href": "https://leetcode.com/problems/shortest-completing-word/discuss/1277850/Python3-Simple-solution-without-Dictionary", "python_solutions": "class Solution:\n def shortestCompletingWord(self, P: str, words: List[str]) -> str:\n alphs=\"\"\n res=\"\" \n for p in P:\n if p.isalpha():\n alphs+=p.lower()\n for word in words: \n if all(alphs.count(alphs[i]) <= word.count(alphs[i]) for i in range(len(alphs))):\n if res==\"\" or len(res)>len(word):\n res=word\n \n return res", "slug": "shortest-completing-word", "post_title": "Python3 Simple solution without Dictionary", "user": "Rei4126", "upvotes": 4, "views": 335, "problem_title": "shortest completing word", "number": 748, "acceptance": 0.5920000000000001, "difficulty": "Easy", "__index_level_0__": 12352, "question": "Given a string licensePlate and an array of strings words, find the shortest completing word in words.\nA completing word is a word that contains all the letters in licensePlate. Ignore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.\nFor example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\".\nReturn the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.\n Example 1:\nInput: licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\nOutput: \"steps\"\nExplanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.\n\"step\" contains 't' and 'p', but only contains 1 's'.\n\"steps\" contains 't', 'p', and both 's' characters.\n\"stripe\" is missing an 's'.\n\"stepple\" is missing an 's'.\nSince \"steps\" is the only word containing all the letters, that is the answer.\nExample 2:\nInput: licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\nOutput: \"pest\"\nExplanation: licensePlate only contains the letter 's'. All the words contain 's', but among these \"pest\", \"stew\", and \"show\" are shortest. The answer is \"pest\" because it is the word that appears earliest of the 3.\n Constraints:\n1 <= licensePlate.length <= 7\nlicensePlate contains digits, letters (uppercase or lowercase), or space ' '.\n1 <= words.length <= 1000\n1 <= words[i].length <= 15\nwords[i] consists of lower case English letters." }, { "post_href": "https://leetcode.com/problems/contain-virus/discuss/2224726/Pyhon-Easy-Solution-oror-DFS-oror-Time-O(m*n*max(m-n))-oror-Faster", "python_solutions": "class Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m,n = len(mat),len(mat[0])\n\n def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area\n if 0<=i int:\n if end in deadends or \"0000\" in deadends:\n return -1\n if end == \"0000\":\n return 0\n start, end, deadends = 0, int(end), {int(deadend) for deadend in deadends}\n\n def distance(cur: int, target: int) -> int:\n diff = 0\n for _ in range(4):\n a, b = cur % 10, target % 10\n d = abs(a - b)\n diff += min(d, 10 - d)\n cur, target = cur // 10, target // 10\n return diff\n\n\t\tdef turn_knob(cur: int, idx: int) -> Tuple[int, int]:\n\t\t\tindex = 10 ** idx\n\t\t\tdigit = cur // index % 10\n\t\t\tup = cur - 9 * index if digit == 9 else cur + index\n\t\t\tdown = cur - index if digit else cur + 9 * index\n\t\t\treturn up, down\n\n def process(\n this_q: List[int], this_v: Dict[int, int], other_v: Dict[int, int], target: int\n ) -> int:\n _, cur = heappop(this_q)\n step = this_v[cur]\n for i in range(4):\n up, down = turn_knob(cur, i)\n if up in other_v:\n return step + other_v[up] + 1\n if down in other_v:\n return step + other_v[down] + 1\n if up not in deadends and up not in this_v:\n this_v[up] = step + 1\n this_q.append((distance(up, target), up))\n if down not in deadends and down not in this_v:\n this_v[down] = step + 1\n this_q.append((distance(down, target), down))\n heapify(this_q)\n return None\n\n s_q, s_v = [(distance(start, end), start)], {start: 0}\n e_q, e_v = [(distance(end, start), end)], {end: 0}\n while s_q and e_q:\n s = process(s_q, s_v, e_v, end)\n if s: return s\n e = process(e_q, e_v, s_v, start)\n if e: return e\n return -1", "slug": "open-the-lock", "post_title": "Python | Bi-directional A star, BFS | 99.7% | 52ms | 14.3MB", "user": "PuneethaPai", "upvotes": 3, "views": 110, "problem_title": "open the lock", "number": 752, "acceptance": 0.555, "difficulty": "Medium", "__index_level_0__": 12365, "question": "You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.\nThe lock initially starts at '0000', a string representing the state of the 4 wheels.\nYou are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.\nGiven a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.\n Example 1:\nInput: deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\nOutput: 6\nExplanation: \nA sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\nNote that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\nbecause the wheels of the lock become stuck after the display becomes the dead end \"0102\".\nExample 2:\nInput: deadends = [\"8888\"], target = \"0009\"\nOutput: 1\nExplanation: We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".\nExample 3:\nInput: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\nOutput: -1\nExplanation: We cannot reach the target without getting stuck.\n Constraints:\n1 <= deadends.length <= 500\ndeadends[i].length == 4\ntarget.length == 4\ntarget will not be in the list deadends.\ntarget and deadends[i] consist of digits only." }, { "post_href": "https://leetcode.com/problems/cracking-the-safe/discuss/2825347/DFS-Solution-in-Python", "python_solutions": "class Solution:\n def crackSafe(self, n: int, k: int) -> str:\n def dfs(path, visitedCombinations, targetNumVisited, combos):\n # Base Case. We've visited all possible combinations\n if len(visitedCombinations) == targetNumVisited:\n combos.append(''.join([str(x) for x in path]))\n return True\n # This if/else is necessary to prevent Python from picking up the first element if n = 1\n if n > 1:\n lastDigits = ''.join([str(x) for x in path[-(n-1):]])\n else:\n lastDigits = ''\n for i in range(k):\n path.append(i)\n newPwd = f'{lastDigits}{i}'\n # We have not reached the minimum pwd length. Continue recursion\n if len(newPwd) != n: \n if dfs(path, visitedCombinations, targetNumVisited, combos):\n return True\n if len(newPwd) == n and newPwd not in visitedCombinations:\n visitedCombinations[newPwd] = 1\n if dfs(path, visitedCombinations, targetNumVisited, combos):\n return True\n del visitedCombinations[newPwd]\n path.pop()\n return False\n \n \n # Empty visited Combinations hash set\n visitedCombinations = {}\n combos = []\n dfs([], visitedCombinations, k**n, combos)\n return combos[0]", "slug": "cracking-the-safe", "post_title": "DFS Solution in Python", "user": "user0138r", "upvotes": 0, "views": 1, "problem_title": "cracking the safe", "number": 753, "acceptance": 0.555, "difficulty": "Hard", "__index_level_0__": 12382, "question": "There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].\nThe safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.\nFor example, the correct password is \"345\" and you enter in \"012345\":\nAfter typing 0, the most recent 3 digits is \"0\", which is incorrect.\nAfter typing 1, the most recent 3 digits is \"01\", which is incorrect.\nAfter typing 2, the most recent 3 digits is \"012\", which is incorrect.\nAfter typing 3, the most recent 3 digits is \"123\", which is incorrect.\nAfter typing 4, the most recent 3 digits is \"234\", which is incorrect.\nAfter typing 5, the most recent 3 digits is \"345\", which is correct and the safe unlocks.\nReturn any string of minimum length that will unlock the safe at some point of entering it.\n Example 1:\nInput: n = 1, k = 2\nOutput: \"10\"\nExplanation: The password is a single digit, so enter each digit. \"01\" would also unlock the safe.\nExample 2:\nInput: n = 2, k = 2\nOutput: \"01100\"\nExplanation: For each possible password:\n- \"00\" is typed in starting from the 4th digit.\n- \"01\" is typed in starting from the 1st digit.\n- \"10\" is typed in starting from the 3rd digit.\n- \"11\" is typed in starting from the 2nd digit.\nThus \"01100\" will unlock the safe. \"10011\", and \"11001\" would also unlock the safe.\n Constraints:\n1 <= n <= 4\n1 <= k <= 10\n1 <= kn <= 4096" }, { "post_href": "https://leetcode.com/problems/reach-a-number/discuss/991390/Python-Dummy-math-solution-easy-to-understand", "python_solutions": "class Solution:\n def reachNumber(self, target: int) -> int:\n target = abs(target)\n step = 0\n far = 0\n while far < target or far%2 != target%2:\n step += 1\n far +=step\n \n return step", "slug": "reach-a-number", "post_title": "[Python] Dummy math solution, easy to understand", "user": "KevinZzz666", "upvotes": 1, "views": 47, "problem_title": "reach a number", "number": 754, "acceptance": 0.426, "difficulty": "Medium", "__index_level_0__": 12384, "question": "You are standing at position 0 on an infinite number line. There is a destination at position target.\nYou can make some number of moves numMoves so that:\nOn each move, you can either go left or right.\nDuring the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.\nGiven the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.\n Example 1:\nInput: target = 2\nOutput: 3\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to -1 (2 steps).\nOn the 3rd move, we step from -1 to 2 (3 steps).\nExample 2:\nInput: target = 3\nOutput: 2\nExplanation:\nOn the 1st move, we step from 0 to 1 (1 step).\nOn the 2nd move, we step from 1 to 3 (2 steps).\n Constraints:\n-109 <= target <= 109\ntarget != 0" }, { "post_href": "https://leetcode.com/problems/pyramid-transition-matrix/discuss/921324/Python3-progressively-building-new-rows", "python_solutions": "class Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n mp = {}\n for x, y, z in allowed: mp.setdefault((x, y), set()).add(z)\n \n def fn(row): \n \"\"\"Return list of rows built from given row.\"\"\"\n ans = [\"\"]\n for x, y in zip(row, row[1:]):\n if (x, y) not in mp: return []\n ans = [xx + zz for xx in ans for zz in mp[x, y]]\n return ans \n \n # dfs \n stack = [bottom]\n while stack: \n row = stack.pop()\n if len(row) == 1: return True \n stack.extend(fn(row))\n return False", "slug": "pyramid-transition-matrix", "post_title": "[Python3] progressively building new rows", "user": "ye15", "upvotes": 2, "views": 215, "problem_title": "pyramid transition matrix", "number": 756, "acceptance": 0.531, "difficulty": "Medium", "__index_level_0__": 12387, "question": "You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains one less block than the row beneath it and is centered on top.\nTo make the pyramid aesthetically pleasing, there are only specific triangular patterns that are allowed. A triangular pattern consists of a single block stacked on top of two blocks. The patterns are given as a list of three-letter strings allowed, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.\nFor example, \"ABC\" represents a triangular pattern with a 'C' block stacked on top of an 'A' (left) and 'B' (right) block. Note that this is different from \"BAC\" where 'B' is on the left bottom and 'A' is on the right bottom.\nYou start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.\nGiven bottom and allowed, return true if you can build the pyramid all the way to the top such that every triangular pattern in the pyramid is in allowed, or false otherwise.\n Example 1:\nInput: bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\nOutput: true\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\nThere are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.\nExample 2:\nInput: bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\nOutput: false\nExplanation: The allowed triangular patterns are shown on the right.\nStarting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.\n Constraints:\n2 <= bottom.length <= 6\n0 <= allowed.length <= 216\nallowed[i].length == 3\nThe letters in all input strings are from the set {'A', 'B', 'C', 'D', 'E', 'F'}.\nAll the values of allowed are unique." }, { "post_href": "https://leetcode.com/problems/set-intersection-size-at-least-two/discuss/2700915/Python-Explained-or-O(nlogn)", "python_solutions": "class Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda x:x[1])\n size = 0\n prev_start = -1\n prev_end = -1\n\n for curr_start, curr_end in intervals:\n if prev_start == -1 or prev_end < curr_start: #if intervals do not overlap\n size += 2\n prev_start = curr_end-1\n prev_end = curr_end\n\n elif prev_start < curr_start: #if intervals overlap\n if prev_end != curr_end:\n prev_start = prev_end\n prev_end = curr_end\n \n else:\n prev_start = curr_end-1\n prev_end = curr_end\n\n size += 1\n\n return size", "slug": "set-intersection-size-at-least-two", "post_title": "Python [Explained] | O(nlogn)", "user": "diwakar_4", "upvotes": 1, "views": 545, "problem_title": "set intersection size at least two", "number": 757, "acceptance": 0.439, "difficulty": "Hard", "__index_level_0__": 12391, "question": "You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.\nA containing set is an array nums where each interval from intervals has at least two integers in nums.\nFor example, if intervals = [[1,3], [3,7], [8,9]], then [1,2,4,7,8,9] and [2,3,4,8,9] are containing sets.\nReturn the minimum possible size of a containing set.\n Example 1:\nInput: intervals = [[1,3],[3,7],[8,9]]\nOutput: 5\nExplanation: let nums = [2, 3, 4, 8, 9].\nIt can be shown that there cannot be any containing array of size 4.\nExample 2:\nInput: intervals = [[1,3],[1,4],[2,5],[3,5]]\nOutput: 3\nExplanation: let nums = [2, 3, 4].\nIt can be shown that there cannot be any containing array of size 2.\nExample 3:\nInput: intervals = [[1,2],[2,3],[2,4],[4,5]]\nOutput: 5\nExplanation: let nums = [1, 2, 3, 4, 5].\nIt can be shown that there cannot be any containing array of size 4.\n Constraints:\n1 <= intervals.length <= 3000\nintervals[i].length == 2\n0 <= starti < endi <= 108" }, { "post_href": "https://leetcode.com/problems/special-binary-string/discuss/1498369/Easy-Approach-oror-Well-Explained-oror-Substring", "python_solutions": "class Solution:\ndef makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]=='1' else -1\n if balance==0:\n sublist.append(\"1\" + self.makeLargestSpecial(s[l+1:r])+ \"0\")\n l = r+1\n \n sublist.sort(reverse=True)\n return ''.join(sublist)", "slug": "special-binary-string", "post_title": "\ud83d\udccc\ud83d\udccc Easy-Approach || Well-Explained || Substring \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 5, "views": 371, "problem_title": "special binary string", "number": 761, "acceptance": 0.604, "difficulty": "Hard", "__index_level_0__": 12394, "question": "Special binary strings are binary strings with the following two properties:\nThe number of 0's is equal to the number of 1's.\nEvery prefix of the binary string has at least as many 1's as 0's.\nYou are given a special binary string s.\nA move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.\nReturn the lexicographically largest resulting string possible after applying the mentioned operations on the string.\n Example 1:\nInput: s = \"11011000\"\nOutput: \"11100100\"\nExplanation: The strings \"10\" [occuring at s[1]] and \"1100\" [at s[3]] are swapped.\nThis is the lexicographically largest string possible after some number of swaps.\nExample 2:\nInput: s = \"10\"\nOutput: \"10\"\n Constraints:\n1 <= s.length <= 50\ns[i] is either '0' or '1'.\ns is a special binary string." }, { "post_href": "https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/discuss/1685874/Simple-python-code", "python_solutions": "class Solution:\n def isPrime(self,x):\n flag=0\n if x==1:\n return False\n for i in range(2,x):\n if x%i==0:\n flag=1\n break\n if flag==1:\n return False\n return True\n \n def countPrimeSetBits(self, left: int, right: int) -> int:\n arr_dict={}\n lst=list(range(left,right+1))\n for i in lst:\n if i not in arr_dict:\n arr_dict[i]=bin(i).replace(\"0b\",\"\")\n arr=list(arr_dict.values())\n count=0\n for i in arr:\n if self.isPrime(i.count('1')):\n # print(i)\n count+=1\n return count", "slug": "prime-number-of-set-bits-in-binary-representation", "post_title": "Simple python code", "user": "amannarayansingh10", "upvotes": 1, "views": 105, "problem_title": "prime number of set bits in binary representation", "number": 762, "acceptance": 0.6779999999999999, "difficulty": "Easy", "__index_level_0__": 12396, "question": "Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.\nRecall that the number of set bits an integer has is the number of 1's present when written in binary.\nFor example, 21 written in binary is 10101, which has 3 set bits.\n Example 1:\nInput: left = 6, right = 10\nOutput: 4\nExplanation:\n6 -> 110 (2 set bits, 2 is prime)\n7 -> 111 (3 set bits, 3 is prime)\n8 -> 1000 (1 set bit, 1 is not prime)\n9 -> 1001 (2 set bits, 2 is prime)\n10 -> 1010 (2 set bits, 2 is prime)\n4 numbers have a prime number of set bits.\nExample 2:\nInput: left = 10, right = 15\nOutput: 5\nExplanation:\n10 -> 1010 (2 set bits, 2 is prime)\n11 -> 1011 (3 set bits, 3 is prime)\n12 -> 1100 (2 set bits, 2 is prime)\n13 -> 1101 (3 set bits, 3 is prime)\n14 -> 1110 (3 set bits, 3 is prime)\n15 -> 1111 (4 set bits, 4 is not prime)\n5 numbers have a prime number of set bits.\n Constraints:\n1 <= left <= right <= 106\n0 <= right - left <= 104" }, { "post_href": "https://leetcode.com/problems/partition-labels/discuss/1868757/Python3-GREEDY-VALIDATION-(-)-Explained", "python_solutions": "class Solution:\n def partitionLabels(self, s: str) -> List[int]:\n L = len(s)\n last = {s[i]: i for i in range(L)} # last appearance of the letter\n i, ans = 0, []\n while i < L:\n end, j = last[s[i]], i + 1\n while j < end: # validation of the part [i, end]\n if last[s[j]] > end:\n end = last[s[j]] # extend the part\n j += 1\n \n ans.append(end - i + 1)\n i = end + 1\n \n return ans", "slug": "partition-labels", "post_title": "\u2714\ufe0f [Python3] GREEDY VALIDATION \u30fe(\uff3e-\uff3e)\u30ce, Explained", "user": "artod", "upvotes": 63, "views": 5700, "problem_title": "partition labels", "number": 763, "acceptance": 0.7979999999999999, "difficulty": "Medium", "__index_level_0__": 12410, "question": "You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.\nNote that the partition is done so that after concatenating all the parts in order, the resultant string should be s.\nReturn a list of integers representing the size of these parts.\n Example 1:\nInput: s = \"ababcbacadefegdehijhklij\"\nOutput: [9,7,8]\nExplanation:\nThe partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.\nExample 2:\nInput: s = \"eccbbbbdec\"\nOutput: [10]\n Constraints:\n1 <= s.length <= 500\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/largest-plus-sign/discuss/833937/Python-3-or-DP-Bomb-Enemy-or-Explanations", "python_solutions": "class Solution:\n def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:\n mat = [[1]*N for _ in range(N)]\n for x, y in mines: mat[x][y] = 0 # create matrix with mine\n \n up = [[0]*N for _ in range(N)] # count 1s above mat[i][j] if mat[i][j] is 1\n for i in range(N):\n for j in range(N):\n if mat[i][j]: \n up[i][j] = 1\n if i > 0: up[i][j] += up[i-1][j] \n \n down = [[0]*N for _ in range(N)] # count 1s below mat[i][j] if mat[i][j] is 1\n for i in range(N-1, -1, -1):\n for j in range(N):\n if mat[i][j]: \n down[i][j] = 1\n if i < N-1: down[i][j] += down[i+1][j] \n \n left = [[0]*N for _ in range(N)] # count 1s on the left side of mat[i][j] if mat[i][j] is 1\n for i in range(N):\n for j in range(N):\n if mat[i][j]:\n left[i][j] = 1\n if j > 0: left[i][j] += left[i][j-1]\n \n right = [[0]*N for _ in range(N)] # count 1s on the right side of mat[i][j] if mat[i][j] is 1\n for i in range(N):\n for j in range(N-1, -1, -1):\n if mat[i][j]:\n right[i][j] = 1\n if j < N-1: right[i][j] += right[i][j+1]\n \n\t\t# find the largest + sign by using cached directions information\n return max(min([up[i][j], down[i][j], left[i][j], right[i][j]]) for i in range(N) for j in range(N))", "slug": "largest-plus-sign", "post_title": "Python 3 | DP - Bomb Enemy | Explanations", "user": "idontknoooo", "upvotes": 5, "views": 396, "problem_title": "largest plus sign", "number": 764, "acceptance": 0.484, "difficulty": "Medium", "__index_level_0__": 12461, "question": "You are given an integer n. You have an n x n binary grid grid with all values initially 1's except for some indices given in the array mines. The ith element of the array mines is defined as mines[i] = [xi, yi] where grid[xi][yi] == 0.\nReturn the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.\nAn axis-aligned plus sign of 1's of order k has some center grid[r][c] == 1 along with four arms of length k - 1 going up, down, left, and right, and made of 1's. Note that there could be 0's or 1's beyond the arms of the plus sign, only the relevant area of the plus sign is checked for 1's.\n Example 1:\nInput: n = 5, mines = [[4,2]]\nOutput: 2\nExplanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.\nExample 2:\nInput: n = 1, mines = [[0,0]]\nOutput: 0\nExplanation: There is no plus sign, so return 0.\n Constraints:\n1 <= n <= 500\n1 <= mines.length <= 5000\n0 <= xi, yi < n\nAll the pairs (xi, yi) are unique." }, { "post_href": "https://leetcode.com/problems/couples-holding-hands/discuss/1258087/Python3-a-few-approaches", "python_solutions": "class Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n loc = {x: i for i, x in enumerate(row)}\n ans = 0\n for i in range(0, len(row), 2): \n p = row[i] - 1 if row[i]&1 else row[i]+1\n if row[i+1] != p: \n ans += 1\n ii = loc[p]\n loc[row[i+1]], loc[row[ii]] = loc[row[ii]], loc[row[i+1]] # swap mappings\n row[i+1], row[ii] = row[ii], row[i+1] # swap values \n return ans", "slug": "couples-holding-hands", "post_title": "[Python3] a few approaches", "user": "ye15", "upvotes": 3, "views": 84, "problem_title": "couples holding hands", "number": 765, "acceptance": 0.569, "difficulty": "Hard", "__index_level_0__": 12469, "question": "There are n couples sitting in 2n seats arranged in a row and want to hold hands.\nThe people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).\nReturn the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.\n Example 1:\nInput: row = [0,2,1,3]\nOutput: 1\nExplanation: We only need to swap the second (row[1]) and third (row[2]) person.\nExample 2:\nInput: row = [3,2,0,1]\nOutput: 0\nExplanation: All couples are already seated side by side.\n Constraints:\n2n == row.length\n2 <= n <= 30\nn is even.\n0 <= row[i] < 2n\nAll the elements of row are unique." }, { "post_href": "https://leetcode.com/problems/toeplitz-matrix/discuss/2761795/Python-Simple-and-Easy-Way-to-Solve-or-97-Faster", "python_solutions": "class Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]])->bool:\n r_len, c_len = len(matrix),len(matrix[0])\n \n for r in range (1, r_len):\n for c in range (1, c_len):\n if matrix[r][c]!=matrix[r-1][c-1]:\n return False\n \n return True", "slug": "toeplitz-matrix", "post_title": "\u2714\ufe0f Python Simple and Easy Way to Solve | 97% Faster \ud83d\udd25", "user": "pniraj657", "upvotes": 3, "views": 182, "problem_title": "toeplitz matrix", "number": 766, "acceptance": 0.688, "difficulty": "Easy", "__index_level_0__": 12473, "question": "Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.\nA matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.\n Example 1:\nInput: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\nOutput: true\nExplanation:\nIn the above grid, the diagonals are:\n\"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\nIn each diagonal all elements are the same, so the answer is True.\nExample 2:\nInput: matrix = [[1,2],[2,2]]\nOutput: false\nExplanation:\nThe diagonal \"[1, 2]\" has different elements.\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 20\n0 <= matrix[i][j] <= 99\n Follow up:\nWhat if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?\nWhat if the matrix is so large that you can only load up a partial row into the memory at once?" }, { "post_href": "https://leetcode.com/problems/reorganize-string/discuss/488325/Python-8-Liner-Memory-usage-less-than-100", "python_solutions": "class Solution:\n def reorganizeString(self, S: str) -> str:\n counter = collections.Counter(S)\n i, res, n = 0, [None] * len(S), len(S)\n for k in sorted(counter, key = counter.get, reverse = True):\n if counter[k] > n // 2 + (n % 2): return \"\"\n for j in range(counter[k]):\n if i >= n: i = 1\n res[i] = k; i += 2\n return \"\".join(res)", "slug": "reorganize-string", "post_title": "Python - 8 Liner - Memory usage less than 100%", "user": "mmbhatk", "upvotes": 9, "views": 1700, "problem_title": "reorganize string", "number": 767, "acceptance": 0.528, "difficulty": "Medium", "__index_level_0__": 12530, "question": "Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.\nReturn any possible rearrangement of s or return \"\" if not possible.\n Example 1:\nInput: s = \"aab\"\nOutput: \"aba\"\nExample 2:\nInput: s = \"aaab\"\nOutput: \"\"\n Constraints:\n1 <= s.length <= 500\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/max-chunks-to-make-sorted-ii/discuss/1498733/Easy-to-Understand-oror-98-faster-oror-Well-Explained", "python_solutions": "class Solution:\ndef maxChunksToSorted(self, nums: List[int]) -> int:\n \n st = []\n for n in nums:\n if len(st)==0 or st[-1]<=n:\n st.append(n)\n else:\n ma = st[-1]\n while st and st[-1]>n:\n ma = max(ma,st.pop())\n st.append(ma)\n \n return len(st)", "slug": "max-chunks-to-make-sorted-ii", "post_title": "\ud83d\udccc\ud83d\udccc Easy-to-Understand || 98% faster || Well-Explained \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 14, "views": 659, "problem_title": "max chunks to make sorted ii", "number": 768, "acceptance": 0.528, "difficulty": "Hard", "__index_level_0__": 12556, "question": "You are given an integer array arr.\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\nReturn the largest number of chunks we can make to sort the array.\n Example 1:\nInput: arr = [5,4,3,2,1]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\nExample 2:\nInput: arr = [2,1,3,4,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [2, 1], [3, 4, 4].\nHowever, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n Constraints:\n1 <= arr.length <= 2000\n0 <= arr[i] <= 108" }, { "post_href": "https://leetcode.com/problems/max-chunks-to-make-sorted/discuss/1579999/Python3-Solution-with-using-stack", "python_solutions": "class Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n stack = []\n \n for num in arr:\n lagest = num\n while stack and num < stack[-1]:\n lagest = max(lagest, stack.pop())\n\n stack.append(lagest)\n \n return len(stack)", "slug": "max-chunks-to-make-sorted", "post_title": "[Python3] Solution with using stack", "user": "maosipov11", "upvotes": 1, "views": 95, "problem_title": "max chunks to make sorted", "number": 769, "acceptance": 0.5820000000000001, "difficulty": "Medium", "__index_level_0__": 12563, "question": "You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].\nWe split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.\nReturn the largest number of chunks we can make to sort the array.\n Example 1:\nInput: arr = [4,3,2,1,0]\nOutput: 1\nExplanation:\nSplitting into two or more chunks will not return the required result.\nFor example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.\nExample 2:\nInput: arr = [1,0,2,3,4]\nOutput: 4\nExplanation:\nWe can split into two chunks, such as [1, 0], [2, 3, 4].\nHowever, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.\n Constraints:\nn == arr.length\n1 <= n <= 10\n0 <= arr[i] < n\nAll the elements of arr are unique." }, { "post_href": "https://leetcode.com/problems/jewels-and-stones/discuss/362196/Solution-in-Python-3-(beats-~94)-(one-line)-(three-solutions)", "python_solutions": "class Solution:\n def numJewelsInStones(self, J: str, S: str) -> int:\n \treturn sum(i in J for i in S)\n\n\n\nclass Solution:\n def numJewelsInStones(self, J: str, S: str) -> int:\n \treturn sum(S.count(i) for i in J)\n\n\n\nfrom collections import Counter\n\nclass Solution:\n def numJewelsInStones(self, J: str, S: str) -> int:\n \treturn sum(Counter(S)[i] for i in J)\n\t\t\n\t\t\n\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "jewels-and-stones", "post_title": "Solution in Python 3 (beats ~94%) (one line) (three solutions)", "user": "junaidmansuri", "upvotes": 28, "views": 4500, "problem_title": "jewels and stones", "number": 771, "acceptance": 0.8809999999999999, "difficulty": "Easy", "__index_level_0__": 12569, "question": "You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels.\nLetters are case sensitive, so \"a\" is considered a different type of stone from \"A\".\n Example 1:\nInput: jewels = \"aA\", stones = \"aAAbbbb\"\nOutput: 3\nExample 2:\nInput: jewels = \"z\", stones = \"ZZ\"\nOutput: 0\n Constraints:\n1 <= jewels.length, stones.length <= 50\njewels and stones consist of only English letters.\nAll the characters of jewels are unique." }, { "post_href": "https://leetcode.com/problems/sliding-puzzle/discuss/2831256/Python-BFS%3A-77-time-70-space", "python_solutions": "class Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n def isSolved(board):\n if board[-1] != 0: return False\n for i in range(5):\n if board[i] != i + 1: return False\n return True\n \n swap = {\n 0: [1, 3],\n 1: [0, 2, 4],\n 2: [1, 5],\n 3: [0, 4],\n 4: [1, 3, 5],\n 5: [2, 4],\n }\n\n q = [board[0] + board[1]]\n steps = 0\n seen = set()\n while (len(q)):\n new_q = []\n for board in q:\n if tuple(board) in seen: continue\n seen.add(tuple(board))\n if isSolved(board): return steps\n\n zeroIdx = board.index(0)\n for swapIdx in swap[zeroIdx]:\n copy = board.copy()\n copy[zeroIdx], copy[swapIdx] = copy[swapIdx], copy[zeroIdx]\n new_q.append(copy)\n steps += 1\n q = new_q\n\n return -1", "slug": "sliding-puzzle", "post_title": "Python BFS: 77% time, 70% space", "user": "hqz3", "upvotes": 0, "views": 2, "problem_title": "sliding puzzle", "number": 773, "acceptance": 0.639, "difficulty": "Hard", "__index_level_0__": 12629, "question": "On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.\nThe state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\nGiven the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.\n Example 1:\nInput: board = [[1,2,3],[4,0,5]]\nOutput: 1\nExplanation: Swap the 0 and the 5 in one move.\nExample 2:\nInput: board = [[1,2,3],[5,4,0]]\nOutput: -1\nExplanation: No number of moves will make the board solved.\nExample 3:\nInput: board = [[4,1,2],[5,0,3]]\nOutput: 5\nExplanation: 5 is the smallest number of moves that solves the board.\nAn example path:\nAfter move 0: [[4,1,2],[5,0,3]]\nAfter move 1: [[4,1,2],[0,5,3]]\nAfter move 2: [[0,1,2],[4,5,3]]\nAfter move 3: [[1,0,2],[4,5,3]]\nAfter move 4: [[1,2,0],[4,5,3]]\nAfter move 5: [[1,2,3],[4,5,0]]\n Constraints:\nboard.length == 2\nboard[i].length == 3\n0 <= board[i][j] <= 5\nEach value board[i][j] is unique." }, { "post_href": "https://leetcode.com/problems/global-and-local-inversions/discuss/1084172/(Optimal-Solution)-Thinking-Process-Explained-in-More-Detail-than-You'd-Ever-Want", "python_solutions": "class Solution:\n def isIdealPermutation(self, A: List[int]) -> bool:\n for i, a in enumerate(A):\n if (abs(a - i) > 1):\n return False\n \n return True", "slug": "global-and-local-inversions", "post_title": "(Optimal Solution) Thinking Process Explained in More Detail than You'd Ever Want", "user": "valige7091", "upvotes": 3, "views": 215, "problem_title": "global and local inversions", "number": 775, "acceptance": 0.436, "difficulty": "Medium", "__index_level_0__": 12635, "question": "You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].\nThe number of global inversions is the number of the different pairs (i, j) where:\n0 <= i < j < n\nnums[i] > nums[j]\nThe number of local inversions is the number of indices i where:\n0 <= i < n - 1\nnums[i] > nums[i + 1]\nReturn true if the number of global inversions is equal to the number of local inversions.\n Example 1:\nInput: nums = [1,0,2]\nOutput: true\nExplanation: There is 1 global inversion and 1 local inversion.\nExample 2:\nInput: nums = [1,2,0]\nOutput: false\nExplanation: There are 2 global inversions and 1 local inversion.\n Constraints:\nn == nums.length\n1 <= n <= 105\n0 <= nums[i] < n\nAll the integers of nums are unique.\nnums is a permutation of all the numbers in the range [0, n - 1]." }, { "post_href": "https://leetcode.com/problems/swap-adjacent-in-lr-string/discuss/2712752/Python3-Solution-or-O(n)-or-Clean-and-Concise", "python_solutions": "class Solution:\n def canTransform(self, S, E):\n L, R, X = 0, 0, 0\n for i, j in zip(S, E):\n L += (j == 'L')\n R += (i == 'R')\n if i == 'R' and L: return False\n if j == 'L' and R: return False\n L -= (i == 'L')\n R -= (j == 'R')\n if L < 0 or R < 0: return False\n X += (i == 'X') - (j == 'X')\n return X == 0", "slug": "swap-adjacent-in-lr-string", "post_title": "\u2714 Python3 Solution | O(n) | Clean and Concise", "user": "satyam2001", "upvotes": 0, "views": 10, "problem_title": "swap adjacent in lr string", "number": 777, "acceptance": 0.371, "difficulty": "Medium", "__index_level_0__": 12645, "question": "In a string composed of 'L', 'R', and 'X' characters, like \"RXXLRXRXL\", a move consists of either replacing one occurrence of \"XL\" with \"LX\", or replacing one occurrence of \"RX\" with \"XR\". Given the starting string start and the ending string end, return True if and only if there exists a sequence of moves to transform one string to the other.\n Example 1:\nInput: start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\nOutput: true\nExplanation: We can transform start to end following these steps:\nRXXLRXRXL ->\nXRXLRXRXL ->\nXRLXRXRXL ->\nXRLXXRRXL ->\nXRLXXRRLX\nExample 2:\nInput: start = \"X\", end = \"L\"\nOutput: false\n Constraints:\n1 <= start.length <= 104\nstart.length == end.length\nBoth start and end will only consist of characters in 'L', 'R', and 'X'." }, { "post_href": "https://leetcode.com/problems/swim-in-rising-water/discuss/2464943/Easy-to-follow-python3-solutoon", "python_solutions": "class Solution:\n # O(max(n^2, m)) time, h --> the highest elevation in the grid\n # O(n^2) space,\n # Approach: BFS, Priority queue\n # I wld advise to do task scheduler question, it's pretty similar\n # except that u apply bfs to traverse the grid 4 directionally\n def swimInWater(self, grid: List[List[int]]) -> int:\n n = len(grid)\n if n == 1:\n return 0\n \n def getNeighbours(coord: Tuple) -> List[Tuple]:\n i, j = coord\n n = len(grid)\n neighbours = []\n \n if i < n-1:\n neighbours.append((i+1, j))\n if i > 0:\n neighbours.append((i-1, j))\n if j < n-1:\n neighbours.append((i, j+1))\n if j > 0:\n neighbours.append((i, j-1))\n \n return neighbours\n \n qu = deque()\n waiting_qu = []\n vstd = set()\n waiting_qu.append([grid[0][0], (0, 0)])\n vstd.add((0, 0))\n time = 0\n \n while waiting_qu:\n time +=1\n while waiting_qu and waiting_qu[0][0] <= time:\n qu.append(heapq.heappop(waiting_qu)[1])\n \n while qu:\n cell = qu.popleft()\n if cell == (n-1, n-1):\n return time\n nbrs = getNeighbours(cell)\n for nb in nbrs:\n if nb in vstd: continue\n x, y = nb\n elevation = grid[x][y]\n vstd.add(nb)\n if elevation > time:\n heapq.heappush(waiting_qu, [elevation, nb])\n else:\n qu.append(nb)\n \n return -1", "slug": "swim-in-rising-water", "post_title": "Easy to follow python3 solutoon", "user": "destifo", "upvotes": 1, "views": 34, "problem_title": "swim in rising water", "number": 778, "acceptance": 0.597, "difficulty": "Hard", "__index_level_0__": 12652, "question": "You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).\nThe 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 distances in zero time. Of course, you must stay within the boundaries of the grid during your swim.\nReturn the least time until you can reach the bottom right square (n - 1, n - 1) if you start at the top left square (0, 0).\n Example 1:\nInput: grid = [[0,2],[1,3]]\nOutput: 3\nExplanation:\nAt time 0, you are in grid location (0, 0).\nYou cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\nYou cannot reach point (1, 1) until time 3.\nWhen the depth of water is 3, we can swim anywhere inside the grid.\nExample 2:\nInput: grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]\nOutput: 16\nExplanation: The final route is shown.\nWe need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n Constraints:\nn == grid.length\nn == grid[i].length\n1 <= n <= 50\n0 <= grid[i][j] < n2\nEach value grid[i][j] is unique." }, { "post_href": "https://leetcode.com/problems/k-th-symbol-in-grammar/discuss/945679/Python-recursive-everything-you-need-to-know", "python_solutions": "class Solution:\n \n def kthGrammar(self, N: int, K: int) -> int:\n if N == 1: \n return 0\n half = 2**(N - 2) \n \n if K > half:\n return 1 if self.kthGrammar(N - 1, K - half) == 0 else 0\n else:\n return self.kthGrammar(N - 1, K)", "slug": "k-th-symbol-in-grammar", "post_title": "Python recursive, everything you need to know", "user": "lattices", "upvotes": 6, "views": 343, "problem_title": "k th symbol in grammar", "number": 779, "acceptance": 0.409, "difficulty": "Medium", "__index_level_0__": 12665, "question": "We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.\nFor example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.\nGiven two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.\n Example 1:\nInput: n = 1, k = 1\nOutput: 0\nExplanation: row 1: 0\nExample 2:\nInput: n = 2, k = 1\nOutput: 0\nExplanation: \nrow 1: 0\nrow 2: 01\nExample 3:\nInput: n = 2, k = 2\nOutput: 1\nExplanation: \nrow 1: 0\nrow 2: 01\n Constraints:\n1 <= n <= 30\n1 <= k <= 2n - 1" }, { "post_href": "https://leetcode.com/problems/reaching-points/discuss/808072/Python-recursive-solution-runtime-beats-98.91", "python_solutions": "class Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n if sx > tx or sy > ty: return False\n if sx == tx: return (ty-sy)%sx == 0 # only change y\n if sy == ty: return (tx-sx)%sy == 0\n if tx > ty: \n return self.reachingPoints(sx, sy, tx%ty, ty) # make sure tx%ty < ty\n elif tx < ty: \n return self.reachingPoints(sx, sy, tx, ty%tx)\n else:\n return False", "slug": "reaching-points", "post_title": "Python recursive solution runtime beats 98.91 %", "user": "yiz486", "upvotes": 14, "views": 3300, "problem_title": "reaching points", "number": 780, "acceptance": 0.324, "difficulty": "Hard", "__index_level_0__": 12688, "question": "Given four integers sx, sy, tx, and ty, return true if it is possible to convert the point (sx, sy) to the point (tx, ty) through some operations, or false otherwise.\nThe allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).\n Example 1:\nInput: sx = 1, sy = 1, tx = 3, ty = 5\nOutput: true\nExplanation:\nOne series of moves that transforms the starting point to the target is:\n(1, 1) -> (1, 2)\n(1, 2) -> (3, 2)\n(3, 2) -> (3, 5)\nExample 2:\nInput: sx = 1, sy = 1, tx = 2, ty = 2\nOutput: false\nExample 3:\nInput: sx = 1, sy = 1, tx = 1, ty = 1\nOutput: true\n Constraints:\n1 <= sx, sy, tx, ty <= 109" }, { "post_href": "https://leetcode.com/problems/rabbits-in-forest/discuss/838445/Python-3-or-Hash-Table-1-liner-or-Explanations", "python_solutions": "class Solution:\n def numRabbits(self, answers: List[int]) -> int:\n return sum((key+1) * math.ceil(freq / (key+1)) if key+1 < freq else key+1 for key, freq in collections.Counter(answers).items())", "slug": "rabbits-in-forest", "post_title": "Python 3 | Hash Table 1 liner | Explanations", "user": "idontknoooo", "upvotes": 1, "views": 178, "problem_title": "rabbits in forest", "number": 781, "acceptance": 0.552, "difficulty": "Medium", "__index_level_0__": 12696, "question": "There is a forest with an unknown number of rabbits. We asked n rabbits \"How many rabbits have the same color as you?\" and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.\nGiven the array answers, return the minimum number of rabbits that could be in the forest.\n Example 1:\nInput: answers = [1,1,2]\nOutput: 5\nExplanation:\nThe two rabbits that answered \"1\" could both be the same color, say red.\nThe rabbit that answered \"2\" can't be red or the answers would be inconsistent.\nSay the rabbit that answered \"2\" was blue.\nThen there should be 2 other blue rabbits in the forest that didn't answer into the array.\nThe smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\nExample 2:\nInput: answers = [10,10,10]\nOutput: 11\n Constraints:\n1 <= answers.length <= 1000\n0 <= answers[i] < 1000" }, { "post_href": "https://leetcode.com/problems/transform-to-chessboard/discuss/1305763/Python3-alternating-numbers", "python_solutions": "class Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n n = len(board)\n \n def fn(vals): \n \"\"\"Return min moves to transform to chessboard.\"\"\"\n total = odd = 0 \n for i, x in enumerate(vals): \n if vals[0] == x: \n total += 1\n if i&1: odd += 1\n elif vals[0] ^ x != (1 << n) - 1: return inf\n ans = inf \n if len(vals) <= 2*total <= len(vals)+1: ans = min(ans, odd)\n if len(vals)-1 <= 2*total <= len(vals): ans = min(ans, total - odd)\n return ans \n \n rows, cols = [0]*n, [0]*n\n for i in range(n): \n for j in range(n): \n if board[i][j]: \n rows[i] ^= 1 << j \n cols[j] ^= 1 << i\n ans = fn(rows) + fn(cols)\n return ans if ans < inf else -1", "slug": "transform-to-chessboard", "post_title": "[Python3] alternating numbers", "user": "ye15", "upvotes": 8, "views": 379, "problem_title": "transform to chessboard", "number": 782, "acceptance": 0.518, "difficulty": "Hard", "__index_level_0__": 12706, "question": "You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.\nReturn the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.\nA chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.\n Example 1:\nInput: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\nOutput: 2\nExplanation: One potential sequence of moves is shown.\nThe first move swaps the first and second column.\nThe second move swaps the second and third row.\nExample 2:\nInput: board = [[0,1],[1,0]]\nOutput: 0\nExplanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.\nExample 3:\nInput: board = [[1,0],[1,0]]\nOutput: -1\nExplanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.\n Constraints:\nn == board.length\nn == board[i].length\n2 <= n <= 30\nboard[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/minimum-distance-between-bst-nodes/discuss/1957176/Python-In-Order-Traversal-Explained-Well-Via-Comments", "python_solutions": "class Solution:\n def minDiffInBST(self, root: Optional[TreeNode]) -> int:\n \n # list with two element\n # the first for the previous element\n # the second for the min value\n pre_mn = [-float(\"inf\"), float(\"inf\")]\n \n def dfs(tree):\n \n if not tree:\n return\n \n # Keep going to the left\n dfs(tree.left)\n \n # if we can't go further, update min and pre\n pre_mn[1] = min(pre_mn[1], abs(tree.val) - pre_mn[0])\n pre_mn[0] = tree.val\n \n # keep traversing in-order\n dfs(tree.right)\n \n dfs(root)\n \n # return min (the second element in the list)\n return pre_mn[1]", "slug": "minimum-distance-between-bst-nodes", "post_title": "Python In-Order Traversal, Explained Well Via Comments", "user": "Hejita", "upvotes": 1, "views": 89, "problem_title": "minimum distance between bst nodes", "number": 783, "acceptance": 0.569, "difficulty": "Easy", "__index_level_0__": 12707, "question": "Given the root of a Binary Search Tree (BST), return the minimum difference between the values of any two different nodes in the tree.\n Example 1:\nInput: root = [4,2,6,1,3]\nOutput: 1\nExample 2:\nInput: root = [1,0,48,null,null,12,49]\nOutput: 1\n Constraints:\nThe number of nodes in the tree is in the range [2, 100].\n0 <= Node.val <= 105\n Note: This question is the same as 530: https://leetcode.com/problems/minimum-absolute-difference-in-bst/" }, { "post_href": "https://leetcode.com/problems/letter-case-permutation/discuss/379928/Python-clear-solution", "python_solutions": "class Solution(object):\n def letterCasePermutation(self, S):\n \"\"\"\n :type S: str\n :rtype: List[str]\n \"\"\"\n def backtrack(sub=\"\", i=0):\n if len(sub) == len(S):\n res.append(sub)\n else:\n if S[i].isalpha():\n backtrack(sub + S[i].swapcase(), i + 1)\n backtrack(sub + S[i], i + 1)\n \n res = []\n backtrack()\n return res", "slug": "letter-case-permutation", "post_title": "Python clear solution", "user": "DenysCoder", "upvotes": 164, "views": 7000, "problem_title": "letter case permutation", "number": 784, "acceptance": 0.735, "difficulty": "Medium", "__index_level_0__": 12721, "question": "Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.\nReturn a list of all possible strings we could create. Return the output in any order.\n Example 1:\nInput: s = \"a1b2\"\nOutput: [\"a1b2\",\"a1B2\",\"A1b2\",\"A1B2\"]\nExample 2:\nInput: s = \"3z4\"\nOutput: [\"3z4\",\"3Z4\"]\n Constraints:\n1 <= s.length <= 12\ns consists of lowercase English letters, uppercase English letters, and digits." }, { "post_href": "https://leetcode.com/problems/is-graph-bipartite/discuss/1990803/JavaC%2B%2BPythonJavaScriptKotlinSwiftO(n)timeBEATS-99.97-MEMORYSPEED-0ms-APRIL-2022", "python_solutions": "class Solution:\n\n def isBipartite(self, graph: list[list[int]]) -> bool:\n\t\n vis = [False for n in range(0, len(graph))]\n \n while sum(vis) != len(graph): # Since graph isn't required to be connected this process needs to be repeated\n\n ind = vis.index(False) # Find the first entry in the visited list that is false\n vis[ind] = True\n grp = {ind:True} # initialize first node as part of group 1\n q = [ind] # Add current index to queue\n \n while q: # Go to each node in the graph\n u = q.pop(0)\n\n for v in graph[u]: # Go to each vertice connected to the current node\n\n if vis[v] == True: # If visited check that it is in the opposite group of the current node\n if grp[u] == grp[v]:\n return False # If a single edge does not lead to a group change return false\n\n else: # If not visited put v in opposite group of u, set to visited, and append to q\n vis[v] = True\n grp[v] = not grp[u]\n q.append(v)\n \n return True", "slug": "is-graph-bipartite", "post_title": "[Java/C++/Python/JavaScript/Kotlin/Swift]O(n)time/BEATS 99.97% MEMORY/SPEED 0ms APRIL 2022", "user": "cucerdariancatalin", "upvotes": 3, "views": 356, "problem_title": "is graph bipartite", "number": 785, "acceptance": 0.527, "difficulty": "Medium", "__index_level_0__": 12773, "question": "There is an undirected graph with n nodes, where each node is numbered between 0 and n - 1. You are given a 2D array graph, where graph[u] is an array of nodes that node u is adjacent to. More formally, for each v in graph[u], there is an undirected edge between node u and node v. The graph has the following properties:\nThere are no self-edges (graph[u] does not contain u).\nThere are no parallel edges (graph[u] does not contain duplicate values).\nIf v is in graph[u], then u is in graph[v] (the graph is undirected).\nThe graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.\nA graph is bipartite if the nodes can be partitioned into two independent sets A and B such that every edge in the graph connects a node in set A and a node in set B.\nReturn true if and only if it is bipartite.\n Example 1:\nInput: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]\nOutput: false\nExplanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.\nExample 2:\nInput: graph = [[1,3],[0,2],[1,3],[0,2]]\nOutput: true\nExplanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.\n Constraints:\ngraph.length == n\n1 <= n <= 100\n0 <= graph[u].length < n\n0 <= graph[u][i] <= n - 1\ngraph[u] does not contain u.\nAll the values of graph[u] are unique.\nIf graph[u] contains v, then graph[v] contains u." }, { "post_href": "https://leetcode.com/problems/k-th-smallest-prime-fraction/discuss/2121258/Explained-Easiest-Python-Solution", "python_solutions": "class Solution:\n\n\tdef kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:\n\t\tif len(arr) > 2:\n\t\t\tres = [] # list for storing the list: [prime fraction of arr[i]/arr[j], arr[i], arr[j]]\n\n\t\t\tfor i in range(len(arr)):\n\t\t\t\tfor j in range(i + 1, len(arr)):\n\t\t\t\t\t# creating and adding the sublist to res\n\t\t\t\t\ttmp = [arr[i] / arr[j], arr[i], arr[j]]\n\t\t\t\t\tres.append(tmp)\n\n\t\t\t# sorting res on the basis of value of arr[i] \n\t\t\tres.sort(key=lambda x: x[0])\n\n\t\t\t# creating and returning the required list\n\t\t\treturn [res[k - 1][1], res[k - 1][2]]\n\t\telse:\n\t\t\treturn arr", "slug": "k-th-smallest-prime-fraction", "post_title": "[Explained] Easiest Python Solution", "user": "the_sky_high", "upvotes": 2, "views": 180, "problem_title": "k th smallest prime fraction", "number": 786, "acceptance": 0.509, "difficulty": "Medium", "__index_level_0__": 12814, "question": "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.\nFor every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].\nReturn the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].\n Example 1:\nInput: arr = [1,2,3,5], k = 3\nOutput: [2,5]\nExplanation: The fractions to be considered in sorted order are:\n1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\nThe third fraction is 2/5.\nExample 2:\nInput: arr = [1,7], k = 1\nOutput: [1,7]\n Constraints:\n2 <= arr.length <= 1000\n1 <= arr[i] <= 3 * 104\narr[0] == 1\narr[i] is a prime number for i > 0.\nAll the numbers of arr are unique and sorted in strictly increasing order.\n1 <= k <= arr.length * (arr.length - 1) / 2\n Follow up: Can you solve the problem with better than O(n2) complexity?" }, { "post_href": "https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/2066105/Python-Easy-Solution-using-Dijkstra's-Algorithm", "python_solutions": "class Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n #Make graph\n adj_list = {i:[] for i in range(n)}\n for frm, to, price in flights:\n adj_list[frm].append((to, price))\n \n best_visited = [2**31]*n # Initialized to maximum\n \n prior_queue = [ (0, -1, src) ] # weight, steps, node\n\n while prior_queue:\n cost, steps, node = heapq.heappop(prior_queue)\n \n if best_visited[node] <= steps: # Have seen the node already, and the current steps are more than last time\n continue\n\n if steps > k: # More than k stops, invalid\n continue\n\n if node==dst: # reach the destination # as priority_queue is a minHeap so this cost is the most minimum cost.\n return cost\n \n best_visited[node] = steps # Update steps\n\n for neighb, weight in adj_list[node]:\n heapq.heappush(prior_queue, (cost + weight, steps + 1, neighb))\n\n return -1\n\t\t\n# Time: O(n * len(flights) * log(n))\n# Space: O(n)", "slug": "cheapest-flights-within-k-stops", "post_title": "Python Easy Solution using Dijkstra's Algorithm", "user": "samirpaul1", "upvotes": 6, "views": 445, "problem_title": "cheapest flights within k stops", "number": 787, "acceptance": 0.359, "difficulty": "Medium", "__index_level_0__": 12820, "question": "There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.\nYou are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.\n Example 1:\nInput: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\nOutput: 700\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\nNote that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.\nExample 2:\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\nOutput: 200\nExplanation:\nThe graph is shown above.\nThe optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.\nExample 3:\nInput: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\nOutput: 500\nExplanation:\nThe graph is shown above.\nThe optimal path with no stops from city 0 to 2 is marked in red and has cost 500.\n Constraints:\n1 <= n <= 100\n0 <= flights.length <= (n * (n - 1) / 2)\nflights[i].length == 3\n0 <= fromi, toi < n\nfromi != toi\n1 <= pricei <= 104\nThere will not be any multiple flights between two cities.\n0 <= src, dst, k < n\nsrc != dst" }, { "post_href": "https://leetcode.com/problems/rotated-digits/discuss/1205605/Python3-simple-solution-using-two-approaches", "python_solutions": "class Solution:\n def rotatedDigits(self, N: int) -> int:\n count = 0\n for x in range(1, N+1):\n x = str(x)\n if '3' in x or '4' in x or '7' in x:\n continue\n if '2' in x or '5' in x or '6' in x or '9' in x:\n count+=1\n return count", "slug": "rotated-digits", "post_title": "Python3 simple solution using two approaches", "user": "EklavyaJoshi", "upvotes": 4, "views": 207, "problem_title": "rotated digits", "number": 788, "acceptance": 0.568, "difficulty": "Medium", "__index_level_0__": 12834, "question": "An integer x is a good if after rotating each digit individually by 180 degrees, we get a valid number that is different from x. Each digit must be rotated - we cannot choose to leave it alone.\nA number is valid if each digit remains a digit after rotation. For example:\n0, 1, and 8 rotate to themselves,\n2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),\n6 and 9 rotate to each other, and\nthe rest of the numbers do not rotate to any other number and become invalid.\nGiven an integer n, return the number of good integers in the range [1, n].\n Example 1:\nInput: n = 10\nOutput: 4\nExplanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\nNote that 1 and 10 are not good numbers, since they remain unchanged after rotating.\nExample 2:\nInput: n = 1\nOutput: 0\nExample 3:\nInput: n = 2\nOutput: 1\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/escape-the-ghosts/discuss/1477363/Python-3-or-Manhattan-Distance-Math-or-Explanation", "python_solutions": "class Solution:\n def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:\n t_x, t_y = target\n m_x, m_y = abs(t_x), abs(t_y)\n for x, y in ghosts:\n manhattan = abs(t_x - x) + abs(t_y - y)\n if manhattan <= m_x + m_y:\n return False\n return True", "slug": "escape-the-ghosts", "post_title": "Python 3 | Manhattan Distance, Math | Explanation", "user": "idontknoooo", "upvotes": 1, "views": 117, "problem_title": "escape the ghosts", "number": 789, "acceptance": 0.607, "difficulty": "Medium", "__index_level_0__": 12845, "question": "You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget] that you are trying to get to. There are several ghosts on the map with their starting positions given as a 2D array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.\nEach turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west, or stay still. All actions happen simultaneously.\nYou escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.\nReturn true if it is possible to escape regardless of how the ghosts move, otherwise return false.\n Example 1:\nInput: ghosts = [[1,0],[0,3]], target = [0,1]\nOutput: true\nExplanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.\nExample 2:\nInput: ghosts = [[1,0]], target = [2,0]\nOutput: false\nExplanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.\nExample 3:\nInput: ghosts = [[2,0]], target = [1,0]\nOutput: false\nExplanation: The ghost can reach the target at the same time as you.\n Constraints:\n1 <= ghosts.length <= 100\nghosts[i].length == 2\n-104 <= xi, yi <= 104\nThere can be multiple ghosts in the same location.\ntarget.length == 2\n-104 <= xtarget, ytarget <= 104" }, { "post_href": "https://leetcode.com/problems/domino-and-tromino-tiling/discuss/1620809/PythonJAVACC%2B%2B-DP-oror-Image-Visualized-Explanation-oror-100-Faster-oror-O(N)", "python_solutions": "class Solution(object):\n def numTilings(self, n):\n dp = [1, 2, 5] + [0] * n\n for i in range(3, n):\n dp[i] = (dp[i - 1] * 2 + dp[i - 3]) % 1000000007\n return dp[n - 1]", "slug": "domino-and-tromino-tiling", "post_title": "\u2705 [Python/JAVA/C/C++] DP || Image Visualized Explanation || 100% Faster || O(N)", "user": "linfq", "upvotes": 84, "views": 2800, "problem_title": "domino and tromino tiling", "number": 790, "acceptance": 0.484, "difficulty": "Medium", "__index_level_0__": 12849, "question": "You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.\nGiven an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, return it modulo 109 + 7.\nIn a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.\n Example 1:\nInput: n = 3\nOutput: 5\nExplanation: The five different ways are show above.\nExample 2:\nInput: n = 1\nOutput: 1\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/custom-sort-string/discuss/2237060/Simple-yet-interview-friendly-or-Faster-than-99.97-or-Custom-Sorting-in-Python", "python_solutions": "class Solution:\n def customSortString(self, order: str, s: str) -> str:\n\n rank = [26]*26\n \n for i in range(len(order)):\n rank[ord(order[i]) - ord('a')] = i\n\n return \"\".join(sorted(list(s), key= lambda x: rank[ord(x) - ord('a')]))", "slug": "custom-sort-string", "post_title": "\u2705 Simple yet interview friendly | Faster than 99.97% | Custom Sorting in Python", "user": "reinkarnation", "upvotes": 2, "views": 62, "problem_title": "custom sort string", "number": 791, "acceptance": 0.693, "difficulty": "Medium", "__index_level_0__": 12858, "question": "You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.\nPermute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.\nReturn any permutation of s that satisfies this property.\n Example 1:\nInput: order = \"cba\", s = \"abcd\"\nOutput: \"cbad\"\nExplanation: \"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\".\nSince \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.\nExample 2:\nInput: order = \"bcafg\", s = \"abcd\"\nOutput: \"bcad\"\nExplanation: The characters \"b\", \"c\", and \"a\" from order dictate the order for the characters in s. The character \"d\" in s does not appear in order, so its position is flexible.\nFollowing the order of appearance in order, \"b\", \"c\", and \"a\" from s should be arranged as \"b\", \"c\", \"a\". \"d\" can be placed at any position since it's not in order. The output \"bcad\" correctly follows this rule. Other arrangements like \"bacd\" or \"bcda\" would also be valid, as long as \"b\", \"c\", \"a\" maintain their order.\n Constraints:\n1 <= order.length <= 26\n1 <= s.length <= 200\norder and s consist of lowercase English letters.\nAll the characters of order are unique." }, { "post_href": "https://leetcode.com/problems/number-of-matching-subsequences/discuss/1289476/Easy-Approach-oror-Well-explained-oror-95-faster", "python_solutions": "class Solution:\ndef numMatchingSubseq(self, s: str, words: List[str]) -> int:\n \n def is_sub(word):\n index=-1\n for ch in word:\n index=s.find(ch,index+1)\n if index==-1:\n return False\n return True\n \n c=0\n for word in words:\n if is_sub(word):\n c+=1\n \n return c", "slug": "number-of-matching-subsequences", "post_title": "\ud83d\udccc Easy-Approach || Well-explained || 95% faster \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 27, "views": 1200, "problem_title": "number of matching subsequences", "number": 792, "acceptance": 0.519, "difficulty": "Medium", "__index_level_0__": 12887, "question": "Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\nFor example, \"ace\" is a subsequence of \"abcde\".\n Example 1:\nInput: s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\nOutput: 3\nExplanation: There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".\nExample 2:\nInput: s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\nOutput: 2\n Constraints:\n1 <= s.length <= 5 * 104\n1 <= words.length <= 5000\n1 <= words[i].length <= 50\ns and words[i] consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/preimage-size-of-factorial-zeroes-function/discuss/1306028/Python3-binary-search", "python_solutions": "class Solution:\n def preimageSizeFZF(self, k: int) -> int:\n lo, hi = 0, 1 << 32\n while lo <= hi: \n mid = lo + hi >> 1\n x, y = mid, 0 \n while x: \n x //= 5\n y += x\n if y < k: lo = mid + 1\n elif y > k: hi = mid - 1\n else: return 5\n return 0", "slug": "preimage-size-of-factorial-zeroes-function", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 1, "views": 69, "problem_title": "preimage size of factorial zeroes function", "number": 793, "acceptance": 0.428, "difficulty": "Hard", "__index_level_0__": 12919, "question": "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.\nFor example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.\nGiven an integer k, return the number of non-negative integers x have the property that f(x) = k.\n Example 1:\nInput: k = 0\nOutput: 5\nExplanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.\nExample 2:\nInput: k = 5\nOutput: 0\nExplanation: There is no x such that x! ends in k = 5 zeroes.\nExample 3:\nInput: k = 3\nOutput: 5\n Constraints:\n0 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/valid-tic-tac-toe-state/discuss/2269469/Python3-oror-int-array-7-lines-w-explanation-oror-TM%3A-98-49", "python_solutions": "class Solution:\n def validTicTacToe(self, board: List[str]) -> bool:\n # The two criteria for a valid board are:\n # 1) num of Xs - num of Os is 0 or 1\n # 2) X is not a winner if the # of moves is even, and\n # O is not a winner if the # of moves is odd.\n\n d = {'X': 1, 'O': -1, ' ': 0} # transform the 1x3 str array to a 1x9 int array\n s = [d[ch] for ch in ''.join(board)] # Ex: [\"XOX\",\" X \",\" \"] --> [1,-1,1,0,1,0,0,0,0]\n sm = sum(s)\n\n if sm>>1: return False # <-- criterion 1\n \n n = -3 if sm == 1 else 3 # <-- criterion 2.\n if n in {s[0]+s[1]+s[2], s[3]+s[4]+s[5], s[6]+s[7]+s[8], \n s[0]+s[3]+s[6], s[1]+s[4]+s[7], s[2]+s[5]+s[8], # the elements of the set are \n s[0]+s[4]+s[8], s[2]+s[4]+s[6]}: return False # the rows, cols, and diags\n \n return True # <-- both criteria are true", "slug": "valid-tic-tac-toe-state", "post_title": "Python3 || int array, 7 lines, w/ explanation || T/M: 98%/ 49%", "user": "warrenruud", "upvotes": 4, "views": 221, "problem_title": "valid tic tac toe state", "number": 794, "acceptance": 0.351, "difficulty": "Medium", "__index_level_0__": 12922, "question": "Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.\nThe board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.\nHere are the rules of Tic-Tac-Toe:\nPlayers take turns placing characters into empty squares ' '.\nThe first player always places 'X' characters, while the second player always places 'O' characters.\n'X' and 'O' characters are always placed into empty squares, never filled ones.\nThe game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\nThe game also ends if all squares are non-empty.\nNo more moves can be played if the game is over.\n Example 1:\nInput: board = [\"O \",\" \",\" \"]\nOutput: false\nExplanation: The first player always plays \"X\".\nExample 2:\nInput: board = [\"XOX\",\" X \",\" \"]\nOutput: false\nExplanation: Players take turns making moves.\nExample 3:\nInput: board = [\"XOX\",\"O O\",\"XOX\"]\nOutput: true\n Constraints:\nboard.length == 3\nboard[i].length == 3\nboard[i][j] is either 'X', 'O', or ' '." }, { "post_href": "https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum/discuss/2304108/Python-or-Two-pointer-technique-or-Easy-solution", "python_solutions": "class Solution:\n def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:\n start,end = -1, -1\n res = 0\n for i in range(len(nums)):\n if nums[i] > right:\n start = end = i\n continue\n \n if nums[i] >= left:\n end = i\n \n res += end - start\n return res", "slug": "number-of-subarrays-with-bounded-maximum", "post_title": "Python | Two pointer technique | Easy solution", "user": "__Asrar", "upvotes": 2, "views": 79, "problem_title": "number of subarrays with bounded maximum", "number": 795, "acceptance": 0.527, "difficulty": "Medium", "__index_level_0__": 12935, "question": "Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right].\nThe test cases are generated so that the answer will fit in a 32-bit integer.\n Example 1:\nInput: nums = [2,1,4,3], left = 2, right = 3\nOutput: 3\nExplanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].\nExample 2:\nInput: nums = [2,9,2,5,6], left = 2, right = 8\nOutput: 7\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109\n0 <= left <= right <= 109" }, { "post_href": "https://leetcode.com/problems/rotate-string/discuss/2369025/or-python3-or-ONE-LINE-or-FASTER-THAN-99-or", "python_solutions": "class Solution:\n def rotateString(self, s: str, goal: str) -> bool:\n return len(s) == len(goal) and s in goal+goal", "slug": "rotate-string", "post_title": "\u2705 | python3 | ONE LINE | FASTER THAN 99% | \ud83d\udd25\ud83d\udcaa", "user": "sahelriaz", "upvotes": 18, "views": 628, "problem_title": "rotate string", "number": 796, "acceptance": 0.542, "difficulty": "Easy", "__index_level_0__": 12939, "question": "Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.\nA shift on s consists of moving the leftmost character of s to the rightmost position.\nFor example, if s = \"abcde\", then it will be \"bcdea\" after one shift.\n Example 1:\nInput: s = \"abcde\", goal = \"cdeab\"\nOutput: true\nExample 2:\nInput: s = \"abcde\", goal = \"abced\"\nOutput: false\n Constraints:\n1 <= s.length, goal.length <= 100\ns and goal consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/all-paths-from-source-to-target/discuss/752799/Python-simple-BFS-solution-explained", "python_solutions": "class Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n q = [[0]]\n result = []\n target = len(graph) - 1\n \n while q:\n temp = q.pop(0)\n \n if temp[-1] == target:\n result.append(temp)\n else:\n for neighbor in graph[temp[-1]]:\n q.append(temp + [neighbor])\n \n return result", "slug": "all-paths-from-source-to-target", "post_title": "Python simple BFS solution explained", "user": "spec_he123", "upvotes": 6, "views": 787, "problem_title": "all paths from source to target", "number": 797, "acceptance": 0.815, "difficulty": "Medium", "__index_level_0__": 12966, "question": "Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1 and return them in any order.\nThe graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).\n Example 1:\nInput: graph = [[1,2],[3],[3],[]]\nOutput: [[0,1,3],[0,2,3]]\nExplanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.\nExample 2:\nInput: graph = [[4,3,1],[3,2,4],[3],[4],[]]\nOutput: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]\n Constraints:\nn == graph.length\n2 <= n <= 15\n0 <= graph[i][j] < n\ngraph[i][j] != i (i.e., there will be no self-loops).\nAll the elements of graph[i] are unique.\nThe input graph is guaranteed to be a DAG." }, { "post_href": "https://leetcode.com/problems/smallest-rotation-with-highest-score/discuss/1307760/Python3-difference-array", "python_solutions": "class Solution:\n def bestRotation(self, nums: List[int]) -> int:\n diff = [0]*(len(nums) + 1)\n for i, x in enumerate(nums): \n diff[i+1] += 1\n if x <= i: diff[0] += 1\n diff[(i-x)%len(nums) + 1] -= 1\n \n ans = prefix = 0 \n mx = -inf \n for i, x in enumerate(diff): \n prefix += x\n if prefix > mx: mx, ans = prefix, i\n return ans", "slug": "smallest-rotation-with-highest-score", "post_title": "[Python3] difference array", "user": "ye15", "upvotes": 0, "views": 137, "problem_title": "smallest rotation with highest score", "number": 798, "acceptance": 0.498, "difficulty": "Hard", "__index_level_0__": 13011, "question": "You are given an array nums. You can rotate it by a non-negative integer k so that the array becomes [nums[k], nums[k + 1], ... nums[nums.length - 1], nums[0], nums[1], ..., nums[k-1]]. Afterward, any entries that are less than or equal to their index are worth one point.\nFor example, if we have nums = [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].\nReturn the rotation index k that corresponds to the highest score we can achieve if we rotated nums by it. If there are multiple answers, return the smallest such index k.\n Example 1:\nInput: nums = [2,3,1,4,0]\nOutput: 3\nExplanation: Scores for each k are listed below: \nk = 0, nums = [2,3,1,4,0], score 2\nk = 1, nums = [3,1,4,0,2], score 3\nk = 2, nums = [1,4,0,2,3], score 3\nk = 3, nums = [4,0,2,3,1], score 4\nk = 4, nums = [0,2,3,1,4], score 3\nSo we should choose k = 3, which has the highest score.\nExample 2:\nInput: nums = [1,3,0,2,4]\nOutput: 0\nExplanation: nums will always have 3 points no matter how it shifts.\nSo we will choose the smallest k, which is 0.\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] < nums.length" }, { "post_href": "https://leetcode.com/problems/champagne-tower/discuss/1818232/Python-Easy-Solution-or-95-Faster-or-Dynamic-Programming", "python_solutions": "class Solution:\n def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:\n dp = [[0 for _ in range(x)] for x in range(1, query_row + 2)]\n dp[0][0] = poured\n \n for i in range(query_row):\n for j in range(len(dp[i])):\n temp = (dp[i][j] - 1) / 2.0\n if temp>0:\n dp[i+1][j] += temp\n dp[i+1][j+1] += temp\n \n return dp[query_row][query_glass] if dp[query_row][query_glass] <= 1 else 1", "slug": "champagne-tower", "post_title": "\u2714\ufe0f Python Easy Solution | 95% Faster | Dynamic Programming", "user": "pniraj657", "upvotes": 24, "views": 1300, "problem_title": "champagne tower", "number": 799, "acceptance": 0.513, "difficulty": "Medium", "__index_level_0__": 13013, "question": "We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row. Each glass holds one cup of champagne.\nThen, some champagne is poured into the first glass at the top. When the topmost glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it. When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on. (A glass at the bottom row has its excess champagne fall on the floor.)\nFor example, after one cup of champagne is poured, the top most glass is full. After two cups of champagne are poured, the two glasses on the second row are half full. After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now. After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.\nNow after pouring some non-negative integer cups of champagne, return how full the jth glass in the ith row is (both i and j are 0-indexed.)\n Example 1:\nInput: poured = 1, query_row = 1, query_glass = 1\nOutput: 0.00000\nExplanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)). There will be no excess liquid so all the glasses under the top glass will remain empty.\nExample 2:\nInput: poured = 2, query_row = 1, query_glass = 1\nOutput: 0.50000\nExplanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)). There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\nExample 3:\nInput: poured = 100000009, query_row = 33, query_glass = 17\nOutput: 1.00000\n Constraints:\n0 <= poured <= 109\n0 <= query_glass <= query_row < 100" }, { "post_href": "https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/discuss/932390/Python3-two-counters", "python_solutions": "class Solution:\n def minSwap(self, A: List[int], B: List[int]) -> int:\n ans = sm = lg = mx = 0\n for x, y in zip(A, B): \n if mx < min(x, y): # prev max < current min\n ans += min(sm, lg) # update answer & reset \n sm = lg = 0 \n mx = max(x, y)\n if x < y: sm += 1 # count \"x < y\"\n elif x > y: lg += 1 # count \"x > y\"\n return ans + min(sm, lg)", "slug": "minimum-swaps-to-make-sequences-increasing", "post_title": "[Python3] two counters", "user": "ye15", "upvotes": 8, "views": 237, "problem_title": "minimum swaps to make sequences increasing", "number": 801, "acceptance": 0.3929999999999999, "difficulty": "Hard", "__index_level_0__": 13030, "question": "You are given two integer arrays of the same length nums1 and nums2. In one operation, you are allowed to swap nums1[i] with nums2[i].\nFor example, if nums1 = [1,2,3,8], and nums2 = [5,6,7,4], you can swap the element at i = 3 to obtain nums1 = [1,2,3,4] and nums2 = [5,6,7,8].\nReturn the minimum number of needed operations to make nums1 and nums2 strictly increasing. The test cases are generated so that the given input always makes it possible.\nAn array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].\n Example 1:\nInput: nums1 = [1,3,5,4], nums2 = [1,2,3,7]\nOutput: 1\nExplanation: \nSwap nums1[3] and nums2[3]. Then the sequences are:\nnums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\nwhich are both strictly increasing.\nExample 2:\nInput: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]\nOutput: 1\n Constraints:\n2 <= nums1.length <= 105\nnums2.length == nums1.length\n0 <= nums1[i], nums2[i] <= 2 * 105" }, { "post_href": "https://leetcode.com/problems/find-eventual-safe-states/discuss/1317749/Python-DFS-Easy", "python_solutions": "class Solution:\n def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:\n n=len(graph)\n status=[0]*(n)\n res=[]\n \n def dfs(i):# this function will check is there any loop, cycle and i is a part of that loop,cycle \n if status[i]==\"visited\": #if this node is already visited, loop detected return true\n return True\n if status[i]==\"safe\": #if this node is previously visited and marked safe no need to repeat it ,return False no loop possible from it\n return False\n status[i]=\"visited\" # so we have visited this node\n for j in graph[i]:\n if dfs(j):# if loop detected return True\n return True\n status[i]=\"safe\" # if we reached till here means no loop detected from node i so this node is safe\n return False # no loop possible return false\n \n \n for i in range(n):\n if not dfs(i): #if no loop detected this node is safe \n res.append(i)\n return res", "slug": "find-eventual-safe-states", "post_title": "Python-DFS-Easy", "user": "manmohan1105", "upvotes": 9, "views": 575, "problem_title": "find eventual safe states", "number": 802, "acceptance": 0.5529999999999999, "difficulty": "Medium", "__index_level_0__": 13032, "question": "There is a directed graph of n nodes with each node labeled from 0 to n - 1. The graph is represented by a 0-indexed 2D integer array graph where graph[i] is an integer array of nodes adjacent to node i, meaning there is an edge from node i to each node in graph[i].\nA node is a terminal node if there are no outgoing edges. A node is a safe node if every possible path starting from that node leads to a terminal node (or another safe node).\nReturn an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.\n Example 1:\nInput: graph = [[1,2],[2,3],[5],[0],[5],[],[]]\nOutput: [2,4,5,6]\nExplanation: The given graph is shown above.\nNodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\nEvery path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.\nExample 2:\nInput: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\nOutput: [4]\nExplanation:\nOnly node 4 is a terminal node, and every path starting at node 4 leads to node 4.\n Constraints:\nn == graph.length\n1 <= n <= 104\n0 <= graph[i].length <= n\n0 <= graph[i][j] <= n - 1\ngraph[i] is sorted in a strictly increasing order.\nThe graph may contain self-loops.\nThe number of edges in the graph will be in the range [1, 4 * 104]." }, { "post_href": "https://leetcode.com/problems/unique-morse-code-words/discuss/2438206/Python-Elegant-and-Short-or-Two-lines-or-No-loops", "python_solutions": "class Solution:\n\t\"\"\"\n\tTime: O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tMORSE = {\n\t\t'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.',\n\t\t'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.',\n\t\t'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-',\n\t\t'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..',\n\t}\n\n\tdef uniqueMorseRepresentations(self, words: List[str]) -> int:\n\t\treturn len(set(map(self.encode, words)))\n\n\t@classmethod\n\tdef encode(cls, word: str) -> str:\n\t\treturn ''.join(map(cls.MORSE.get, word))", "slug": "unique-morse-code-words", "post_title": "Python Elegant & Short | Two lines | No loops", "user": "Kyrylo-Ktl", "upvotes": 5, "views": 395, "problem_title": "unique morse code words", "number": 804, "acceptance": 0.8270000000000001, "difficulty": "Easy", "__index_level_0__": 13048, "question": "International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows:\n'a' maps to \".-\",\n'b' maps to \"-...\",\n'c' maps to \"-.-.\", and so on.\nFor convenience, the full table for the 26 letters of the English alphabet is given below:\n[\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\nGiven an array of strings words where each word can be written as a concatenation of the Morse code of each letter.\nFor example, \"cab\" can be written as \"-.-..--...\", which is the concatenation of \"-.-.\", \".-\", and \"-...\". We will call such a concatenation the transformation of a word.\nReturn the number of different transformations among all words we have.\n Example 1:\nInput: words = [\"gin\",\"zen\",\"gig\",\"msg\"]\nOutput: 2\nExplanation: The transformation of each word is:\n\"gin\" -> \"--...-.\"\n\"zen\" -> \"--...-.\"\n\"gig\" -> \"--...--.\"\n\"msg\" -> \"--...--.\"\nThere are 2 different transformations: \"--...-.\" and \"--...--.\".\nExample 2:\nInput: words = [\"a\"]\nOutput: 1\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 12\nwords[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/split-array-with-same-average/discuss/120654/Simple-python-with-explanation", "python_solutions": "class Solution(object):\n def splitArraySameAverage(self, A):\n if len(A)==1: return False\n global_avg = sum(A)/float(len(A))\n for lenB in range(1, len(A)/2+1):\n if int(lenB*global_avg) == lenB*global_avg:\n if self.exist(lenB*global_avg, lenB, A):\n return True\n return False\n \n def exist(self, tosum, item_count, arr):\n if item_count==0:\n return False if tosum else True\n if item_count > len(arr) or not arr: \n return False\n if any([self.exist(tosum-arr[0], item_count-1, arr[1:]),\n self.exist(tosum, item_count, arr[1:])]):\n return True\n return False", "slug": "split-array-with-same-average", "post_title": "Simple python with explanation", "user": "licaiuu", "upvotes": 26, "views": 4200, "problem_title": "split array with same average", "number": 805, "acceptance": 0.259, "difficulty": "Hard", "__index_level_0__": 13097, "question": "You are given an integer array nums.\nYou should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).\nReturn true if it is possible to achieve that and false otherwise.\nNote that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.\n Example 1:\nInput: nums = [1,2,3,4,5,6,7,8]\nOutput: true\nExplanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.\nExample 2:\nInput: nums = [3,1]\nOutput: false\n Constraints:\n1 <= nums.length <= 30\n0 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/number-of-lines-to-write-string/discuss/1170893/Python3-97-Faster-Solution", "python_solutions": "class Solution:\n def numberOfLines(self, widths: List[int], s: str) -> List[int]:\n count = ans = wi = 0\n s = list(s)\n while s:\n val = ord(s[0]) - 97\n \n if(widths[val] + wi > 100):\n wi = 0\n count += 1\n \n wi += widths[val]\n \n s.pop(0)\n return([count + 1 , wi])", "slug": "number-of-lines-to-write-string", "post_title": "[Python3] 97% Faster Solution", "user": "VoidCupboard", "upvotes": 2, "views": 80, "problem_title": "number of lines to write string", "number": 806, "acceptance": 0.662, "difficulty": "Easy", "__index_level_0__": 13100, "question": "You are given a string s of lowercase English letters and an array widths denoting how many pixels wide each lowercase English letter is. Specifically, widths[0] is the width of 'a', widths[1] is the width of 'b', and so on.\nYou are trying to write s across several lines, where each line is no longer than 100 pixels. Starting at the beginning of s, write as many letters on the first line such that the total width does not exceed 100 pixels. Then, from where you stopped in s, continue writing as many letters as you can on the second line. Continue this process until you have written all of s.\nReturn an array result of length 2 where:\nresult[0] is the total number of lines.\nresult[1] is the width of the last line in pixels.\n Example 1:\nInput: widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: [3,60]\nExplanation: You can write s as follows:\nabcdefghij // 100 pixels wide\nklmnopqrst // 100 pixels wide\nuvwxyz // 60 pixels wide\nThere are a total of 3 lines, and the last line is 60 pixels wide.\nExample 2:\nInput: widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10], s = \"bbbcccdddaaa\"\nOutput: [2,4]\nExplanation: You can write s as follows:\nbbbcccdddaa // 98 pixels wide\na // 4 pixels wide\nThere are a total of 2 lines, and the last line is 4 pixels wide.\n Constraints:\nwidths.length == 26\n2 <= widths[i] <= 10\n1 <= s.length <= 1000\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/max-increase-to-keep-city-skyline/discuss/445773/Python-3-(two-lines)-(beats-~100)", "python_solutions": "class Solution:\n def maxIncreaseKeepingSkyline(self, G: List[List[int]]) -> int:\n M, N, R, C = len(G), len(G[0]), [max(r) for r in G], [max(c) for c in zip(*G)]\n return sum(min(R[i],C[j]) - G[i][j] for i,j in itertools.product(range(M),range(N)))\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "max-increase-to-keep-city-skyline", "post_title": "Python 3 (two lines) (beats ~100%)", "user": "junaidmansuri", "upvotes": 5, "views": 1200, "problem_title": "max increase to keep city skyline", "number": 807, "acceptance": 0.86, "difficulty": "Medium", "__index_level_0__": 13111, "question": "There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.\nA city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.\nWe are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.\nReturn the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.\n Example 1:\nInput: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\nOutput: 35\nExplanation: The building heights are shown in the center of the above image.\nThe skylines when viewed from each cardinal direction are drawn in red.\nThe grid after increasing the height of buildings without affecting skylines is:\ngridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]\nExample 2:\nInput: grid = [[0,0,0],[0,0,0],[0,0,0]]\nOutput: 0\nExplanation: Increasing the height of any building will result in the skyline changing.\n Constraints:\nn == grid.length\nn == grid[r].length\n2 <= n <= 50\n0 <= grid[r][c] <= 100" }, { "post_href": "https://leetcode.com/problems/soup-servings/discuss/1651208/Python-3-or-Bottom-up-and-Top-down-DP-or-Explanation", "python_solutions": "class Solution:\n def soupServings(self, n: int) -> float:\n @cache # cache the result for input (a, b)\n def dfs(a, b):\n if a <= 0 and b > 0: return 1 # set criteria probability\n elif a <= 0 and b <= 0: return 0.5\n elif a > 0 and b <= 0: return 0\n return (dfs(a-4, b) + dfs(a-3, b-1) + dfs(a-2, b-2) + dfs(a-1, b-3)) * 0.25 # dfs\n if n > 4275: return 1 # observe the distribution you will find `a` tends to be easier to get used up than `b`\n n /= 25 # reduce the input scale\n return dfs(n, n) # both soup have `n` ml", "slug": "soup-servings", "post_title": "Python 3 | Bottom-up & Top-down DP | Explanation", "user": "idontknoooo", "upvotes": 5, "views": 660, "problem_title": "soup servings", "number": 808, "acceptance": 0.433, "difficulty": "Medium", "__index_level_0__": 13134, "question": "There are two types of soup: type A and type B. Initially, we have n ml of each type of soup. There are four kinds of operations:\nServe 100 ml of soup A and 0 ml of soup B,\nServe 75 ml of soup A and 25 ml of soup B,\nServe 50 ml of soup A and 50 ml of soup B, and\nServe 25 ml of soup A and 75 ml of soup B.\nWhen we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability 0.25. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup.\nNote that we do not have an operation where all 100 ml's of soup B are used first.\nReturn the probability that soup A will be empty first, plus half the probability that A and B become empty at the same time. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: n = 50\nOutput: 0.62500\nExplanation: If we choose the first two operations, A will become empty first.\nFor the third operation, A and B will become empty at the same time.\nFor the fourth operation, B will become empty first.\nSo the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.\nExample 2:\nInput: n = 100\nOutput: 0.71875\n Constraints:\n0 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/expressive-words/discuss/1507874/Problem-description-is-horrible...-but-here's-simple-python-solution", "python_solutions": "class Solution:\n def expressiveWords(self, s: str, words: List[str]) -> int:\n \n def summarize(word):\n res = []\n \n n = len(word)\n i, j = 0, 0\n while i<=j and j <= n-1:\n while j <= n-1 and word[j] == word[i]:\n j += 1\n res.append(word[i])\n res.append(j-i)\n i = j\n return res\n \n t = 0 \n start = summarize(s)\n n = len(start)//2\n def compare(w):\n r = summarize(w)\n \n if len(r) != len(start):\n return False \n for i in range(0, 2*n, 2):\n if start[i] != r[i]:\n return False\n elif start[i] == r[i]:\n if start[i+1] < r[i+1]:\n return False\n elif start[i+1] == r[i+1]:\n pass \n elif start[i+1] < 3:\n return False\n return True\n\n for w in words:\n if compare(w):\n t += 1\n return t", "slug": "expressive-words", "post_title": "Problem description is horrible... but here's simple python solution", "user": "byuns9334", "upvotes": 3, "views": 483, "problem_title": "expressive words", "number": 809, "acceptance": 0.4629999999999999, "difficulty": "Medium", "__index_level_0__": 13139, "question": "Sometimes people repeat letters to represent extra feeling. For example:\n\"hello\" -> \"heeellooo\"\n\"hi\" -> \"hiiii\"\nIn these strings like \"heeellooo\", we have groups of adjacent letters that are all the same: \"h\", \"eee\", \"ll\", \"ooo\".\nYou are given a string s and an array of query strings words. A query word is stretchy if it can be made to be equal to s by any number of applications of the following extension operation: choose a group consisting of characters c, and add some number of characters c to the group so that the size of the group is three or more.\nFor example, starting with \"hello\", we could do an extension on the group \"o\" to get \"hellooo\", but we cannot get \"helloo\" since the group \"oo\" has a size less than three. Also, we could do another extension like \"ll\" -> \"lllll\" to get \"helllllooo\". If s = \"helllllooo\", then the query word \"hello\" would be stretchy because of these two extension operations: query = \"hello\" -> \"hellooo\" -> \"helllllooo\" = s.\nReturn the number of query strings that are stretchy.\n Example 1:\nInput: s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]\nOutput: 1\nExplanation: \nWe can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\nWe can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.\nExample 2:\nInput: s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]\nOutput: 3\n Constraints:\n1 <= s.length, words.length <= 100\n1 <= words[i].length <= 100\ns and words[i] consist of lowercase letters." }, { "post_href": "https://leetcode.com/problems/chalkboard-xor-game/discuss/2729320/Simple-python-code-with-explanation", "python_solutions": "class Solution:\n def xorGame(self, nums):\n #create a variable 0 \n x = 0 \n #iterate over the elements in the nums\n for i in nums:\n #do xor of all the elements\n x ^= i \n #Alice wins in two situations :\n #1.if the xor is already 0 (x == 0 )\n #2.if the length of nums is even because if alice got chance with even length and xor != 0 he will select a number so that he will leave the odd number of same integer \n #if nums == [a,a,a,b] then alice erase b so bob must erase from [a,a,a] so he will lose if he erase any number \n return x == 0 or len(nums)%2 == 0 \n #in other situations bob will win", "slug": "chalkboard-xor-game", "post_title": "Simple python code with explanation", "user": "thomanani", "upvotes": 0, "views": 11, "problem_title": "chalkboard xor game", "number": 810, "acceptance": 0.5539999999999999, "difficulty": "Hard", "__index_level_0__": 13150, "question": "You are given an array of integers nums represents the numbers written on a chalkboard.\nAlice 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. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.\nAlso, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.\nReturn true if and only if Alice wins the game, assuming both players play optimally.\n Example 1:\nInput: nums = [1,1,2]\nOutput: false\nExplanation: \nAlice has two choices: erase 1 or erase 2. \nIf 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. \nIf Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.\nExample 2:\nInput: nums = [0,1]\nOutput: true\nExample 3:\nInput: nums = [1,2,3]\nOutput: true\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] < 216" }, { "post_href": "https://leetcode.com/problems/subdomain-visit-count/discuss/914736/Python3-100-faster-100-less-memory-(32ms-14.1mb)", "python_solutions": "class Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n d = defaultdict(int)\n for s in cpdomains:\n cnt, s = s.split()\n cnt = int(cnt)\n d[s] += cnt\n pos = s.find('.') + 1\n while pos > 0:\n d[s[pos:]] += cnt\n pos = s.find('.', pos) + 1\n for x, i in d.items():\n yield f'{i} {x}'", "slug": "subdomain-visit-count", "post_title": "Python3 100% faster, 100% less memory (32ms, 14.1mb)", "user": "haasosaurus", "upvotes": 10, "views": 1300, "problem_title": "subdomain visit count", "number": 811, "acceptance": 0.752, "difficulty": "Medium", "__index_level_0__": 13152, "question": "A website domain \"discuss.leetcode.com\" consists of various subdomains. At the top level, we have \"com\", at the next level, we have \"leetcode.com\" and at the lowest level, \"discuss.leetcode.com\". When we visit a domain like \"discuss.leetcode.com\", we will also visit the parent domains \"leetcode.com\" and \"com\" implicitly.\nA count-paired domain is a domain that has one of the two formats \"rep d1.d2.d3\" or \"rep d1.d2\" where rep is the number of visits to the domain and d1.d2.d3 is the domain itself.\nFor example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.\nGiven an array of count-paired domains cpdomains, return an array of the count-paired domains of each subdomain in the input. You may return the answer in any order.\n Example 1:\nInput: cpdomains = [\"9001 discuss.leetcode.com\"]\nOutput: [\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\nExplanation: We only have one website domain: \"discuss.leetcode.com\".\nAs discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.\nExample 2:\nInput: cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\nOutput: [\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\nExplanation: We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\nFor the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.\n Constraints:\n1 <= cpdomain.length <= 100\n1 <= cpdomain[i].length <= 100\ncpdomain[i] follows either the \"repi d1i.d2i.d3i\" format or the \"repi d1i.d2i\" format.\nrepi is an integer in the range [1, 104].\nd1i, d2i, and d3i consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/largest-triangle-area/discuss/1585033/Python-oror-Faster-than-93-oror-Simple-maths-oror-with-explanation", "python_solutions": "class Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float: \n \n area = 0\n n = len(points)\n for i in range(n):\n x1,y1 = points[i]\n for j in range(i+1,n):\n x2,y2 = points[j]\n for k in range(j+1,n):\n x3,y3 = points[k]\n curr = abs(0.5*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)))\n if curr>area:\n area = curr\n return area", "slug": "largest-triangle-area", "post_title": "Python || Faster than 93% || Simple maths || with explanation", "user": "ana_2kacer", "upvotes": 19, "views": 1300, "problem_title": "largest triangle area", "number": 812, "acceptance": 0.6, "difficulty": "Easy", "__index_level_0__": 13172, "question": "Given an array of points on the X-Y plane points where points[i] = [xi, yi], return the area of the largest triangle that can be formed by any three different points. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\nOutput: 2.00000\nExplanation: The five points are shown in the above figure. The red triangle is the largest.\nExample 2:\nInput: points = [[1,0],[0,0],[0,1]]\nOutput: 0.50000\n Constraints:\n3 <= points.length <= 50\n-50 <= xi, yi <= 50\nAll the given points are unique." }, { "post_href": "https://leetcode.com/problems/largest-sum-of-averages/discuss/1633894/Python-3-Solution-Using-Memoization", "python_solutions": "class Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n \n @lru_cache(maxsize=None)\n def maxAvgSum(index: int, partitions_left: int) -> int:\n if partitions_left == 1:\n return sum(nums[index:]) / (len(nums) - index)\n\n max_sum: float = 0.0\n for i in range(index, len(nums) - (partitions_left - 1)):\n cur_sum: float = sum(nums[index:i + 1])/(i + 1 - index)\n cur_sum += maxAvgSum(i + 1, partitions_left - 1)\n max_sum = max(cur_sum, max_sum)\n return max_sum\n \n return maxAvgSum(0, k)", "slug": "largest-sum-of-averages", "post_title": "Python 3 Solution Using Memoization", "user": "mlalma", "upvotes": 1, "views": 100, "problem_title": "largest sum of averages", "number": 813, "acceptance": 0.529, "difficulty": "Medium", "__index_level_0__": 13178, "question": "You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.\nNote that the partition must use every integer in nums, and that the score is not necessarily an integer.\nReturn the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.\n Example 1:\nInput: nums = [9,1,2,3,9], k = 3\nOutput: 20.00000\nExplanation: \nThe best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\nWe could have also partitioned nums into [9, 1], [2], [3, 9], for example.\nThat partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\nExample 2:\nInput: nums = [1,2,3,4,5,6,7], k = 4\nOutput: 20.50000\n Constraints:\n1 <= nums.length <= 100\n1 <= nums[i] <= 104\n1 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/binary-tree-pruning/discuss/298312/Python-faster-than-98-16-ms", "python_solutions": "class Solution(object):\n def pruneTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root==None:\n return None\n _l = self.pruneTree(root.left)\n _r = self.pruneTree(root.right)\n if root.val == 0 and _l == None and _r == None:\n return None\n else:\n root.left = _l\n root.right = _r\n return root", "slug": "binary-tree-pruning", "post_title": "Python - faster than 98%, 16 ms", "user": "il_buono", "upvotes": 8, "views": 826, "problem_title": "binary tree pruning", "number": 814, "acceptance": 0.726, "difficulty": "Medium", "__index_level_0__": 13183, "question": "Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed.\nA subtree of a node node is node plus every node that is a descendant of node.\n Example 1:\nInput: root = [1,null,0,0,1]\nOutput: [1,null,0,null,1]\nExplanation: \nOnly the red nodes satisfy the property \"every subtree not containing a 1\".\nThe diagram on the right represents the answer.\nExample 2:\nInput: root = [1,0,1,0,0,0,1]\nOutput: [1,null,1,null,1]\nExample 3:\nInput: root = [1,1,0,1,1,0,1,0]\nOutput: [1,1,0,1,1,null,1]\n Constraints:\nThe number of nodes in the tree is in the range [1, 200].\nNode.val is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/bus-routes/discuss/2275016/Python3-BFS-Approach", "python_solutions": "class Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n m = defaultdict(set)\n for i, route in enumerate(routes):\n for node in route:\n m[node].add(i)\n ans = -1\n vis = set()\n queue = deque()\n queue.append(source)\n while queue:\n l = len(queue)\n ans += 1\n for _ in range(l):\n cur = queue.popleft()\n if cur == target:\n return ans\n for bus in m[cur]:\n if bus not in vis:\n vis.add(bus)\n queue.extend(routes[bus])\n return -1", "slug": "bus-routes", "post_title": "[Python3] BFS Approach", "user": "van_fantasy", "upvotes": 1, "views": 127, "problem_title": "bus routes", "number": 815, "acceptance": 0.457, "difficulty": "Hard", "__index_level_0__": 13218, "question": "You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.\nFor 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.\nYou will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.\nReturn the least number of buses you must take to travel from source to target. Return -1 if it is not possible.\n Example 1:\nInput: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\nOutput: 2\nExplanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\nExample 2:\nInput: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\nOutput: -1\n Constraints:\n1 <= routes.length <= 500.\n1 <= routes[i].length <= 105\nAll the values of routes[i] are unique.\nsum(routes[i].length) <= 105\n0 <= routes[i][j] < 106\n0 <= source, target < 106" }, { "post_href": "https://leetcode.com/problems/ambiguous-coordinates/discuss/934654/Python3-valid-numbers", "python_solutions": "class Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n s = s.strip(\"(\").strip(\")\")\n \n def fn(s): \n \"\"\"Return valid numbers from s.\"\"\"\n if len(s) == 1: return [s]\n if s.startswith(\"0\") and s.endswith(\"0\"): return []\n if s.startswith(\"0\"): return [s[:1] + \".\" + s[1:]]\n if s.endswith(\"0\"): return [s]\n return [s[:i] + \".\" + s[i:] for i in range(1, len(s))] + [s]\n \n ans = []\n for i in range(1, len(s)): \n for x in fn(s[:i]):\n for y in fn(s[i:]): \n ans.append(f\"({x}, {y})\")\n return ans", "slug": "ambiguous-coordinates", "post_title": "[Python3] valid numbers", "user": "ye15", "upvotes": 7, "views": 302, "problem_title": "ambiguous coordinates", "number": 816, "acceptance": 0.561, "difficulty": "Medium", "__index_level_0__": 13225, "question": "We had some 2-dimensional coordinates, like \"(1, 3)\" or \"(2, 0.5)\". Then, we removed all commas, decimal points, and spaces and ended up with the string s.\nFor example, \"(1, 3)\" becomes s = \"(13)\" and \"(2, 0.5)\" becomes s = \"(205)\".\nReturn a list of strings representing all possibilities for what our original coordinates could have been.\nOur original representation never had extraneous zeroes, so we never started with numbers like \"00\", \"0.0\", \"0.00\", \"1.0\", \"001\", \"00.01\", or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like \".1\".\nThe final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)\n Example 1:\nInput: s = \"(123)\"\nOutput: [\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]\nExample 2:\nInput: s = \"(0123)\"\nOutput: [\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]\nExplanation: 0.0, 00, 0001 or 00.01 are not allowed.\nExample 3:\nInput: s = \"(00011)\"\nOutput: [\"(0, 0.011)\",\"(0.001, 1)\"]\n Constraints:\n4 <= s.length <= 12\ns[0] == '(' and s[s.length - 1] == ')'.\nThe rest of s are digits." }, { "post_href": "https://leetcode.com/problems/linked-list-components/discuss/933679/Python3-counting-end-of-component", "python_solutions": "class Solution:\n def numComponents(self, head: ListNode, G: List[int]) -> int:\n Gs = set(G)\n ans = 0\n while head: \n if head.val in Gs and (head.next is None or head.next.val not in Gs): ans += 1\n head = head.next \n return ans", "slug": "linked-list-components", "post_title": "[Python3] counting end of component", "user": "ye15", "upvotes": 3, "views": 180, "problem_title": "linked list components", "number": 817, "acceptance": 0.581, "difficulty": "Medium", "__index_level_0__": 13231, "question": "You are given the head of a linked list containing unique integer values and an integer array nums that is a subset of the linked list values.\nReturn the number of connected components in nums where two values are connected if they appear consecutively in the linked list.\n Example 1:\nInput: head = [0,1,2,3], nums = [0,1,3]\nOutput: 2\nExplanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.\nExample 2:\nInput: head = [0,1,2,3,4], nums = [0,3,1,4]\nOutput: 2\nExplanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.\n Constraints:\nThe number of nodes in the linked list is n.\n1 <= n <= 104\n0 <= Node.val < n\nAll the values Node.val are unique.\n1 <= nums.length <= n\n0 <= nums[i] < n\nAll the values of nums are unique." }, { "post_href": "https://leetcode.com/problems/race-car/discuss/1512080/Greedy-Approach-oror-Normal-conditions-oror-94-faster-oror-Well-Coded", "python_solutions": "class Solution:\ndef racecar(self, target: int) -> int:\n \n q = deque()\n q.append((0,0,1))\n while q:\n m,p,s = q.popleft()\n if p==target:\n return m\n rev = -1 if s>0 else 1\n\t\t\n q.append((m+1,p+s,s*2))\n \n if (p+starget and s>0): # If you are back to the target and speed is reverse or if you are ahead of target and speed is positive then reverse the speed\n q.append((m+1,p,rev))\n \n return -1", "slug": "race-car", "post_title": "\ud83d\udccc\ud83d\udccc Greedy Approach || Normal conditions || 94% faster || Well-Coded \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 9, "views": 764, "problem_title": "race car", "number": 818, "acceptance": 0.435, "difficulty": "Hard", "__index_level_0__": 13240, "question": "Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):\nWhen you get an instruction 'A', your car does the following:\nposition += speed\nspeed *= 2\nWhen you get an instruction 'R', your car does the following:\nIf your speed is positive then speed = -1\notherwise speed = 1\nYour position stays the same.\nFor example, after commands \"AAR\", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.\nGiven a target position target, return the length of the shortest sequence of instructions to get there.\n Example 1:\nInput: target = 3\nOutput: 2\nExplanation: \nThe shortest instruction sequence is \"AA\".\nYour position goes from 0 --> 1 --> 3.\nExample 2:\nInput: target = 6\nOutput: 5\nExplanation: \nThe shortest instruction sequence is \"AAARA\".\nYour position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.\n Constraints:\n1 <= target <= 104" }, { "post_href": "https://leetcode.com/problems/most-common-word/discuss/2830994/Python-oror-Long-but-FAST-oror-Memory-beats-82.67!", "python_solutions": "class Solution:\n def getSplit(self, s):\n result = []\n strS = ''\n for i in s.lower():\n if i not in \"!?',;. \": strS += i\n else:\n if len(strS) > 0: result.append(strS)\n strS = ''\n if len(strS) > 0: result.append(strS)\n return result\n\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n paragraph = self.getSplit(paragraph)\n freq = {}\n for s in paragraph:\n if s not in banned:\n if s in freq: freq[s] += 1\n else: freq[s] = 1\n \n m = max(freq.values())\n for k in freq:\n if freq[k] == m: return k", "slug": "most-common-word", "post_title": "Python || Long but FAST || Memory beats 82.67%!", "user": "qiy2019", "upvotes": 1, "views": 27, "problem_title": "most common word", "number": 819, "acceptance": 0.449, "difficulty": "Easy", "__index_level_0__": 13243, "question": "Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.\nThe words in paragraph are case-insensitive and the answer should be returned in lowercase.\n Example 1:\nInput: paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\", banned = [\"hit\"]\nOutput: \"ball\"\nExplanation: \n\"hit\" occurs 3 times, but it is a banned word.\n\"ball\" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. \nNote that words in the paragraph are not case sensitive,\nthat punctuation is ignored (even if adjacent to words, such as \"ball,\"), \nand that \"hit\" isn't the answer even though it occurs more because it is banned.\nExample 2:\nInput: paragraph = \"a.\", banned = []\nOutput: \"a\"\n Constraints:\n1 <= paragraph.length <= 1000\nparagraph consists of English letters, space ' ', or one of the symbols: \"!?',;.\".\n0 <= banned.length <= 100\n1 <= banned[i].length <= 10\nbanned[i] consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/short-encoding-of-words/discuss/2172401/Python-Concise-Brute-Force-and-Trie-Solutions-with-Explanation", "python_solutions": "class Solution:\n def minimumLengthEncoding(self, words: List[str]) -> int:\n words.sort(key=len, reverse=True)\n res = []\n for suffix in words:\n if not any(word.endswith(suffix) for word in res): # check that this word is not actually a suffix\n res.append(suffix)\n return sum(len(word)+1 for word in res) # append hash '#' symbol to each word that is not a suffix", "slug": "short-encoding-of-words", "post_title": "[Python] Concise Brute Force & Trie Solutions with Explanation", "user": "zayne-siew", "upvotes": 23, "views": 1100, "problem_title": "short encoding of words", "number": 820, "acceptance": 0.607, "difficulty": "Medium", "__index_level_0__": 13271, "question": "A valid encoding of an array of words is any reference string s and array of indices indices such that:\nwords.length == indices.length\nThe reference string s ends with the '#' character.\nFor each index indices[i], the substring of s starting from indices[i] and up to (but not including) the next '#' character is equal to words[i].\nGiven an array of words, return the length of the shortest reference string s possible of any valid encoding of words.\n Example 1:\nInput: words = [\"time\", \"me\", \"bell\"]\nOutput: 10\nExplanation: A valid encoding would be s = \"time#bell#\" and indices = [0, 2, 5].\nwords[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\nwords[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\nwords[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"\nExample 2:\nInput: words = [\"t\"]\nOutput: 2\nExplanation: A valid encoding would be s = \"t#\" and indices = [0].\n Constraints:\n1 <= words.length <= 2000\n1 <= words[i].length <= 7\nwords[i] consists of only lowercase letters." }, { "post_href": "https://leetcode.com/problems/shortest-distance-to-a-character/discuss/1226696/Python3Any-improvement", "python_solutions": "class Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n L = []\n for idx, value in enumerate(s):\n if value == c:\n L.append(idx)\n \n distance = []\n i = 0\n for idx, value in enumerate(s):\n if value == c:\n distance.append(0)\n i += 1\n elif idx < L[0]:\n distance.append(L[0] - idx)\n elif idx > L[-1]:\n distance.append(idx - L[-1])\n else:\n distance.append(min((L[i] - idx), (idx - L[i-1]))) \n return distance", "slug": "shortest-distance-to-a-character", "post_title": "\u3010Python3\u3011Any improvement ?", "user": "qiaochow", "upvotes": 5, "views": 293, "problem_title": "shortest distance to a character", "number": 821, "acceptance": 0.7140000000000001, "difficulty": "Easy", "__index_level_0__": 13295, "question": "Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.\nThe distance between two indices i and j is abs(i - j), where abs is the absolute value function.\n Example 1:\nInput: s = \"loveleetcode\", c = \"e\"\nOutput: [3,2,1,0,1,0,0,1,2,2,1,0]\nExplanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\nThe closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\nThe closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\nFor index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.\nThe closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.\nExample 2:\nInput: s = \"aaab\", c = \"b\"\nOutput: [3,2,1,0]\n Constraints:\n1 <= s.length <= 104\ns[i] and c are lowercase English letters.\nIt is guaranteed that c occurs at least once in s." }, { "post_href": "https://leetcode.com/problems/card-flipping-game/discuss/530999/Python3-simple-solution-using-a-for()-loop", "python_solutions": "class Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n \"\"\"\n O(n) time complexity: n is length of fronts\n O(n) space complexity\n \"\"\"\n same = {x for i, x in enumerate(fronts) if x == backs[i]}\n res = 9999\n for i in range(len(fronts)):\n if fronts[i] not in same: res = min(res, fronts[i])\n if backs[i] not in same: res = min(res, backs[i])\n return res % 9999", "slug": "card-flipping-game", "post_title": "Python3 simple solution using a for() loop", "user": "jb07", "upvotes": 2, "views": 254, "problem_title": "card flipping game", "number": 822, "acceptance": 0.456, "difficulty": "Medium", "__index_level_0__": 13330, "question": "You are given two 0-indexed integer arrays fronts and backs of length n, where the ith card has the positive integer fronts[i] printed on the front and backs[i] printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may flip over any number of cards (possibly zero).\nAfter flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.\nReturn the minimum possible good integer after flipping the cards. If there are no good integers, return 0.\n Example 1:\nInput: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]\nOutput: 2\nExplanation:\nIf we flip the second card, the face up numbers are [1,3,4,4,7] and the face down are [1,2,4,1,3].\n2 is the minimum good integer as it appears facing down but not facing up.\nIt can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.\nExample 2:\nInput: fronts = [1], backs = [1]\nOutput: 0\nExplanation:\nThere are no good integers no matter how we flip the cards, so we return 0.\n Constraints:\nn == fronts.length == backs.length\n1 <= n <= 1000\n1 <= fronts[i], backs[i] <= 2000" }, { "post_href": "https://leetcode.com/problems/binary-trees-with-factors/discuss/2402569/Python-oror-Detailed-Explanation-oror-Easily-Understood-oror-DP-oror-O(n-*-sqrt(n))", "python_solutions": "class Solution:\n def numFactoredBinaryTrees(self, arr: List[int]) -> int:\n total_nums = len(arr)\n moduler = 1000000007\n count_product_dict = {num: 1 for num in arr}\n arr.sort()\n\n for i in range(1, total_nums):\n for j in range(i):\n quotient = arr[i] // arr[j]\n if quotient < 2 or math.sqrt(arr[i]) > arr[i- 1]:\n break\n if arr[i] % arr[j] == 0:\n count_product_dict[arr[i]] += count_product_dict[arr[j]] * count_product_dict.get(quotient, 0)\n count_product_dict[arr[i]] %= moduler\n \n return sum(count_product_dict.values()) % moduler", "slug": "binary-trees-with-factors", "post_title": "\ud83d\udd25 Python || Detailed Explanation \u2705 || Easily Understood || DP || O(n * sqrt(n))", "user": "wingskh", "upvotes": 35, "views": 1100, "problem_title": "binary trees with factors", "number": 823, "acceptance": 0.5, "difficulty": "Medium", "__index_level_0__": 13333, "question": "Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.\nWe make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.\nReturn the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.\n Example 1:\nInput: arr = [2,4]\nOutput: 3\nExplanation: We can make these trees: [2], [4], [4, 2, 2]\nExample 2:\nInput: arr = [2,4,5,10]\nOutput: 7\nExplanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].\n Constraints:\n1 <= arr.length <= 1000\n2 <= arr[i] <= 109\nAll the values of arr are unique." }, { "post_href": "https://leetcode.com/problems/goat-latin/discuss/1877272/Python-3-Simple-Solution-w-Explanation", "python_solutions": "class Solution:\n def toGoatLatin(self, sentence: str) -> str:\n new = sentence.split() # Breaks up the input into individual sentences\n count = 1 # Starting at 1 since we only have one \"a\" to begin with.\n \n for x in range(len(new)):\n if new[x][0].casefold() in 'aeiou': # Checks if the first value of x is a vowel. The casefold, can be replaced with lower, lowers the case. Can also just be removed and have \"in 'aeiouAEIOU'\n new[x] = new[x] + 'ma' + 'a'*count # Brings it together with the count multiplying number of \"a\"'s as needed.\n count += 1\n elif new[x].casefold() not in 'aeiou': # Same comment as above.\n new[x] = new[x][1:] + new[x][0] + 'ma' + 'a'*count # Just moves the first value to the end then does the a.\n count += 1\n \n return \" \".join(x for x in new) # Converts the list back into a string.", "slug": "goat-latin", "post_title": "[Python 3] - Simple Solution w Explanation", "user": "IvanTsukei", "upvotes": 4, "views": 110, "problem_title": "goat latin", "number": 824, "acceptance": 0.6779999999999999, "difficulty": "Easy", "__index_level_0__": 13358, "question": "You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.\nWe would like to convert the sentence to \"Goat Latin\" (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows:\nIf a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append \"ma\" to the end of the word.\nFor example, the word \"apple\" becomes \"applema\".\nIf a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\".\nFor example, the word \"goat\" becomes \"oatgma\".\nAdd one letter 'a' to the end of each word per its word index in the sentence, starting with 1.\nFor example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.\nReturn the final sentence representing the conversion from sentence to Goat Latin.\n Example 1:\nInput: sentence = \"I speak Goat Latin\"\nOutput: \"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"\nExample 2:\nInput: sentence = \"The quick brown fox jumped over the lazy dog\"\nOutput: \"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"\n Constraints:\n1 <= sentence.length <= 150\nsentence consists of English letters and spaces.\nsentence has no leading or trailing spaces.\nAll the words in sentence are separated by a single space." }, { "post_href": "https://leetcode.com/problems/friends-of-appropriate-ages/discuss/2074946/Python-3-or-Three-Methods-(Binary-Search-CounterHashmap-Math)-or-Explanation", "python_solutions": "class Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n ages.sort() # sort the `ages`\n ans = 0\n n = len(ages)\n for idx, age in enumerate(ages): # for each age\n lb = age # lower bound\n ub = (age - 7) * 2 # upper bound\n i = bisect.bisect_left(ages, lb) # binary search lower bound\n j = bisect.bisect_left(ages, ub) # binary search upper bound\n if j - i <= 0: continue\n ans += j - i # count number of potential friends\n if lb <= age < ub: # ignore itself\n ans -= 1\n return ans", "slug": "friends-of-appropriate-ages", "post_title": "Python 3 | Three Methods (Binary Search, Counter/Hashmap, Math) | Explanation", "user": "idontknoooo", "upvotes": 5, "views": 416, "problem_title": "friends of appropriate ages", "number": 825, "acceptance": 0.4639999999999999, "difficulty": "Medium", "__index_level_0__": 13401, "question": "There are n persons on a social media website. You are given an integer array ages where ages[i] is the age of the ith person.\nA Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:\nage[y] <= 0.5 * age[x] + 7\nage[y] > age[x]\nage[y] > 100 && age[x] < 100\nOtherwise, x will send a friend request to y.\nNote that if x sends a request to y, y will not necessarily send a request to x. Also, a person will not send a friend request to themself.\nReturn the total number of friend requests made.\n Example 1:\nInput: ages = [16,16]\nOutput: 2\nExplanation: 2 people friend request each other.\nExample 2:\nInput: ages = [16,17,18]\nOutput: 2\nExplanation: Friend requests are made 17 -> 16, 18 -> 17.\nExample 3:\nInput: ages = [20,30,100,110,120]\nOutput: 3\nExplanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.\n Constraints:\nn == ages.length\n1 <= n <= 2 * 104\n1 <= ages[i] <= 120" }, { "post_href": "https://leetcode.com/problems/most-profit-assigning-work/discuss/2603913/Python3-or-Solved-Using-Binary-Search-W-Sorting-O((n%2Bm)*logn)-Runtime-Solution!", "python_solutions": "class Solution:\n #Time-Complexity: O(n + nlogn + n + mlog(n)) -> O((n+m) *logn)\n #Space-Complexity: O(n)\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n #Approach: First of all, linearly traverse each and every corresponding index\n #position of first two input arrays: difficulty and profit to group each\n #item by 1-d array and put it in separate 2-d array. Then, sort the 2-d array\n #by increasing difficulty of the job! Then, for each worker, perform binary\n #search and consistently update the max profit the current worker can work and\n #earn! Add this value to answer variable, which is cumulative for all workers!\n #this will be the result returned at the end!\n arr = []\n for i in range(len(difficulty)):\n arr.append([difficulty[i], profit[i]])\n #sort by difficulty!\n arr.sort(key = lambda x: x[0])\n #then, I need to update the maximum profit up to each and every item!\n maximum = float(-inf)\n for j in range(len(arr)):\n maximum = max(maximum, arr[j][1])\n arr[j][1] = maximum\n ans = 0\n #iterate through each and every worker!\n for w in worker:\n bestProfit = 0\n #define search space to perform binary search!\n L, R = 0, len(arr) - 1\n #as long as search space has at least one element to consider or one job,\n #continue iterations of binary search!\n while L <= R:\n mid = (L + R) // 2\n mid_e = arr[mid]\n #check if current job has difficulty that is manageable!\n if(mid_e[0] <= w):\n bestProfit = max(bestProfit, mid_e[1])\n #we still need to search right and try higher difficulty\n #jobs that might yield higher profit!\n L = mid + 1\n continue\n else:\n R = mid - 1\n continue\n #once we break from while loop and end binary search, we should have\n #found bestProfit for current worker performing task that is manageable!\n ans += bestProfit\n return ans", "slug": "most-profit-assigning-work", "post_title": "Python3 | Solved Using Binary Search W/ Sorting O((n+m)*logn) Runtime Solution!", "user": "JOON1234", "upvotes": 2, "views": 134, "problem_title": "most profit assigning work", "number": 826, "acceptance": 0.446, "difficulty": "Medium", "__index_level_0__": 13412, "question": "You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:\ndifficulty[i] and profit[i] are the difficulty and the profit of the ith job, and\nworker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).\nEvery worker can be assigned at most one job, but one job can be completed multiple times.\nFor example, if three workers attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, their profit is $0.\nReturn the maximum profit we can achieve after assigning the workers to the jobs.\n Example 1:\nInput: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\nOutput: 100\nExplanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.\nExample 2:\nInput: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\nOutput: 0\n Constraints:\nn == difficulty.length\nn == profit.length\nm == worker.length\n1 <= n, m <= 104\n1 <= difficulty[i], profit[i], worker[i] <= 105" }, { "post_href": "https://leetcode.com/problems/making-a-large-island/discuss/1340782/Python-Clean-DFS", "python_solutions": "class Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n N = len(grid)\n DIRECTIONS = [(-1, 0), (0, -1), (0, 1), (1, 0)]\n \n\t\taddress = {}\n def dfs(row, column, island_id):\n queue = deque([(row, column, island_id)])\n visited.add((row, column))\n area = 1\n while queue: \n row, column, island_id = queue.pop()\n address[(row, column)] = island_id\n for direction in DIRECTIONS:\n r, c = row + direction[0], column + direction[1]\n if r in range(N) and c in range(N) and grid[r][c] == 1 and (r, c) not in visited:\n queue.append((r, c, island_id))\n visited.add((r, c))\n area += 1\n return area\n \n visited = set()\n area = {}\n island_id = 0\n for row in range(N):\n for column in range(N):\n if grid[row][column] == 1 and (row, column) not in visited:\n area[island_id] = dfs(row, column, island_id)\n island_id += 1\n \n if len(address.keys()) == N**2: return N**2 \n \n largest_area = 1\n for row in range(N):\n for column in range(N):\n if grid[row][column] == 1: continue\n neighbours = set()\n large_area = 1\n for direction in DIRECTIONS:\n r, c = row + direction[0], column + direction[1]\n if r in range(N) and c in range(N) and grid[r][c] == 1 and address[(r, c)] not in neighbours:\n neighbours.add(address[(r, c)])\n large_area += area[address[(r, c)]]\n largest_area = max(largest_area, large_area)\n \n return largest_area", "slug": "making-a-large-island", "post_title": "[Python] Clean DFS", "user": "soma28", "upvotes": 4, "views": 1000, "problem_title": "making a large island", "number": 827, "acceptance": 0.447, "difficulty": "Hard", "__index_level_0__": 13422, "question": "You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.\nReturn the size of the largest island in grid after applying this operation.\nAn island is a 4-directionally connected group of 1s.\n Example 1:\nInput: grid = [[1,0],[0,1]]\nOutput: 3\nExplanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\nExample 2:\nInput: grid = [[1,1],[1,0]]\nOutput: 4\nExplanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\nExample 3:\nInput: grid = [[1,1],[1,1]]\nOutput: 4\nExplanation: Can't change any 0 to 1, only one island with area = 4.\n Constraints:\nn == grid.length\nn == grid[i].length\n1 <= n <= 500\ngrid[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/count-unique-characters-of-all-substrings-of-a-given-string/discuss/2140546/Python-O(n)-with-intuition-step-by-step-thought-process", "python_solutions": "class Solution:\n def uniqueLetterString(self, s: str) -> int:\n r=0\n for i in range(len(s)):\n for j in range(i, len(s)):\n ss=s[i:j+1]\n unique=sum([ 1 for (i,v) in Counter(ss).items() if v == 1 ])\n r+=unique\n return r", "slug": "count-unique-characters-of-all-substrings-of-a-given-string", "post_title": "Python O(n) with intuition / step-by-step thought process", "user": "alskdjfhg123", "upvotes": 6, "views": 354, "problem_title": "count unique characters of all substrings of a given string", "number": 828, "acceptance": 0.517, "difficulty": "Hard", "__index_level_0__": 13442, "question": "Let's define a function countUniqueChars(s) that returns the number of unique characters in s.\nFor example, calling countUniqueChars(s) if s = \"LEETCODE\" then \"L\", \"T\", \"C\", \"O\", \"D\" are the unique characters since they appear only once in s, therefore countUniqueChars(s) = 5.\nGiven a string s, return the sum of countUniqueChars(t) where t is a substring of s. The test cases are generated such that the answer fits in a 32-bit integer.\nNotice that some substrings can be repeated so in this case you have to count the repeated ones too.\n Example 1:\nInput: s = \"ABC\"\nOutput: 10\nExplanation: All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\nEvery substring is composed with only unique letters.\nSum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\nExample 2:\nInput: s = \"ABA\"\nOutput: 8\nExplanation: The same as example 1, except countUniqueChars(\"ABA\") = 1.\nExample 3:\nInput: s = \"LEETCODE\"\nOutput: 92\n Constraints:\n1 <= s.length <= 105\ns consists of uppercase English letters only." }, { "post_href": "https://leetcode.com/problems/consecutive-numbers-sum/discuss/1466133/8-lines-Python3-code", "python_solutions": "class Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n csum=0\n result=0\n for i in range(1,n+1):\n csum+=i-1\n if csum>=n:\n break\n if (n-csum)%i==0:\n result+=1\n return result", "slug": "consecutive-numbers-sum", "post_title": "8 lines Python3 code", "user": "tongho", "upvotes": 6, "views": 705, "problem_title": "consecutive numbers sum", "number": 829, "acceptance": 0.415, "difficulty": "Hard", "__index_level_0__": 13456, "question": "Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.\n Example 1:\nInput: n = 5\nOutput: 2\nExplanation: 5 = 2 + 3\nExample 2:\nInput: n = 9\nOutput: 3\nExplanation: 9 = 4 + 5 = 2 + 3 + 4\nExample 3:\nInput: n = 15\nOutput: 4\nExplanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n Constraints:\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/positions-of-large-groups/discuss/1831860/Python-simple-and-elegant-multiple-solutions-%22Streak%22", "python_solutions": "class Solution(object):\n def largeGroupPositions(self, s):\n s += \" \"\n \n streak, char, out = 0, s[0], []\n \n for i,c in enumerate(s):\n if c != char:\n if streak >= 3:\n out.append([i-streak, i-1])\n \n streak, char = 0, s[i]\n \n streak += 1\n \n return out", "slug": "positions-of-large-groups", "post_title": "Python - simple and elegant - multiple solutions - \"Streak\"", "user": "domthedeveloper", "upvotes": 1, "views": 83, "problem_title": "positions of large groups", "number": 830, "acceptance": 0.518, "difficulty": "Easy", "__index_level_0__": 13465, "question": "In a string s of lowercase letters, these letters form consecutive groups of the same character.\nFor example, a string like s = \"abbxxxxzyy\" has the groups \"a\", \"bb\", \"xxxx\", \"z\", and \"yy\".\nA group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, \"xxxx\" has the interval [3,6].\nA group is considered large if it has 3 or more characters.\nReturn the intervals of every large group sorted in increasing order by start index.\n Example 1:\nInput: s = \"abbxxxxzzy\"\nOutput: [[3,6]]\nExplanation: \"xxxx\" is the only large group with start index 3 and end index 6.\nExample 2:\nInput: s = \"abc\"\nOutput: []\nExplanation: We have groups \"a\", \"b\", and \"c\", none of which are large groups.\nExample 3:\nInput: s = \"abcdddeeeeaabbbcd\"\nOutput: [[3,5],[6,9],[12,14]]\nExplanation: The large groups are \"ddd\", \"eeee\", and \"bbb\".\n Constraints:\n1 <= s.length <= 1000\ns contains lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/masking-personal-information/discuss/1868652/3-Lines-Python-Solution-oror-98-Faster-oror-Memory-less-than-87", "python_solutions": "class Solution:\n def maskPII(self, s: str) -> str:\n if '@' in s: return f'{s[0].lower()}*****{s[s.index(\"@\")-1].lower()+\"\".join([x.lower() for x in s[s.index(\"@\"):]])}'\n s=''.join([x for x in s if x not in '()- +'])\n return ('' if len(s)<=10 else '+'+'*'*(len(s)-10)+'-')+f'***-***-{s[-4:]}'", "slug": "masking-personal-information", "post_title": "3-Lines Python Solution || 98% Faster || Memory less than 87%", "user": "Taha-C", "upvotes": 1, "views": 94, "problem_title": "masking personal information", "number": 831, "acceptance": 0.47, "difficulty": "Medium", "__index_level_0__": 13484, "question": "You are given a personal information string s, representing either an email address or a phone number. Return the masked personal information using the below rules.\nEmail address:\nAn email address is:\nA name consisting of uppercase and lowercase English letters, followed by\nThe '@' symbol, followed by\nThe domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character).\nTo mask an email:\nThe uppercase letters in the name and domain must be converted to lowercase letters.\nThe middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks \"*****\".\nPhone number:\nA phone number is formatted as follows:\nThe phone number contains 10-13 digits.\nThe last 10 digits make up the local number.\nThe remaining 0-3 digits, in the beginning, make up the country code.\nSeparation characters from the set {'+', '-', '(', ')', ' '} separate the above digits in some way.\nTo mask a phone number:\nRemove all separation characters.\nThe masked phone number should have the form:\n\"***-***-XXXX\" if the country code has 0 digits.\n\"+*-***-***-XXXX\" if the country code has 1 digit.\n\"+**-***-***-XXXX\" if the country code has 2 digits.\n\"+***-***-***-XXXX\" if the country code has 3 digits.\n\"XXXX\" is the last 4 digits of the local number.\n Example 1:\nInput: s = \"LeetCode@LeetCode.com\"\nOutput: \"l*****e@leetcode.com\"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nExample 2:\nInput: s = \"AB@qq.com\"\nOutput: \"a*****b@qq.com\"\nExplanation: s is an email address.\nThe name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\nNote that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.\nExample 3:\nInput: s = \"1(234)567-890\"\nOutput: \"***-***-7890\"\nExplanation: s is a phone number.\nThere are 10 digits, so the local number is 10 digits and the country code is 0 digits.\nThus, the resulting masked number is \"***-***-7890\".\n Constraints:\ns is either a valid email or a phone number.\nIf s is an email:\n8 <= s.length <= 40\ns consists of uppercase and lowercase English letters and exactly one '@' symbol and '.' symbol.\nIf s is a phone number:\n10 <= s.length <= 20\ns consists of digits, spaces, and the symbols '(', ')', '-', and '+'." }, { "post_href": "https://leetcode.com/problems/flipping-an-image/discuss/1363051/PYTHON-VERY-VERY-EASY-SOLN.-3-solutions-explained-O(n).-With-or-without-inbuilt-functions.", "python_solutions": "class Solution:\n def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Simple & striaghtforward without using inbuilt functions.\n \n In actual the run time is very less as we are iterating only n/2 time\n for each image list.\n Time complexity : O(n * n/2) == O(n^2) \n Space complexity : O(1)\n \"\"\"\n \n for im in image: #Iterate through each im list in the image list.\n i, j = 0, len(im)-1 #Maintain two pointers one at start and one at end.\n while i <= j: #Iterate while first pointer is less than or equal to second pointer.\n im[i], im[j] = im[j]^1, im[i]^1 #swap element at both pointer & complement them at the same time.\n i +=1 #increment first pointer to move forward\n j -=1 #decrement second pointer to move backward\n \n return image # return same list\n \n \n \"\"\"\n Using inbuilt functions\n \"\"\"\n # for im in range(len(image)):\n # image[im] = list(map(lambda a : abs(a-1), reversed(image[im])))\n # return image\n \n \"\"\"\n One liner\n \"\"\"\n return [[i^1 for i in im[::-1]] for im in image]", "slug": "flipping-an-image", "post_title": "[PYTHON] VERY VERY EASY SOLN. 3 solutions explained O(n). With or without inbuilt functions.", "user": "er1shivam", "upvotes": 10, "views": 663, "problem_title": "flipping an image", "number": 832, "acceptance": 0.805, "difficulty": "Easy", "__index_level_0__": 13489, "question": "Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.\nTo flip an image horizontally means that each row of the image is reversed.\nFor example, flipping [1,1,0] horizontally results in [0,1,1].\nTo invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.\nFor example, inverting [0,1,1] results in [1,0,0].\n Example 1:\nInput: image = [[1,1,0],[1,0,1],[0,0,0]]\nOutput: [[1,0,0],[0,1,0],[1,1,1]]\nExplanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\nThen, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\nExample 2:\nInput: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\nOutput: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\nExplanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\nThen invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n Constraints:\nn == image.length\nn == image[i].length\n1 <= n <= 20\nimages[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/find-and-replace-in-string/discuss/1920198/Python-3-or-simple-or-3-lines-of-code-w-explanation", "python_solutions": "class Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n # iterate from the greater index to the smallest\n for i, src, tg in sorted(list(zip(indices, sources, targets)), reverse=True): \n # if found the pattern matches with the source, replace with the target accordingly\n if s[i:i+len(src)] == src: s = s[:i] + tg + s[i+len(src):] \n return s", "slug": "find-and-replace-in-string", "post_title": "Python 3 | simple | 3 lines of code w/ explanation", "user": "Ploypaphat", "upvotes": 3, "views": 327, "problem_title": "find and replace in string", "number": 833, "acceptance": 0.541, "difficulty": "Medium", "__index_level_0__": 13539, "question": "You are given a 0-indexed string s that you must perform k replacement operations on. The replacement operations are given as three 0-indexed parallel arrays, indices, sources, and targets, all of length k.\nTo complete the ith replacement operation:\nCheck if the substring sources[i] occurs at index indices[i] in the original string s.\nIf it does not occur, do nothing.\nOtherwise if it does occur, replace that substring with targets[i].\nFor example, if s = \"abcd\", indices[i] = 0, sources[i] = \"ab\", and targets[i] = \"eee\", then the result of this replacement will be \"eeecd\".\nAll replacement operations must occur simultaneously, meaning the replacement operations should not affect the indexing of each other. The testcases will be generated such that the replacements will not overlap.\nFor example, a testcase with s = \"abc\", indices = [0, 1], and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap.\nReturn the resulting string after performing all replacement operations on s.\nA substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\nOutput: \"eeebffff\"\nExplanation:\n\"a\" occurs at index 0 in s, so we replace it with \"eee\".\n\"cd\" occurs at index 2 in s, so we replace it with \"ffff\".\nExample 2:\nInput: s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\nOutput: \"eeecd\"\nExplanation:\n\"ab\" occurs at index 0 in s, so we replace it with \"eee\".\n\"ec\" does not occur at index 2 in s, so we do nothing.\n Constraints:\n1 <= s.length <= 1000\nk == indices.length == sources.length == targets.length\n1 <= k <= 100\n0 <= indexes[i] < s.length\n1 <= sources[i].length, targets[i].length <= 50\ns consists of only lowercase English letters.\nsources[i] and targets[i] consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/sum-of-distances-in-tree/discuss/1311639/Python3-post-order-and-pre-order-dfs", "python_solutions": "class Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n graph = {}\n for u, v in edges: \n graph.setdefault(u, []).append(v)\n graph.setdefault(v, []).append(u)\n \n size = [0]*n\n \n def fn(x, par): \n \"\"\"Return size and sum of distances in sub-tree.\"\"\"\n c = s = 0\n for xx in graph.get(x, []): \n if xx != par: \n cc, ss = fn(xx, x)\n c, s = c + cc, s + ss + cc\n size[x] = c + 1\n return c + 1, s\n \n ans = [0]*n\n ans[0] = fn(0, -1)[1]\n \n stack = [0]\n while stack: \n x = stack.pop()\n for xx in graph.get(x, []): \n if not ans[xx]: \n ans[xx] = ans[x] + n - 2*size[xx]\n stack.append(xx)\n return ans", "slug": "sum-of-distances-in-tree", "post_title": "[Python3] post-order & pre-order dfs", "user": "ye15", "upvotes": 2, "views": 195, "problem_title": "sum of distances in tree", "number": 834, "acceptance": 0.542, "difficulty": "Hard", "__index_level_0__": 13550, "question": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\nYou are given the integer n and the array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\nReturn an array answer of length n where answer[i] is the sum of the distances between the ith node in the tree and all other nodes.\n Example 1:\nInput: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\nOutput: [8,12,6,10,10,10]\nExplanation: The tree is shown above.\nWe can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\nequals 1 + 1 + 2 + 2 + 2 = 8.\nHence, answer[0] = 8, and so on.\nExample 2:\nInput: n = 1, edges = []\nOutput: [0]\nExample 3:\nInput: n = 2, edges = [[1,0]]\nOutput: [1,1]\n Constraints:\n1 <= n <= 3 * 104\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nThe given input represents a valid tree." }, { "post_href": "https://leetcode.com/problems/image-overlap/discuss/2748733/Python-(Faster-than-82)-or-Brute-force-(Recursive)-and-optimized-using-HashMap", "python_solutions": "class Solution:\n def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:\n n = len(img1)\n bestOverlap = 0\n\n def helper(dr, dc):\n overlap = 0\n for r in range(n):\n for c in range(n):\n nr, nc = r + dr, c + dc\n if nr in range(n) and nc in range(n) and img1[nr][nc] == 1 and img2[r][c] == 1:\n overlap += 1\n\n return overlap\n\n for r in range(-n, n):\n for c in range(-n, n):\n bestOverlap = max(helper(r, c), bestOverlap)\n\n return bestOverlap", "slug": "image-overlap", "post_title": "Python (Faster than 82%) | Brute force (Recursive) and optimized using HashMap", "user": "KevinJM17", "upvotes": 1, "views": 18, "problem_title": "image overlap", "number": 835, "acceptance": 0.64, "difficulty": "Medium", "__index_level_0__": 13556, "question": "You are given two images, img1 and img2, represented as binary, square matrices of size n x n. A binary matrix has only 0s and 1s as values.\nWe translate one image however we choose by sliding all the 1 bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the overlap by counting the number of positions that have a 1 in both images.\nNote also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.\nReturn the largest possible overlap.\n Example 1:\nInput: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]\nOutput: 3\nExplanation: We translate img1 to right by 1 unit and down by 1 unit.\nThe number of positions that have a 1 in both images is 3 (shown in red).\nExample 2:\nInput: img1 = [[1]], img2 = [[1]]\nOutput: 1\nExample 3:\nInput: img1 = [[0]], img2 = [[0]]\nOutput: 0\n Constraints:\nn == img1.length == img1[i].length\nn == img2.length == img2[i].length\n1 <= n <= 30\nimg1[i][j] is either 0 or 1.\nimg2[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/rectangle-overlap/discuss/342095/Solution-in-Python-3-(beats-100)-(-2-lines-)", "python_solutions": "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n [A,B,C,D], [E,F,G,H] = rec1, rec2\n return F float:\n \n @lru_cache(None)\n def fn(n): \n \"\"\"Return prob of of points between K and N given current point n.\"\"\"\n if N < n: return 0\n if K <= n: return 1\n if n+1 < K: return (1+W)/W*fn(n+1) - 1/W*fn(n+W+1)\n return 1/W*sum(fn(n+i) for i in range(1, W+1))\n \n return fn(0)", "slug": "new-21-game", "post_title": "[Python3] top-down & bottom-up dp", "user": "ye15", "upvotes": 4, "views": 558, "problem_title": "new 21 game", "number": 837, "acceptance": 0.361, "difficulty": "Medium", "__index_level_0__": 13589, "question": "Alice plays the following game, loosely based on the card game \"21\".\nAlice starts with 0 points and draws numbers while she has less than k points. During each draw, she gains an integer number of points randomly from the range [1, maxPts], where maxPts is an integer. Each draw is independent and the outcomes have equal probabilities.\nAlice stops drawing numbers when she gets k or more points.\nReturn the probability that Alice has n or fewer points.\nAnswers within 10-5 of the actual answer are considered accepted.\n Example 1:\nInput: n = 10, k = 1, maxPts = 10\nOutput: 1.00000\nExplanation: Alice gets a single card, then stops.\nExample 2:\nInput: n = 6, k = 1, maxPts = 10\nOutput: 0.60000\nExplanation: Alice gets a single card, then stops.\nIn 6 out of 10 possibilities, she is at or below 6 points.\nExample 3:\nInput: n = 21, k = 17, maxPts = 10\nOutput: 0.73278\n Constraints:\n0 <= k <= n <= 104\n1 <= maxPts <= 104" }, { "post_href": "https://leetcode.com/problems/push-dominoes/discuss/2629832/Easy-Python-O(n)-solution", "python_solutions": "class Solution:\n def pushDominoes(self, dominoes: str) -> str:\n dominoes = 'L' + dominoes + 'R'\n res = []\n left = 0\n \n for right in range(1, len(dominoes)):\n if dominoes[right] == '.': \n continue\n \n middle = right - left - 1\n if left: \n res.append(dominoes[left])\n if dominoes[left] == dominoes[right]: \n res.append(dominoes[left] * middle)\n elif dominoes[left] == 'L' and dominoes[right] == 'R':\n res.append('.' * middle)\n else: \n res.append('R' * (middle // 2) + '.' * (middle % 2) + 'L' * (middle // 2))\n left = right\n \n return ''.join(res)", "slug": "push-dominoes", "post_title": "Easy Python O(n) solution", "user": "namanxk", "upvotes": 3, "views": 225, "problem_title": "push dominoes", "number": 838, "acceptance": 0.57, "difficulty": "Medium", "__index_level_0__": 13594, "question": "There are n dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right.\nAfter each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right.\nWhen a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.\nFor the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.\nYou are given a string dominoes representing the initial state where:\ndominoes[i] = 'L', if the ith domino has been pushed to the left,\ndominoes[i] = 'R', if the ith domino has been pushed to the right, and\ndominoes[i] = '.', if the ith domino has not been pushed.\nReturn a string representing the final state.\n Example 1:\nInput: dominoes = \"RR.L\"\nOutput: \"RR.L\"\nExplanation: The first domino expends no additional force on the second domino.\nExample 2:\nInput: dominoes = \".L.R...LR..L..\"\nOutput: \"LL.RR.LLRRLL..\"\n Constraints:\nn == dominoes.length\n1 <= n <= 105\ndominoes[i] is either 'L', 'R', or '.'." }, { "post_href": "https://leetcode.com/problems/similar-string-groups/discuss/2698654/My-Python-Union-Find-Solution", "python_solutions": "class Solution:\n def numSimilarGroups(self, strs: List[str]) -> int:\n N = len(strs)\n parent = [i for i in range(N)]\n depth = [1 for _ in range(N)]\n\n def find(idx):\n if idx != parent[idx]:\n return find(parent[idx])\n return idx\n \n def union(idx1, idx2):\n p1 = find(idx1)\n p2 = find(idx2)\n if p1 == p2: return\n if depth[p1] < depth[p2]:\n parent[p1] = p2\n elif depth[p2] < depth[p1]:\n parent[p2] = p1\n else:\n parent[p2] = p1\n depth[p1] += 1\n\n def similar(w1, w2):\n dif_idx = -1\n for idx in range(len(w1)):\n if w1[idx] != w2[idx]:\n if dif_idx < 0:\n dif_idx = idx\n else:\n if w1[dif_idx] != w2[idx]: return False\n if w2[dif_idx] != w1[idx]: return False\n if w1[idx+1:] != w2[idx+1:]: return False\n return True\n return True\n \n for idx in range(1, N):\n for pid in range(0, idx):\n if similar(strs[pid], strs[idx]):\n union(pid, idx)\n\n return len([i for i, p in enumerate(parent) if i==p])", "slug": "similar-string-groups", "post_title": "My Python Union Find Solution", "user": "MonQiQi", "upvotes": 1, "views": 99, "problem_title": "similar string groups", "number": 839, "acceptance": 0.478, "difficulty": "Hard", "__index_level_0__": 13626, "question": "Two strings, X and Y, are considered similar if either they are identical or we can make them equivalent by swapping at most two letters (in distinct positions) within the string X.\nFor example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\", \"rats\", or \"arts\".\nTogether, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"}. Notice that \"tars\" and \"arts\" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.\nWe are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?\n Example 1:\nInput: strs = [\"tars\",\"rats\",\"arts\",\"star\"]\nOutput: 2\nExample 2:\nInput: strs = [\"omv\",\"ovm\"]\nOutput: 1\n Constraints:\n1 <= strs.length <= 300\n1 <= strs[i].length <= 300\nstrs[i] consists of lowercase letters only.\nAll words in strs have the same length and are anagrams of each other." }, { "post_href": "https://leetcode.com/problems/magic-squares-in-grid/discuss/381223/Two-Solutions-in-Python-3-(beats-~99)-(two-lines)", "python_solutions": "class Solution:\n def numMagicSquaresInside(self, G: List[List[int]]) -> int:\n \tM, N, S, t = len(G)-2, len(G[0])-2, {(8,1,6,3,5,7,4,9,2),(6,1,8,7,5,3,2,9,4),(2,7,6,9,5,1,4,3,8),(6,7,2,1,5,9,8,3,4)}, range(3)\n \treturn sum((lambda x: x in S or x[::-1] in S)(tuple(sum([G[i+k][j:j+3] for k in t],[]))) for i,j in itertools.product(range(M),range(N)))", "slug": "magic-squares-in-grid", "post_title": "Two Solutions in Python 3 (beats ~99%) (two lines)", "user": "junaidmansuri", "upvotes": 1, "views": 624, "problem_title": "magic squares in grid", "number": 840, "acceptance": 0.385, "difficulty": "Medium", "__index_level_0__": 13631, "question": "A 3 x 3 magic square is a 3 x 3 grid filled with distinct numbers from 1 to 9 such that each row, column, and both diagonals all have the same sum.\nGiven a row x col grid of integers, how many 3 x 3 \"magic square\" subgrids are there? (Each subgrid is contiguous).\n Example 1:\nInput: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\nOutput: 1\nExplanation: \nThe following subgrid is a 3 x 3 magic square:\nwhile this one is not:\nIn total, there is only one magic square inside the given grid.\nExample 2:\nInput: grid = [[8]]\nOutput: 0\n Constraints:\nrow == grid.length\ncol == grid[i].length\n1 <= row, col <= 10\n0 <= grid[i][j] <= 15" }, { "post_href": "https://leetcode.com/problems/keys-and-rooms/discuss/1116836/Python3-Soln-greater-Keys-and-Rooms-stack-implementation", "python_solutions": "class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n visited_rooms = set()\n stack = [0] # for rooms that we need to visit and we start from room [0]\n \n while stack: \n room = stack.pop() \n visited_rooms.add(room)\n for key in rooms[room]:\n if key not in visited_rooms:\n stack.append(key)\n return len(visited_rooms) == len(rooms)", "slug": "keys-and-rooms", "post_title": "[Python3] Soln -> Keys and Rooms [stack implementation]", "user": "avEraGeC0der", "upvotes": 12, "views": 620, "problem_title": "keys and rooms", "number": 841, "acceptance": 0.7020000000000001, "difficulty": "Medium", "__index_level_0__": 13635, "question": "There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.\nWhen you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.\nGiven an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.\n Example 1:\nInput: rooms = [[1],[2],[3],[]]\nOutput: true\nExplanation: \nWe visit room 0 and pick up key 1.\nWe then visit room 1 and pick up key 2.\nWe then visit room 2 and pick up key 3.\nWe then visit room 3.\nSince we were able to visit every room, we return true.\nExample 2:\nInput: rooms = [[1,3],[3,0,1],[2],[0]]\nOutput: false\nExplanation: We can not enter room number 2 since the only key that unlocks it is in that room.\n Constraints:\nn == rooms.length\n2 <= n <= 1000\n0 <= rooms[i].length <= 1000\n1 <= sum(rooms[i].length) <= 3000\n0 <= rooms[i][j] < n\nAll the values of rooms[i] are unique." }, { "post_href": "https://leetcode.com/problems/split-array-into-fibonacci-sequence/discuss/1579510/PYTHON-BACKTRACKING-or-THREE-PROBLEMS-ONE-SOLUTION", "python_solutions": "class Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n def dfs(i):\n if i>=len(num):\n return len(ans)>2 \n n = 0\n for j in range(i, len(num)):\n n = n*10 + int(num[j]) \n if n>2**31: # if number exceeds the range mentioned\n return False\n # if len < 2 we know more elements need to be appended\n # as size>=3 if size is already greater we check for fibonacci\n # as last + secondLast == curr\n if len(ans)<2 or (ans[-1]+ans[-2]==n):\n ans.append(n)\n if dfs(j+1):\n return True\n ans.pop()\n if i==j and num[j]=='0': # if trailing 0 is present\n return False\n \n if len(num)<=2: return []\n ans = []\n if dfs(0): return ans\n return []", "slug": "split-array-into-fibonacci-sequence", "post_title": "PYTHON BACKTRACKING | THREE PROBLEMS ONE SOLUTION", "user": "hX_", "upvotes": 1, "views": 150, "problem_title": "split array into fibonacci sequence", "number": 842, "acceptance": 0.3829999999999999, "difficulty": "Medium", "__index_level_0__": 13680, "question": "You are given a string of digits num, such as \"123456579\". We can split it into a Fibonacci-like sequence [123, 456, 579].\nFormally, a Fibonacci-like sequence is a list f of non-negative integers such that:\n0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),\nf.length >= 3, and\nf[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.\nNote that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.\nReturn any Fibonacci-like sequence split from num, or return [] if it cannot be done.\n Example 1:\nInput: num = \"1101111\"\nOutput: [11,0,11,11]\nExplanation: The output [110, 1, 111] would also be accepted.\nExample 2:\nInput: num = \"112358130\"\nOutput: []\nExplanation: The task is impossible.\nExample 3:\nInput: num = \"0123\"\nOutput: []\nExplanation: Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.\n Constraints:\n1 <= num.length <= 200\nnum contains only digits." }, { "post_href": "https://leetcode.com/problems/guess-the-word/discuss/2385099/Python-Solution-with-narrowed-candidates-and-blacklist", "python_solutions": "class Solution:\n def findSecretWord(self, words: List[str], master: 'Master') -> None: \n k = 1 # for tracing the number of loops\n matches = 0\n blacklists = [[] for i in range(6)]\n \n while matches != 6:\n n = len(words)\n r = random.randint(0, n - 1)\n matches = master.guess(words[r])\n key = words[r]\n # print(k, n, r, matches, key)\n \n words.pop(r)\n \n if matches == 0:\n for i in range(6):\n blacklists[i].append(key[i])\n # print(blacklists)\n \n elif matches > 0 and matches < 6:\n candidates = []\n for i in range(n - 1):\n count = 0\n for j in range(6):\n if words[i][j] not in blacklists[j] and words[i][j] == key[j]:\n count += 1\n if count >= matches:\n candidates.append(words[i])\n \n words = candidates.copy()\n # print(words)\n \n k += 1", "slug": "guess-the-word", "post_title": "[Python] Solution with narrowed candidates and blacklist", "user": "bbshark", "upvotes": 2, "views": 203, "problem_title": "guess the word", "number": 843, "acceptance": 0.418, "difficulty": "Hard", "__index_level_0__": 13687, "question": "You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word.\nYou are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns:\n-1 if word is not from words, or\nan integer representing the number of exact matches (value and position) of your guess to the secret word.\nThere is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word).\nFor each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get:\n\"Either you took too many guesses, or you did not find the secret word.\" if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or\n\"You guessed the secret word correctly.\" if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses.\nThe test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method).\n Example 1:\nInput: secret = \"acckzz\", words = [\"acckzz\",\"ccbazz\",\"eiowzz\",\"abcczz\"], allowedGuesses = 10\nOutput: You guessed the secret word correctly.\nExplanation:\nmaster.guess(\"aaaaaa\") returns -1, because \"aaaaaa\" is not in wordlist.\nmaster.guess(\"acckzz\") returns 6, because \"acckzz\" is secret and has all 6 matches.\nmaster.guess(\"ccbazz\") returns 3, because \"ccbazz\" has 3 matches.\nmaster.guess(\"eiowzz\") returns 2, because \"eiowzz\" has 2 matches.\nmaster.guess(\"abcczz\") returns 4, because \"abcczz\" has 4 matches.\nWe made 5 calls to master.guess, and one of them was the secret, so we pass the test case.\nExample 2:\nInput: secret = \"hamada\", words = [\"hamada\",\"khaled\"], allowedGuesses = 10\nOutput: You guessed the secret word correctly.\nExplanation: Since there are two words, you can guess both.\n Constraints:\n1 <= words.length <= 100\nwords[i].length == 6\nwords[i] consist of lowercase English letters.\nAll the strings of wordlist are unique.\nsecret exists in words.\n10 <= allowedGuesses <= 30" }, { "post_href": "https://leetcode.com/problems/backspace-string-compare/discuss/381659/Three-Solutions-in-Python-3-(With-and-Without-Deque-and-Two-Pointer)", "python_solutions": "class Solution:\n def backspaceCompare(self, S: str, T: str) -> bool:\n \ta, A = [collections.deque(), collections.deque()], [S,T]\n \tfor i in range(2):\n\t \tfor j in A[i]:\n \t\t \t\tif j != '#': a[i].append(j)\n \t\t \t\telif a[i]: a[i].pop()\n \treturn a[0] == a[1]", "slug": "backspace-string-compare", "post_title": "Three Solutions in Python 3 (With and Without Deque and Two-Pointer)", "user": "junaidmansuri", "upvotes": 16, "views": 2600, "problem_title": "backspace string compare", "number": 844, "acceptance": 0.48, "difficulty": "Easy", "__index_level_0__": 13692, "question": "Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.\nNote that after backspacing an empty text, the text will continue empty.\n Example 1:\nInput: s = \"ab#c\", t = \"ad#c\"\nOutput: true\nExplanation: Both s and t become \"ac\".\nExample 2:\nInput: s = \"ab##\", t = \"c#d#\"\nOutput: true\nExplanation: Both s and t become \"\".\nExample 3:\nInput: s = \"a#c\", t = \"b\"\nOutput: false\nExplanation: s becomes \"c\" while t becomes \"b\".\n Constraints:\n1 <= s.length, t.length <= 200\ns and t only contain lowercase letters and '#' characters.\n Follow up: Can you solve it in O(n) time and O(1) space?" }, { "post_href": "https://leetcode.com/problems/longest-mountain-in-array/discuss/1837098/Python3%3A-One-pass-O(1)-Auxiliary-Space", "python_solutions": "class Solution:\n def longestMountain(self, arr: List[int]) -> int:\n increasing = False\n increased = False\n mx = -math.inf\n curr = -math.inf\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n if increasing:\n curr += 1\n increased = True\n else:\n mx = max(curr, mx)\n curr = 2\n increased = True\n increasing = True\n elif arr[i] < arr[i-1]:\n if increasing:\n increasing = False\n curr += 1\n else:\n if increased and not increasing:\n mx = max(mx, curr)\n curr = -math.inf\n increased = False\n increasing = False\n if not increasing and increased:\n mx = max(mx, curr)\n return 0 if mx == -math.inf else mx", "slug": "longest-mountain-in-array", "post_title": "Python3: One pass, O(1) Auxiliary Space", "user": "DheerajGadwala", "upvotes": 2, "views": 51, "problem_title": "longest mountain in array", "number": 845, "acceptance": 0.402, "difficulty": "Medium", "__index_level_0__": 13750, "question": "You may recall that an array arr is a mountain array if and only if:\narr.length >= 3\nThere exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:\narr[0] < arr[1] < ... < arr[i - 1] < arr[i]\narr[i] > arr[i + 1] > ... > arr[arr.length - 1]\nGiven an integer array arr, return the length of the longest subarray, which is a mountain. Return 0 if there is no mountain subarray.\n Example 1:\nInput: arr = [2,1,4,7,3,2,5]\nOutput: 5\nExplanation: The largest mountain is [1,4,7,3,2] which has length 5.\nExample 2:\nInput: arr = [2,2,2]\nOutput: 0\nExplanation: There is no mountain.\n Constraints:\n1 <= arr.length <= 104\n0 <= arr[i] <= 104\n Follow up:\nCan you solve it using only one pass?\nCan you solve it in O(1) space?" }, { "post_href": "https://leetcode.com/problems/hand-of-straights/discuss/1938042/Python3-oror-Hashmap-oror-15-line-easy-to-understand", "python_solutions": "class Solution:\n def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n counter = Counter(hand)\n while counter:\n n = groupSize\n start = min(counter.keys())\n while n:\n if start not in counter:\n return False\n counter[start] -= 1\n if not counter[start]:\n del counter[start]\n start += 1\n n -= 1\n return True", "slug": "hand-of-straights", "post_title": "Python3 || Hashmap || 15-line easy to understand", "user": "gulugulugulugulu", "upvotes": 3, "views": 227, "problem_title": "hand of straights", "number": 846, "acceptance": 0.564, "difficulty": "Medium", "__index_level_0__": 13763, "question": "Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.\nGiven an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.\n Example 1:\nInput: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\nOutput: true\nExplanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]\nExample 2:\nInput: hand = [1,2,3,4,5], groupSize = 4\nOutput: false\nExplanation: Alice's hand can not be rearranged into groups of 4.\n Constraints:\n1 <= hand.length <= 104\n0 <= hand[i] <= 109\n1 <= groupSize <= hand.length\n Note: This question is the same as 1296: https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/" }, { "post_href": "https://leetcode.com/problems/shortest-path-visiting-all-nodes/discuss/1800062/Python-Simple-Python-Solution-Using-Breadth-First-Search", "python_solutions": "class Solution:\n\tdef shortestPathLength(self, graph: List[List[int]]) -> int:\n\n\t\tlength = len(graph)\n\n\t\tresult = 0\n\n\t\tvisited_node = []\n\n\t\tqueue = [] \n\n\t\tfor i in range(length):\n\t\t\tvisited_node.append(set([1< str:\n \n final_shift = list(accumulate(shifts[::-1]))[::-1]\n \n s_list = list(S)\n \n for x in range(len(s_list)):\n midval = ord(s_list[x]) + final_shift[x]%26\n if midval > 122:\n midval = midval - 26\n \n s_list[x] = chr(midval)\n \n return ''.join(s_list)", "slug": "shifting-letters", "post_title": "[Python/Python3] Shifting Letter | 2 Solutions | One-liner", "user": "newborncoder", "upvotes": 4, "views": 761, "problem_title": "shifting letters", "number": 848, "acceptance": 0.4539999999999999, "difficulty": "Medium", "__index_level_0__": 13782, "question": "You are given a string s of lowercase English letters and an integer array shifts of the same length.\nCall the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').\nFor example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.\nNow for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.\nReturn the final string after all such shifts to s are applied.\n Example 1:\nInput: s = \"abc\", shifts = [3,5,9]\nOutput: \"rpl\"\nExplanation: We start with \"abc\".\nAfter shifting the first 1 letters of s by 3, we have \"dbc\".\nAfter shifting the first 2 letters of s by 5, we have \"igc\".\nAfter shifting the first 3 letters of s by 9, we have \"rpl\", the answer.\nExample 2:\nInput: s = \"aaa\", shifts = [1,2,3]\nOutput: \"gfd\"\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters.\nshifts.length == s.length\n0 <= shifts[i] <= 109" }, { "post_href": "https://leetcode.com/problems/maximize-distance-to-closest-person/discuss/2706156/python%3A-easy-to-understand-3-situations", "python_solutions": "class Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n #initialization, starting index is 0, result is res\n left,res,index = -1,0,0\n while index != len(seats):\n # only right is 1\n if left == -1 and seats[index] == 1:\n res = max(res,index)\n left = index\n index+=1\n continue\n # only left is 1\n if index == len(seats)-1 and seats[index] == 0:\n res = max(res,index-left)\n index+=1\n continue\n # left and right both 1, sitting in the middle\n if seats[index] == 1:\n res = max(res,(index-left)//2)\n left = index\n index+=1\n return res", "slug": "maximize-distance-to-closest-person", "post_title": "python: easy to understand, 3 situations", "user": "zoey513", "upvotes": 2, "views": 95, "problem_title": "maximize distance to closest person", "number": 849, "acceptance": 0.476, "difficulty": "Medium", "__index_level_0__": 13804, "question": "You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith seat is empty (0-indexed).\nThere is at least one empty seat, and at least one person sitting.\nAlex wants to sit in the seat such that the distance between him and the closest person to him is maximized. \nReturn that maximum distance to the closest person.\n Example 1:\nInput: seats = [1,0,0,0,1,0,1]\nOutput: 2\nExplanation: \nIf Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\nIf Alex sits in any other open seat, the closest person has distance 1.\nThus, the maximum distance to the closest person is 2.\nExample 2:\nInput: seats = [1,0,0,0]\nOutput: 3\nExplanation: \nIf Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\nThis is the maximum distance possible, so the answer is 3.\nExample 3:\nInput: seats = [0,1]\nOutput: 1\n Constraints:\n2 <= seats.length <= 2 * 104\nseats[i] is 0 or 1.\nAt least one seat is empty.\nAt least one seat is occupied." }, { "post_href": "https://leetcode.com/problems/rectangle-area-ii/discuss/1398210/Python3-sweeping", "python_solutions": "class Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n line = []\n for x1, y1, x2, y2 in rectangles: \n line.append((y1, x1, x2, 1))\n line.append((y2, x1, x2, 0))\n \n ans = yy = val = 0\n seg = []\n for y, x1, x2, tf in sorted(line): \n ans += val * (y - yy)\n yy = y \n if tf: insort(seg, (x1, x2))\n else: seg.remove((x1, x2))\n val = 0 \n prev = -inf \n for x1, x2 in seg: \n val += max(0, x2 - max(x1, prev))\n prev = max(prev, x2)\n return ans % 1_000_000_007", "slug": "rectangle-area-ii", "post_title": "[Python3] sweeping", "user": "ye15", "upvotes": 1, "views": 212, "problem_title": "rectangle area ii", "number": 850, "acceptance": 0.537, "difficulty": "Hard", "__index_level_0__": 13840, "question": "You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [xi1, yi1, xi2, yi2] denotes the ith rectangle where (xi1, yi1) are the coordinates of the bottom-left corner, and (xi2, yi2) are the coordinates of the top-right corner.\nCalculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.\nReturn the total area. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\nOutput: 6\nExplanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.\nFrom (1,1) to (2,2), the green and red rectangles overlap.\nFrom (1,0) to (2,3), all three rectangles overlap.\nExample 2:\nInput: rectangles = [[0,0,1000000000,1000000000]]\nOutput: 49\nExplanation: The answer is 1018 modulo (109 + 7), which is 49.\n Constraints:\n1 <= rectangles.length <= 200\nrectanges[i].length == 4\n0 <= xi1, yi1, xi2, yi2 <= 109\nxi1 <= xi2\nyi1 <= yi2" }, { "post_href": "https://leetcode.com/problems/loud-and-rich/discuss/2714041/Python-Pure-topological-sort", "python_solutions": "class Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n richer_count = [0 for _ in range(len(quiet))]\n graph = defaultdict(list)\n answer = [idx for idx in range(len(quiet))]\n \n ## create the graph so that we go from the richer to the poorer\n for rich, poor in richer:\n graph[rich].append(poor)\n richer_count[poor] += 1\n \n ## we include the richest ones.\n queue = collections.deque([])\n for person, rich_count in enumerate(richer_count):\n if not rich_count:\n queue.append(person)\n \n while queue:\n person = queue.popleft()\n ## pointer to the quietest person\n quieter_person = answer[person]\n \n for poorer in graph[person]:\n ## pointer to the quietest person richer than me\n quieter_richer = answer[poorer]\n ## on the answer we are storing the pointer to the quietest one. so for the next poorer we are going to store the pointer which contains the quietest\n answer[poorer] = min(quieter_person, quieter_richer, key = lambda prsn : quiet[prsn])\n richer_count[poorer] -= 1\n if not richer_count[poorer]:\n queue.append(poorer)\n return answer", "slug": "loud-and-rich", "post_title": "Python Pure topological sort", "user": "Henok2011", "upvotes": 1, "views": 77, "problem_title": "loud and rich", "number": 851, "acceptance": 0.5820000000000001, "difficulty": "Medium", "__index_level_0__": 13841, "question": "There is a group of n people labeled from 0 to n - 1 where each person has a different amount of money and a different level of quietness.\nYou are given an array richer where richer[i] = [ai, bi] indicates that ai has more money than bi and an integer array quiet where quiet[i] is the quietness of the ith person. All the given data in richer are logically correct (i.e., the data will not lead you to a situation where x is richer than y and y is richer than x at the same time).\nReturn an integer array answer where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]) among all people who definitely have equal to or more money than the person x.\n Example 1:\nInput: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\nOutput: [5,5,2,5,4,5,6,7]\nExplanation: \nanswer[0] = 5.\nPerson 5 has more money than 3, which has more money than 1, which has more money than 0.\nThe only person who is quieter (has lower quiet[x]) is person 7, but it is not clear if they have more money than person 0.\nanswer[7] = 7.\nAmong all people that definitely have equal to or more money than person 7 (which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x]) is person 7.\nThe other answers can be filled out with similar reasoning.\nExample 2:\nInput: richer = [], quiet = [0]\nOutput: [0]\n Constraints:\nn == quiet.length\n1 <= n <= 500\n0 <= quiet[i] < n\nAll the values of quiet are unique.\n0 <= richer.length <= n * (n - 1) / 2\n0 <= ai, bi < n\nai != bi\nAll the pairs of richer are unique.\nThe observations in richer are all logically consistent." }, { "post_href": "https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/2068528/Simple-Python-one-liner", "python_solutions": "class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n return (arr.index(max(arr)))", "slug": "peak-index-in-a-mountain-array", "post_title": "Simple Python one-liner", "user": "tusharkhanna575", "upvotes": 3, "views": 144, "problem_title": "peak index in a mountain array", "number": 852, "acceptance": 0.6940000000000001, "difficulty": "Medium", "__index_level_0__": 13845, "question": "An array arr is a mountain if the following properties hold:\narr.length >= 3\nThere exists some i with 0 < i < arr.length - 1 such that:\narr[0] < arr[1] < ... < arr[i - 1] < arr[i] \narr[i] > arr[i + 1] > ... > arr[arr.length - 1]\nGiven a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].\nYou must solve it in O(log(arr.length)) time complexity.\n Example 1:\nInput: arr = [0,1,0]\nOutput: 1\nExample 2:\nInput: arr = [0,2,1,0]\nOutput: 1\nExample 3:\nInput: arr = [0,10,5,2]\nOutput: 1\n Constraints:\n3 <= arr.length <= 105\n0 <= arr[i] <= 106\narr is guaranteed to be a mountain array." }, { "post_href": "https://leetcode.com/problems/car-fleet/discuss/939525/Python3-greedy-O(NlogN)", "python_solutions": "class Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n ans = prev = 0\n for pp, ss in sorted(zip(position, speed), reverse=True): \n tt = (target - pp)/ss # time to arrive at target \n if prev < tt: \n ans += 1\n prev = tt\n return ans", "slug": "car-fleet", "post_title": "[Python3] greedy O(NlogN)", "user": "ye15", "upvotes": 17, "views": 1200, "problem_title": "car fleet", "number": 853, "acceptance": 0.501, "difficulty": "Medium", "__index_level_0__": 13892, "question": "There are n cars going to the same destination along a one-lane road. The destination is target miles away.\nYou are given two integer array position and speed, both of length n, where position[i] is the position of the ith car and speed[i] is the speed of the ith car (in miles per hour).\nA car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (i.e., they are assumed to have the same position).\nA car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet.\nIf a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.\nReturn the number of car fleets that will arrive at the destination.\n Example 1:\nInput: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]\nOutput: 3\nExplanation:\nThe cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.\nThe car starting at 0 does not catch up to any other car, so it is a fleet by itself.\nThe cars starting at 5 (speed 1) and 3 (speed 3) become a fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.\nNote that no other cars meet these fleets before the destination, so the answer is 3.\nExample 2:\nInput: target = 10, position = [3], speed = [3]\nOutput: 1\nExplanation: There is only one car, hence there is only one fleet.\nExample 3:\nInput: target = 100, position = [0,2,4], speed = [4,2,1]\nOutput: 1\nExplanation:\nThe cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.\nThen, the fleet (speed 2) and the car starting at 4 (speed 1) become one fleet, meeting each other at 6. The fleet moves at speed 1 until it reaches target.\n Constraints:\nn == position.length == speed.length\n1 <= n <= 105\n0 < target <= 106\n0 <= position[i] < target\nAll the values of position are unique.\n0 < speed[i] <= 106" }, { "post_href": "https://leetcode.com/problems/k-similar-strings/discuss/321201/three-solutions-of-this-problem-good-for-understanding-DFS-DFS-with-memo-and-BFS", "python_solutions": "class Solution:\n # DFS\n def kSimilarity(self, A: str, B: str) -> int:\n N = len(A)\n def dfs(A, B, pos):\n if A == B:\n return 0\n \n while A[pos] == B[pos]:\n pos += 1\n \n minCnt = float('inf')\n for i in range(pos + 1, N):\n if B[i] == A[pos] and B[i] != A[i]:\n B[i], B[pos] = B[pos], B[i]\n tmp = dfs(A, B, pos + 1) + 1\n minCnt = min(tmp, minCnt)\n B[i], B[pos] = B[pos], B[i]\n \n return minCnt\n \n return dfs(list(A), list(B), 0)\n\n # DFS with memorization\n def kSimilarity1(self, A: str, B: str) -> int:\n N = len(A)\n def dfs(A, B, pos):\n sB = ''.join(B)\n if sB in map:\n return map[sB]\n \n if A == B:\n return 0\n \n while A[pos] == B[pos]:\n pos += 1\n \n minCnt = float('inf')\n for i in range(pos + 1, N):\n if B[i] == A[pos] and B[i] != A[i]:\n B[i], B[pos] = B[pos], B[i]\n tmp = dfs(A, B, pos + 1) + 1\n minCnt = min(tmp, minCnt)\n B[i], B[pos] = B[pos], B[i]\n \n map[sB] = minCnt\n return minCnt\n \n map = collections.defaultdict()\n return dfs(list(A), list(B), 0)\n \n # BFS\n def kSimilarity2(self, A: str, B: str) -> int:\n N = len(B)\n q = collections.deque([B])\n visited = set(B)\n \n cnt = 0\n pos = 0\n while q:\n qSize = len(q)\n \n for _ in range(qSize):\n cur = q.popleft()\n if cur == A:\n return cnt\n \n pos = 0\n while cur[pos] == A[pos]:\n pos += 1\n \n lCur = list(cur)\n for i in range(pos + 1, N):\n if lCur[i] == A[pos] and lCur[i] != A[i]:\n lCur[i], lCur[pos] = lCur[pos], lCur[i]\n \n sCur = ''.join(lCur)\n if sCur not in visited:\n q.append(sCur)\n \n visited.add(sCur)\n lCur[i], lCur[pos] = lCur[pos], lCur[i]\n cnt += 1\n \n return cnt", "slug": "k-similar-strings", "post_title": "three solutions of this problem, good for understanding DFS, DFS with memo and BFS", "user": "shchshhappy", "upvotes": 21, "views": 2900, "problem_title": "k similar strings", "number": 854, "acceptance": 0.401, "difficulty": "Hard", "__index_level_0__": 13909, "question": "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.\nGiven two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.\n Example 1:\nInput: s1 = \"ab\", s2 = \"ba\"\nOutput: 1\nExplanation: The two string are 1-similar because we can use one swap to change s1 to s2: \"ab\" --> \"ba\".\nExample 2:\nInput: s1 = \"abc\", s2 = \"bca\"\nOutput: 2\nExplanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: \"abc\" --> \"bac\" --> \"bca\".\n Constraints:\n1 <= s1.length <= 20\ns2.length == s1.length\ns1 and s2 contain only lowercase letters from the set {'a', 'b', 'c', 'd', 'e', 'f'}.\ns2 is an anagram of s1." }, { "post_href": "https://leetcode.com/problems/score-of-parentheses/discuss/2299821/Python-or-faster-than-83-or-easy-understanding-or-explaining-with-comments", "python_solutions": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stk = [0] # temp value to help us\n\n for char in s:\n if char == '(':\n stk.append(0) # new parent: current sum = 0\n else:\n # An expression will be closed\n # Find its value: either 1 for empty () or 2 * its sub-expressions\n # we can calc both with a simple max()\n value = max(2 * stk.pop(), 1)\n\n # Add the expression sum to its parent current sum\n # Assume we have expression E that is (CHD)\n # where C, H, D are valid-subexpressions with values 5, 10, 4\n # then E is (5+10+4) = (19) = 38\n # Every time we finish an expression, we add its value to its parent\n # get the parent and update its sum with a finished sub-expression\n stk[-1] += value\n\n return stk.pop()\n\t\t```", "slug": "score-of-parentheses", "post_title": "Python | faster than 83% | easy-understanding | explaining with comments", "user": "Saiko15", "upvotes": 3, "views": 130, "problem_title": "score of parentheses", "number": 856, "acceptance": 0.65, "difficulty": "Medium", "__index_level_0__": 13915, "question": "Given a balanced parentheses string s, return the score of the string.\nThe score of a balanced parentheses string is based on the following rule:\n\"()\" has score 1.\nAB has score A + B, where A and B are balanced parentheses strings.\n(A) has score 2 * A, where A is a balanced parentheses string.\n Example 1:\nInput: s = \"()\"\nOutput: 1\nExample 2:\nInput: s = \"(())\"\nOutput: 2\nExample 3:\nInput: s = \"()()\"\nOutput: 2\n Constraints:\n2 <= s.length <= 50\ns consists of only '(' and ')'.\ns is a balanced parentheses string." }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-hire-k-workers/discuss/1265778/Python3-greedy-(priority-queue)", "python_solutions": "class Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n ans, rsm = inf, 0\n pq = [] # max-heap \n for q, w in sorted(zip(quality, wage), key=lambda x: x[1]/x[0]): \n rsm += q \n heappush(pq, -q)\n if len(pq) > k: rsm += heappop(pq)\n if len(pq) == k: ans = min(ans, rsm * w/q)\n return ans", "slug": "minimum-cost-to-hire-k-workers", "post_title": "[Python3] greedy (priority queue)", "user": "ye15", "upvotes": 1, "views": 83, "problem_title": "minimum cost to hire k workers", "number": 857, "acceptance": 0.521, "difficulty": "Hard", "__index_level_0__": 13939, "question": "There are n workers. You are given two integer arrays quality and wage where quality[i] is the quality of the ith worker and wage[i] is the minimum wage expectation for the ith worker.\nWe want to hire exactly k workers to form a paid group. To hire a group of k workers, we must pay them according to the following rules:\nEvery worker in the paid group must be paid at least their minimum wage expectation.\nIn the group, each worker's pay must be directly proportional to their quality. This means if a worker\u2019s quality is double that of another worker in the group, then they must be paid twice as much as the other worker.\nGiven the integer k, return the least amount of money needed to form a paid group satisfying the above conditions. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: quality = [10,20,5], wage = [70,50,30], k = 2\nOutput: 105.00000\nExplanation: We pay 70 to 0th worker and 35 to 2nd worker.\nExample 2:\nInput: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3\nOutput: 30.66667\nExplanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.\n Constraints:\nn == quality.length == wage.length\n1 <= k <= n <= 104\n1 <= quality[i], wage[i] <= 104" }, { "post_href": "https://leetcode.com/problems/mirror-reflection/discuss/2376355/Python3-oror-4-lines-geometry-w-explanation-oror-TM%3A-9281", "python_solutions": "class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n\n L = lcm(p,q)\n\n if (L//q)%2 == 0:\n return 2\n\n return (L//p)%2", "slug": "mirror-reflection", "post_title": "Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81%", "user": "warrenruud", "upvotes": 73, "views": 3400, "problem_title": "mirror reflection", "number": 858, "acceptance": 0.633, "difficulty": "Medium", "__index_level_0__": 13943, "question": "There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.\nThe square room has walls of length p and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.\nGiven the two integers p and q, return the number of the receptor that the ray meets first.\nThe test cases are guaranteed so that the ray will meet a receptor eventually.\n Example 1:\nInput: p = 2, q = 1\nOutput: 2\nExplanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\nExample 2:\nInput: p = 3, q = 1\nOutput: 1\n Constraints:\n1 <= q <= p <= 1000" }, { "post_href": "https://leetcode.com/problems/buddy-strings/discuss/2790774/Python-oror-Beginner-Friendly-oror-98-faster-oror-O(n)", "python_solutions": "class Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n\n freq1=[0]*26\n freq2=[0]*26\n diff =0\n\n if(len(s)!=len(goal)):\n return False\n for i in range(len(s)):\n if(s[i]!=goal[i]):\n diff+=1\n freq1[ord(s[i])-ord('a')]+=1\n freq2[ord(goal[i])-ord('a')]+=1\n unique= True\n for idx in range(len(freq1)):\n if(freq1[idx]!=freq2[idx]):\n return False\n if(freq1[idx]>1):\n unique = False\n if(diff==2 or (unique==False and diff==0)):\n return True", "slug": "buddy-strings", "post_title": "Python || Beginner Friendly || 98% faster || O(n)", "user": "hasan2599", "upvotes": 1, "views": 176, "problem_title": "buddy strings", "number": 859, "acceptance": 0.291, "difficulty": "Easy", "__index_level_0__": 13964, "question": "Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.\nSwapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].\nFor example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\".\n Example 1:\nInput: s = \"ab\", goal = \"ba\"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.\nExample 2:\nInput: s = \"ab\", goal = \"ab\"\nOutput: false\nExplanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.\nExample 3:\nInput: s = \"aa\", goal = \"aa\"\nOutput: true\nExplanation: You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.\n Constraints:\n1 <= s.length, goal.length <= 2 * 104\ns and goal consist of lowercase letters." }, { "post_href": "https://leetcode.com/problems/lemonade-change/discuss/1260496/Python-3-Easy-to-understand-Better-than-95", "python_solutions": "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n change5=0\n change10=0\n change20=0\n for i in range(len(bills)):\n if bills[i]==5:\n change5+=1\n elif bills[i]==10:\n change10+=1\n change5-=1\n elif bills[i]==20:\n if change10>0 :\n change5-=1\n change10-=1\n else:\n change5-=3\n change20+=1\n if change5<0 or change10<0 or change20<0:\n return False\n return True", "slug": "lemonade-change", "post_title": "Python 3 Easy-to-understand Better than 95%", "user": "mk_mohtashim", "upvotes": 4, "views": 447, "problem_title": "lemonade change", "number": 860, "acceptance": 0.528, "difficulty": "Easy", "__index_level_0__": 13985, "question": "At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.\nNote that you do not have any change in hand at first.\nGiven an integer array bills where bills[i] is the bill the ith customer pays, return true if you can provide every customer with the correct change, or false otherwise.\n Example 1:\nInput: bills = [5,5,5,10,20]\nOutput: true\nExplanation: \nFrom the first 3 customers, we collect three $5 bills in order.\nFrom the fourth customer, we collect a $10 bill and give back a $5.\nFrom the fifth customer, we give a $10 bill and a $5 bill.\nSince all customers got correct change, we output true.\nExample 2:\nInput: bills = [5,5,10,10,20]\nOutput: false\nExplanation: \nFrom the first two customers in order, we collect two $5 bills.\nFor the next two customers in order, we collect a $10 bill and give back a $5 bill.\nFor the last customer, we can not give the change of $15 back because we only have two $10 bills.\nSince not every customer received the correct change, the answer is false.\n Constraints:\n1 <= bills.length <= 105\nbills[i] is either 5, 10, or 20." }, { "post_href": "https://leetcode.com/problems/score-after-flipping-matrix/discuss/940701/Python3-Greedy-O(MN)", "python_solutions": "class Solution:\n def matrixScore(self, A: List[List[int]]) -> int:\n m, n = len(A), len(A[0])\n for i in range(m):\n if A[i][0] == 0: \n for j in range(n): A[i][j] ^= 1 \n \n for j in range(n): \n cnt = sum(A[i][j] for i in range(m))\n if cnt < m - cnt: \n for i in range(m): A[i][j] ^= 1\n \n return sum(int(\"\".join(map(str, A[i])), 2) for i in range(m))", "slug": "score-after-flipping-matrix", "post_title": "[Python3] Greedy O(MN)", "user": "ye15", "upvotes": 14, "views": 385, "problem_title": "score after flipping matrix", "number": 861, "acceptance": 0.7509999999999999, "difficulty": "Medium", "__index_level_0__": 14001, "question": "You are given an m x n binary matrix grid.\nA move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).\nEvery row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.\nReturn the highest possible score after making any number of moves (including zero moves).\n Example 1:\nInput: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\nOutput: 39\nExplanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39\nExample 2:\nInput: grid = [[0]]\nOutput: 1\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 20\ngrid[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/1515369/Python3-binary-search", "python_solutions": "class Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n loc = {0: -1}\n stack = [0] # increasing stack\n ans, prefix = inf, 0\n for i, x in enumerate(nums): \n prefix += x\n ii = bisect_right(stack, prefix - k)\n if ii: ans = min(ans, i - loc[stack[ii-1]])\n loc[prefix] = i\n while stack and stack[-1] >= prefix: stack.pop()\n stack.append(prefix)\n return ans if ans < inf else -1", "slug": "shortest-subarray-with-sum-at-least-k", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 4, "views": 350, "problem_title": "shortest subarray with sum at least k", "number": 862, "acceptance": 0.261, "difficulty": "Hard", "__index_level_0__": 14015, "question": "Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.\nA subarray is a contiguous part of an array.\n Example 1:\nInput: nums = [1], k = 1\nOutput: 1\nExample 2:\nInput: nums = [1,2], k = 4\nOutput: -1\nExample 3:\nInput: nums = [2,-1,2], k = 3\nOutput: 3\n Constraints:\n1 <= nums.length <= 105\n-105 <= nums[i] <= 105\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/discuss/1606006/Easy-to-understand-Python-graph-solution", "python_solutions": "class Solution:\n def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:\n \n graph=defaultdict(list)\n #create undirected graph\n stack=[root]\n while stack:\n node=stack.pop()\n if node==target:\n targetVal=node.val\n if node.left:\n graph[node.val].append(node.left.val)\n graph[node.left.val].append(node.val)\n stack.append(node.left)\n if node.right:\n graph[node.val].append(node.right.val)\n graph[node.right.val].append(node.val)\n stack.append(node.right)\n \n #start BFS\n q=deque([(targetVal,0)]) #startNode distance=0\n seen=set()\n seen.add(targetVal)\n res=[]\n while q:\n node,depth=q.popleft()\n if depth==k: \n res.append(node)\n if depth>k: break #no need to continue\n\n for neigh in graph[node]:\n if neigh not in seen:\n q.append((neigh,depth+1))\n seen.add(neigh)\n return res", "slug": "all-nodes-distance-k-in-binary-tree", "post_title": "Easy to understand Python \ud83d\udc0d graph solution", "user": "InjySarhan", "upvotes": 6, "views": 439, "problem_title": "all nodes distance k in binary tree", "number": 863, "acceptance": 0.621, "difficulty": "Medium", "__index_level_0__": 14020, "question": "Given the root of a binary tree, the value of a target node target, and an integer k, return an array of the values of all nodes that have a distance k from the target node.\nYou can return the answer in any order.\n Example 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\nOutput: [7,4,1]\nExplanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.\nExample 2:\nInput: root = [1], target = 1, k = 3\nOutput: []\n Constraints:\nThe number of nodes in the tree is in the range [1, 500].\n0 <= Node.val <= 500\nAll the values Node.val are unique.\ntarget is the value of one of the nodes in the tree.\n0 <= k <= 1000" }, { "post_href": "https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/1516812/Python3-bfs", "python_solutions": "class Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n m, n = len(grid), len(grid[0])\n \n ii = jj = total = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j] == \"@\": ii, jj = i, j\n elif grid[i][j].islower(): total += 1\n \n ans = 0\n seen = {(ii, jj, 0)}\n queue = [(ii, jj, 0)]\n while queue: \n newq = []\n for i, j, keys in queue: \n if keys == (1 << total) - 1: return ans \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] != \"#\": \n kk = keys \n if grid[ii][jj].islower(): kk |= 1 << ord(grid[ii][jj]) - 97\n if (ii, jj, kk) in seen or grid[ii][jj].isupper() and not kk & (1 << ord(grid[ii][jj])-65): continue \n newq.append((ii, jj, kk))\n seen.add((ii, jj, kk))\n ans += 1\n queue = newq\n return -1", "slug": "shortest-path-to-get-all-keys", "post_title": "[Python3] bfs", "user": "ye15", "upvotes": 4, "views": 222, "problem_title": "shortest path to get all keys", "number": 864, "acceptance": 0.455, "difficulty": "Hard", "__index_level_0__": 14034, "question": "You are given an m x n grid grid where:\n'.' is an empty cell.\n'#' is a wall.\n'@' is the starting point.\nLowercase letters represent keys.\nUppercase letters represent locks.\nYou start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.\nIf you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.\nFor some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\nReturn the lowest number of moves to acquire all keys. If it is impossible, return -1.\n Example 1:\nInput: grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\nOutput: 8\nExplanation: Note that the goal is to obtain all the keys not to open all the locks.\nExample 2:\nInput: grid = [\"@..aA\",\"..B#.\",\"....b\"]\nOutput: 6\nExample 3:\nInput: grid = [\"@Aa\"]\nOutput: -1\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 30\ngrid[i][j] is either an English letter, '.', '#', or '@'. \nThere is exactly one '@' in the grid.\nThe number of keys in the grid is in the range [1, 6].\nEach key in the grid is unique.\nEach key in the grid has a matching lock." }, { "post_href": "https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/discuss/940618/Python3-dfs-O(N)", "python_solutions": "class Solution:\n def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n \n @lru_cache(None)\n def fn(node):\n \"\"\"Return height of tree rooted at node.\"\"\"\n if not node: return 0\n return 1 + max(fn(node.left), fn(node.right))\n \n node = root\n while node: \n left, right = fn(node.left), fn(node.right)\n if left == right: return node\n elif left > right: node = node.left\n else: node = node.right", "slug": "smallest-subtree-with-all-the-deepest-nodes", "post_title": "[Python3] dfs O(N)", "user": "ye15", "upvotes": 5, "views": 140, "problem_title": "smallest subtree with all the deepest nodes", "number": 865, "acceptance": 0.6859999999999999, "difficulty": "Medium", "__index_level_0__": 14037, "question": "Given the root of a binary tree, the depth of each node is the shortest distance to the root.\nReturn the smallest subtree such that it contains all the deepest nodes in the original tree.\nA node is called the deepest if it has the largest depth possible among any node in the entire tree.\nThe subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.\n Example 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest nodes of the tree.\nNotice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.\nExample 2:\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree.\nExample 3:\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest node in the tree is 2, the valid subtrees are the subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.\n Constraints:\nThe number of nodes in the tree will be in the range [1, 500].\n0 <= Node.val <= 500\nThe values of the nodes in the tree are unique.\n Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/" }, { "post_href": "https://leetcode.com/problems/prime-palindrome/discuss/707393/Python3-check-next-palindrome-Prime-Palindrome", "python_solutions": "class Solution:\n def primePalindrome(self, N: int) -> int:\n def isPrime(N):\n return N > 1 and all(N % d for d in range(2, int(N**0.5)+1))\n \n # N must be a palindrome with odd number of digits.\n # The return value will have odd number of digits too.\n def nextPalindrome(N):\n if N in [999, 99999, 9999999]:\n return (N + 1) * 10 + 1\n n = str(N // 10 ** (len(str(N))//2) + 1)\n return int(n + n[-2::-1])\n \n if N <= 11: \n while not isPrime(N):\n N += 1\n return N\n \n if (digits := len(str(N))) % 2 == 0:\n N = 10 ** digits + 1\n else:\n n = str(N // 10 ** (len(str(N))//2))\n if (p := int(n + n[-2::-1])) >= N:\n N = p\n else:\n N = nextPalindrome(p)\n \n while not isPrime(N):\n N = nextPalindrome(N)\n return N", "slug": "prime-palindrome", "post_title": "Python3 check next palindrome - Prime Palindrome", "user": "r0bertz", "upvotes": 1, "views": 484, "problem_title": "prime palindrome", "number": 866, "acceptance": 0.258, "difficulty": "Medium", "__index_level_0__": 14053, "question": "Given an integer n, return the smallest prime palindrome greater than or equal to n.\nAn integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.\nFor example, 2, 3, 5, 7, 11, and 13 are all primes.\nAn integer is a palindrome if it reads the same from left to right as it does from right to left.\nFor example, 101 and 12321 are palindromes.\nThe test cases are generated so that the answer always exists and is in the range [2, 2 * 108].\n Example 1:\nInput: n = 6\nOutput: 7\nExample 2:\nInput: n = 8\nOutput: 11\nExample 3:\nInput: n = 13\nOutput: 101\n Constraints:\n1 <= n <= 108" }, { "post_href": "https://leetcode.com/problems/transpose-matrix/discuss/2100098/Python-Easy-2-Approaches-one-liner", "python_solutions": "class Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n m,n=len(matrix),len(matrix[0])\n ans = [[None] * m for _ in range(n)]\n for i in range(m):\n for j in range(n):\n ans[j][i]=matrix[i][j]\n \n return ans", "slug": "transpose-matrix", "post_title": "Python Easy - 2 Approaches - one liner", "user": "constantine786", "upvotes": 18, "views": 2600, "problem_title": "transpose matrix", "number": 867, "acceptance": 0.635, "difficulty": "Easy", "__index_level_0__": 14060, "question": "Given a 2D integer array matrix, return the transpose of matrix.\nThe transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\n Example 1:\nInput: matrix = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [[1,4,7],[2,5,8],[3,6,9]]\nExample 2:\nInput: matrix = [[1,2,3],[4,5,6]]\nOutput: [[1,4],[2,5],[3,6]]\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 1000\n1 <= m * n <= 105\n-109 <= matrix[i][j] <= 109" }, { "post_href": "https://leetcode.com/problems/binary-gap/discuss/1306246/Easy-Python-Solution(100)", "python_solutions": "class Solution:\n def binaryGap(self, n: int) -> int:\n if(bin(n).count('1'))==1:\n return 0\n c=0\n x=bin(n)[2:]\n for i in range(len(x)):\n if(x[i]=='1'):\n j=i+1\n while j bool:\n for i in range(32):\n if Counter(str(n))==Counter(str(2**i)):\n return True\n return False", "slug": "reordered-power-of-2", "post_title": "python short and precise answer", "user": "benon", "upvotes": 3, "views": 90, "problem_title": "reordered power of 2", "number": 869, "acceptance": 0.639, "difficulty": "Medium", "__index_level_0__": 14131, "question": "You are given an integer n. We reorder the digits in any order (including the original order) such that the leading digit is not zero.\nReturn true if and only if we can do this so that the resulting number is a power of two.\n Example 1:\nInput: n = 1\nOutput: true\nExample 2:\nInput: n = 10\nOutput: false\n Constraints:\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/advantage-shuffle/discuss/843628/Python-3-or-Greedy-Two-Pointers-or-Explanations", "python_solutions": "class Solution:\n def advantageCount(self, A: List[int], B: List[int]) -> List[int]:\n sorted_a = sorted(A, reverse=True) # descending order\n sorted_b = sorted(enumerate(B), key=lambda x: (x[1], x[0]), reverse=True) # descending order with original index\n n, j = len(B), 0\n ans = [-1] * n\n for i, (ori_idx, val) in enumerate(sorted_b): # A greedily tries to cover value in B as large as possible\n if sorted_a[j] > val: ans[ori_idx], j = sorted_a[j], j+1\n for i in range(n): # assign rest value in A to ans\n if ans[i] == -1: ans[i], j = sorted_a[j], j+1\n return ans", "slug": "advantage-shuffle", "post_title": "Python 3 | Greedy, Two Pointers | Explanations", "user": "idontknoooo", "upvotes": 3, "views": 322, "problem_title": "advantage shuffle", "number": 870, "acceptance": 0.517, "difficulty": "Medium", "__index_level_0__": 14165, "question": "You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].\nReturn any permutation of nums1 that maximizes its advantage with respect to nums2.\n Example 1:\nInput: nums1 = [2,7,11,15], nums2 = [1,10,4,11]\nOutput: [2,11,7,15]\nExample 2:\nInput: nums1 = [12,24,8,32], nums2 = [13,25,32,11]\nOutput: [24,32,8,12]\n Constraints:\n1 <= nums1.length <= 105\nnums2.length == nums1.length\n0 <= nums1[i], nums2[i] <= 109" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-refueling-stops/discuss/2454099/Python3-oror-10-lines-heap-wexplanation-oror-TM%3A-90-98", "python_solutions": "class Solution: # Here's the plan:\n # \n # 1) We only need to be concerned with two quantities: the dist traveled (pos)\n # and the fuel acquired (fuel). We have to refuel before pos > fuel.\n # \n # 2) Because we have an infinite capacity tank, we only have to plan where to acquire\n # fuel before pos > fuel, and common sense says to stop at the station within range\n # with the most fuel.\n # \n # 3) And that's a job for a heap. we heappush the stations that are within range of present\n # fuel, and heappop the best choice if and when we need fuel.\n # \n # 4) We are finished when a) we have acquired sufficient fuel such that fuel >= target \n # (return # of fuelings), or b) fuel < target and the heap is empty (return -1).\n \n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n\n fuel, heap, count = startFuel, [], 0 # <-- initialize some stuff\n \n stations.append([target, 0]) # <-- this handles the \"stations = []\" test\n\n while stations:\n if fuel >= target: return count # <-- 4) \n\n while stations and stations[0][0] <= fuel: # <-- 3)\n _, liters = stations.pop(0)\n heappush(heap,-liters)\n\n if not heap: return -1 # <-- 4)\n fuel-= heappop(heap)\n\n count+= 1", "slug": "minimum-number-of-refueling-stops", "post_title": "Python3 || 10 lines, heap, w/explanation || T/M: 90%/ 98%", "user": "warrenruud", "upvotes": 3, "views": 140, "problem_title": "minimum number of refueling stops", "number": 871, "acceptance": 0.3979999999999999, "difficulty": "Hard", "__index_level_0__": 14170, "question": "A car travels from a starting position to a destination which is target miles east of the starting position.\nThere are gas stations along the way. The gas stations are represented as an array stations where stations[i] = [positioni, fueli] indicates that the ith gas station is positioni miles east of the starting position and has fueli liters of gas.\nThe car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.\nReturn the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.\nNote that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n Example 1:\nInput: target = 1, startFuel = 1, stations = []\nOutput: 0\nExplanation: We can reach the target without refueling.\nExample 2:\nInput: target = 100, startFuel = 1, stations = [[10,100]]\nOutput: -1\nExplanation: We can not reach the target (or even the first gas station).\nExample 3:\nInput: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\nOutput: 2\nExplanation: We start with 10 liters of fuel.\nWe drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\nThen, we drive from position 10 to position 60 (expending 50 liters of fuel),\nand refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\nWe made 2 refueling stops along the way, so we return 2.\n Constraints:\n1 <= target, startFuel <= 109\n0 <= stations.length <= 500\n1 <= positioni < positioni+1 < target\n1 <= fueli < 109" }, { "post_href": "https://leetcode.com/problems/leaf-similar-trees/discuss/1564699/Easy-Python-Solution-or-Faster-than-98-(24ms)", "python_solutions": "class Solution:\n def __init__(self):\n self.n = []\n \n def dfs(self, root):\n if root:\n\t\t\t# checking if the node is leaf\n if not root.left and not root.right: \n\t\t\t\t# appends the leaf nodes to the list - self.n \n self.n.append(root.val) \n\t\t\t\t\n self.dfs(root.left)\n self.dfs(root.right)\n \n def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n self.dfs(root1)\n a = self.n\n self.n = []\n self.dfs(root2)\n \n if a == self.n:\n return True\n else:\n return False", "slug": "leaf-similar-trees", "post_title": "Easy Python Solution | Faster than 98% (24ms)", "user": "the_sky_high", "upvotes": 4, "views": 174, "problem_title": "leaf similar trees", "number": 872, "acceptance": 0.652, "difficulty": "Easy", "__index_level_0__": 14183, "question": "Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.\nFor example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).\nTwo binary trees are considered leaf-similar if their leaf value sequence is the same.\nReturn true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.\n Example 1:\nInput: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]\nOutput: true\nExample 2:\nInput: root1 = [1,2,3], root2 = [1,3,2]\nOutput: false\n Constraints:\nThe number of nodes in each tree will be in the range [1, 200].\nBoth of the given trees will have values in the range [0, 200]." }, { "post_href": "https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/discuss/2732493/python-simple-solution-faster", "python_solutions": "class Solution:\n def lenLongestFibSubseq(self, arr: List[int]) -> int:\n arrset=set(arr)\n res=0\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n a,b,l=arr[i],arr[j],2\n while(a+b in arrset):\n a,b,l=b,a+b,l+1\n res=max(res,l)\n return res if res>=3 else 0", "slug": "length-of-longest-fibonacci-subsequence", "post_title": "python simple solution faster", "user": "Raghunath_Reddy", "upvotes": 0, "views": 8, "problem_title": "length of longest fibonacci subsequence", "number": 873, "acceptance": 0.486, "difficulty": "Medium", "__index_level_0__": 14195, "question": "A sequence x1, x2, ..., xn is Fibonacci-like if:\nn >= 3\nxi + xi+1 == xi+2 for all i + 2 <= n\nGiven a strictly increasing array arr of positive integers forming a sequence, return the length of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.\nA subsequence is derived from another sequence arr by deleting any number of elements (including none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].\n Example 1:\nInput: arr = [1,2,3,4,5,6,7,8]\nOutput: 5\nExplanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].\nExample 2:\nInput: arr = [1,3,7,11,12,14,18]\nOutput: 3\nExplanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].\n Constraints:\n3 <= arr.length <= 1000\n1 <= arr[i] < arr[i + 1] <= 109" }, { "post_href": "https://leetcode.com/problems/walking-robot-simulation/discuss/381840/Solution-in-Python-3", "python_solutions": "class Solution:\n def robotSim(self, c: List[int], b: List[List[int]]) -> int:\n x, y, d, b, M = 0, 0, 0, set([tuple(i) for i in b]), 0\n for i in c:\n if i < 0: d = (d + 2*i + 3)%4\n else:\n if d in [1,3]:\n for x in range(x, x+(i+1)*(2-d), 2-d):\n if (x+(2-d), y) in b: break\n else:\n for y in range(y, y+(i+1)*(1-d), 1-d):\n if (x, y+(1-d)) in b: break\n M = max(M, x**2 + y**2)\n return M\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "walking-robot-simulation", "post_title": "Solution in Python 3", "user": "junaidmansuri", "upvotes": 3, "views": 513, "problem_title": "walking robot simulation", "number": 874, "acceptance": 0.384, "difficulty": "Medium", "__index_level_0__": 14202, "question": "A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:\n-2: Turn left 90 degrees.\n-1: Turn right 90 degrees.\n1 <= k <= 9: Move forward k units, one unit at a time.\nSome of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.\nReturn the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).\nNote:\nNorth means +Y direction.\nEast means +X direction.\nSouth means -Y direction.\nWest means -X direction.\nThere can be obstacle in [0,0].\n Example 1:\nInput: commands = [4,-1,3], obstacles = []\nOutput: 25\nExplanation: The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 3 units to (3, 4).\nThe furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.\nExample 2:\nInput: commands = [4,-1,4,-2,4], obstacles = [[2,4]]\nOutput: 65\nExplanation: The robot starts at (0, 0):\n1. Move north 4 units to (0, 4).\n2. Turn right.\n3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n4. Turn left.\n5. Move north 4 units to (1, 8).\nThe furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.\nExample 3:\nInput: commands = [6,-1,-1,6], obstacles = []\nOutput: 36\nExplanation: The robot starts at (0, 0):\n1. Move north 6 units to (0, 6).\n2. Turn right.\n3. Turn right.\n4. Move south 6 units to (0, 0).\nThe furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.\n Constraints:\n1 <= commands.length <= 104\ncommands[i] is either -2, -1, or an integer in the range [1, 9].\n0 <= obstacles.length <= 104\n-3 * 104 <= xi, yi <= 3 * 104\nThe answer is guaranteed to be less than 231." }, { "post_href": "https://leetcode.com/problems/koko-eating-bananas/discuss/1705145/Python-BinarySearch-%2B-Optimizations-or-Explained", "python_solutions": "class Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n k = 1\n while True:\n total_time = 0\n for i in piles:\n total_time += ceil(i / k)\n if total_time > h:\n k += 1\n else:\n return k", "slug": "koko-eating-bananas", "post_title": "[Python] BinarySearch + Optimizations | Explained", "user": "anCoderr", "upvotes": 20, "views": 814, "problem_title": "koko eating bananas", "number": 875, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 14210, "question": "Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.\nKoko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and eats k bananas from that pile. If the pile has less than k bananas, she eats all of them instead and will not eat any more bananas during this hour.\nKoko likes to eat slowly but still wants to finish eating all the bananas before the guards return.\nReturn the minimum integer k such that she can eat all the bananas within h hours.\n Example 1:\nInput: piles = [3,6,7,11], h = 8\nOutput: 4\nExample 2:\nInput: piles = [30,11,23,4,20], h = 5\nOutput: 30\nExample 3:\nInput: piles = [30,11,23,4,20], h = 6\nOutput: 23\n Constraints:\n1 <= piles.length <= 104\npiles.length <= h <= 109\n1 <= piles[i] <= 109" }, { "post_href": "https://leetcode.com/problems/middle-of-the-linked-list/discuss/526372/PythonJSJavaGoC%2B%2B-O(n)-by-two-pointers-90%2B-w-Diagram", "python_solutions": "class Solution:\n def middleNode(self, head: ListNode) -> ListNode:\n \n slow, fast = head, head\n \n while fast:\n \n fast = fast.next\n if fast:\n fast = fast.next\n else:\n # fast has reached the end of linked list\n # slow is on the middle point now\n break\n \n slow = slow.next\n \n return slow", "slug": "middle-of-the-linked-list", "post_title": "Python/JS/Java/Go/C++ O(n) by two-pointers 90%+ [w/ Diagram]", "user": "brianchiang_tw", "upvotes": 45, "views": 2800, "problem_title": "middle of the linked list", "number": 876, "acceptance": 0.7390000000000001, "difficulty": "Easy", "__index_level_0__": 14233, "question": "Given the head of a singly linked list, return the middle node of the linked list.\nIf there are two middle nodes, return the second middle node.\n Example 1:\nInput: head = [1,2,3,4,5]\nOutput: [3,4,5]\nExplanation: The middle node of the list is node 3.\nExample 2:\nInput: head = [1,2,3,4,5,6]\nOutput: [4,5,6]\nExplanation: Since the list has two middle nodes with values 3 and 4, we return the second one.\n Constraints:\nThe number of nodes in the list is in the range [1, 100].\n1 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/stone-game/discuss/643412/Python-O(-n2-)-by-top-down-DP-w-Comment", "python_solutions": "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n \n\t\t# Alex always win finally, no matter which step he takes first.\n return True", "slug": "stone-game", "post_title": "Python O( n^2 ) by top-down DP [w/ Comment]", "user": "brianchiang_tw", "upvotes": 4, "views": 642, "problem_title": "stone game", "number": 877, "acceptance": 0.6970000000000001, "difficulty": "Medium", "__index_level_0__": 14263, "question": "Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].\nThe objective of the game is to end with the most stones. The total number of stones across all the piles is odd, so there are no ties.\nAlice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile of stones either from the beginning or from the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.\nAssuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.\n Example 1:\nInput: piles = [5,3,4,5]\nOutput: true\nExplanation: \nAlice starts first, and can only take the first 5 or the last 5.\nSay she takes the first 5, so that the row becomes [3, 4, 5].\nIf Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\nIf Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\nThis demonstrated that taking the first 5 was a winning move for Alice, so we return true.\nExample 2:\nInput: piles = [3,7,2,3]\nOutput: true\n Constraints:\n2 <= piles.length <= 500\npiles.length is even.\n1 <= piles[i] <= 500\nsum(piles[i]) is odd." }, { "post_href": "https://leetcode.com/problems/nth-magical-number/discuss/1545825/Python3-binary-search", "python_solutions": "class Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n\t # inclusion-exclusion principle\n ab = lcm(a,b)\n lo, hi = 0, n*min(a, b)\n while lo < hi: \n mid = lo + hi >> 1\n if mid//a + mid//b - mid//ab < n: lo = mid + 1\n else: hi = mid \n return lo % 1_000_000_007", "slug": "nth-magical-number", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 1, "views": 106, "problem_title": "nth magical number", "number": 878, "acceptance": 0.357, "difficulty": "Hard", "__index_level_0__": 14280, "question": "A positive integer is magical if it is divisible by either a or b.\nGiven the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\nInput: n = 1, a = 2, b = 3\nOutput: 2\nExample 2:\nInput: n = 4, a = 2, b = 3\nOutput: 6\n Constraints:\n1 <= n <= 109\n2 <= a, b <= 4 * 104" }, { "post_href": "https://leetcode.com/problems/profitable-schemes/discuss/2661178/Python3-DP", "python_solutions": "class Solution:\n def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:\n # A[i][j][k] = # schemes using subset of first i crimes, using <= j people, with total profit >= k \n A = [[[0 for k in range(minProfit + 1)] for j in range(n + 1)] for i in range(len(profit) + 1)]\n # if using first 0 crimes, only one way, and that if minProfit <= 0\n for j in range(n + 1):\n A[0][j][0] = 1\n for i in range(1, len(profit) + 1):\n for j in range(n + 1):\n for k in range(minProfit + 1):\n # we are here calculating A[j][j][k]\n # two cases, either we use i'th crime or not. \n # but if i'th crime requires more than j people, we con't use it\n if group[i-1] > j:\n A[i][j][k] = A[i-1][j][k]\n else:\n # if i'th crime gets profit greater than k, then we have no restriction \n # on the rest of the groups\n if profit[i-1] > k:\n A[i][j][k] = (A[i-1][j][k] + A[i-1][j-group[i-1]][0]) % (10**9 + 7)\n else:\n A[i][j][k] = (A[i-1][j][k] + A[i-1][j-group[i-1]][k-profit[i-1]]) % (10**9 + 7)\n return A[len(profit)][n][minProfit]", "slug": "profitable-schemes", "post_title": "Python3 DP", "user": "jbradleyglenn", "upvotes": 0, "views": 11, "problem_title": "profitable schemes", "number": 879, "acceptance": 0.4039999999999999, "difficulty": "Hard", "__index_level_0__": 14282, "question": "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.\nLet's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.\nReturn the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\nInput: n = 5, minProfit = 3, group = [2,2], profit = [2,3]\nOutput: 2\nExplanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\nIn total, there are 2 schemes.\nExample 2:\nInput: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\nOutput: 7\nExplanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\nThere are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).\n Constraints:\n1 <= n <= 100\n0 <= minProfit <= 100\n1 <= group.length <= 100\n1 <= group[i] <= 100\nprofit.length == group.length\n0 <= profit[i] <= 100" }, { "post_href": "https://leetcode.com/problems/decoded-string-at-index/discuss/1585059/Python3-Solution-with-using-stack", "python_solutions": "class Solution:\n def decodeAtIndex(self, s: str, k: int) -> str:\n lens = [0]\n \n for c in s:\n if c.isalpha():\n lens.append(lens[-1] + 1)\n else:\n lens.append(lens[-1] * int(c))\n \n for idx in range(len(s), 0, -1):\n k %= lens[idx]\n if k == 0 and s[idx - 1].isalpha():\n return s[idx - 1]\n \n return", "slug": "decoded-string-at-index", "post_title": "[Python3] Solution with using stack", "user": "maosipov11", "upvotes": 2, "views": 217, "problem_title": "decoded string at index", "number": 880, "acceptance": 0.283, "difficulty": "Medium", "__index_level_0__": 14286, "question": "You are given an encoded string s. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:\nIf the character read is a letter, that letter is written onto the tape.\nIf the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.\nGiven an integer k, return the kth letter (1-indexed) in the decoded string.\n Example 1:\nInput: s = \"leet2code3\", k = 10\nOutput: \"o\"\nExplanation: The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\nThe 10th letter in the string is \"o\".\nExample 2:\nInput: s = \"ha22\", k = 5\nOutput: \"h\"\nExplanation: The decoded string is \"hahahaha\".\nThe 5th letter is \"h\".\nExample 3:\nInput: s = \"a2345678999999999999999\", k = 1\nOutput: \"a\"\nExplanation: The decoded string is \"a\" repeated 8301530446056247680 times.\nThe 1st letter is \"a\".\n Constraints:\n2 <= s.length <= 100\ns consists of lowercase English letters and digits 2 through 9.\ns starts with a letter.\n1 <= k <= 109\nIt is guaranteed that k is less than or equal to the length of the decoded string.\nThe decoded string is guaranteed to have less than 263 letters." }, { "post_href": "https://leetcode.com/problems/boats-to-save-people/discuss/1878155/Explained-Python-2-Pointers-Solution", "python_solutions": "class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n people.sort()\n lo = 0\n hi = len(people)-1\n boats = 0\n while lo <= hi:\n if people[lo] + people[hi] <= limit:\n lo += 1\n hi -= 1\n else:\n hi -= 1\n boats += 1\n return boats", "slug": "boats-to-save-people", "post_title": "\u2b50Explained Python 2 Pointers Solution", "user": "anCoderr", "upvotes": 26, "views": 3400, "problem_title": "boats to save people", "number": 881, "acceptance": 0.527, "difficulty": "Medium", "__index_level_0__": 14290, "question": "You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most limit.\nReturn the minimum number of boats to carry every given person.\n Example 1:\nInput: people = [1,2], limit = 3\nOutput: 1\nExplanation: 1 boat (1, 2)\nExample 2:\nInput: people = [3,2,2,1], limit = 3\nOutput: 3\nExplanation: 3 boats (1, 2), (2) and (3)\nExample 3:\nInput: people = [3,5,3,4], limit = 5\nOutput: 4\nExplanation: 4 boats (3), (3), (4), (5)\n Constraints:\n1 <= people.length <= 5 * 104\n1 <= people[i] <= limit <= 3 * 104" }, { "post_href": "https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/discuss/2568608/BFS-intuitive", "python_solutions": "class Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n graph = collections.defaultdict(dict)\n for s, e, n in edges: # n: subnodes in edge\n graph[s][e] = n\n graph[e][s] = n\n \n seen = set() # (start, end, step)\n q = collections.deque()\n for n in graph[0]:\n q.append((0, n, 0))\n \n res = 1\n move = maxMoves\n while q:\n for _ in range(len(q)):\n start, end, step = q.popleft()\n seen.add((start, end, step))\n seen.add((end, start, graph[end][start]-step+1))\n \n if step == graph[start][end] + 1: #check if reached next node\n for n in graph[end]:\n if (end, n, 1) not in seen:\n q.append((end, n, 1))\n res += 1\n \n else:\n if (start, end, step+1) not in seen and (end, start, graph[end][start]-step) not in seen:\n q.append((start, end, step+1))\n res += 1\n \n move -= 1 \n if move == 0:\n break\n\n return res", "slug": "reachable-nodes-in-subdivided-graph", "post_title": "BFS intuitive", "user": "scr112", "upvotes": 0, "views": 15, "problem_title": "reachable nodes in subdivided graph", "number": 882, "acceptance": 0.503, "difficulty": "Hard", "__index_level_0__": 14319, "question": "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.\nThe graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.\nTo subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].\nIn this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.\nGiven the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.\n Example 1:\nInput: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\nOutput: 13\nExplanation: The edge subdivisions are shown in the image above.\nThe nodes that are reachable are highlighted in yellow.\nExample 2:\nInput: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\nOutput: 23\nExample 3:\nInput: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\nOutput: 1\nExplanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n Constraints:\n0 <= edges.length <= min(n * (n - 1) / 2, 104)\nedges[i].length == 3\n0 <= ui < vi < n\nThere are no multiple edges in the graph.\n0 <= cnti <= 104\n0 <= maxMoves <= 109\n1 <= n <= 3000" }, { "post_href": "https://leetcode.com/problems/projection-area-of-3d-shapes/discuss/1357263/Python3-dollarolution", "python_solutions": "class Solution:\n def projectionArea(self, grid: List[List[int]]) -> int:\n p = len(grid)\n x, y, c = [], [0]*p, 0\n for i in range(p):\n x.append(0)\n for j in range(p):\n n = grid[i][j]\n if n > 0:\n c += 1\n if x[i] < n:\n x[i] = n\n if y[j] < n:\n y[j] = n\n\n return (sum(x)+sum(y)+c)", "slug": "projection-area-of-3d-shapes", "post_title": "Python3 $olution", "user": "AakRay", "upvotes": 1, "views": 105, "problem_title": "projection area of 3d shapes", "number": 883, "acceptance": 0.708, "difficulty": "Easy", "__index_level_0__": 14322, "question": "You are given an n x n grid where we place some 1 x 1 x 1 cubes that are axis-aligned with the x, y, and z axes.\nEach value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).\nWe view the projection of these cubes onto the xy, yz, and zx planes.\nA projection is like a shadow, that maps our 3-dimensional figure to a 2-dimensional plane. We are viewing the \"shadow\" when looking at the cubes from the top, the front, and the side.\nReturn the total area of all three projections.\n Example 1:\nInput: grid = [[1,2],[3,4]]\nOutput: 17\nExplanation: Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.\nExample 2:\nInput: grid = [[2]]\nOutput: 5\nExample 3:\nInput: grid = [[1,0],[0,2]]\nOutput: 8\n Constraints:\nn == grid.length == grid[i].length\n1 <= n <= 50\n0 <= grid[i][j] <= 50" }, { "post_href": "https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/1219754/Python3-99-Faster-Solution", "python_solutions": "class Solution:\n def uncommonFromSentences(self, A: str, B: str) -> List[str]:\n uncommon = []\n \n def find_uncommon(s , t):\n ans = []\n for i in s:\n if(s.count(i) == 1 and i not in t):\n ans.append(i)\n \n return ans\n \n return find_uncommon(A.split() , B.split()) + find_uncommon(B.split() , A.split())", "slug": "uncommon-words-from-two-sentences", "post_title": "[Python3] 99% Faster Solution", "user": "VoidCupboard", "upvotes": 3, "views": 188, "problem_title": "uncommon words from two sentences", "number": 884, "acceptance": 0.66, "difficulty": "Easy", "__index_level_0__": 14333, "question": "A sentence is a string of single-space separated words where each word consists only of lowercase letters.\nA word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.\nGiven two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.\n Example 1:\nInput: s1 = \"this apple is sweet\", s2 = \"this apple is sour\"\nOutput: [\"sweet\",\"sour\"]\nExample 2:\nInput: s1 = \"apple apple\", s2 = \"banana\"\nOutput: [\"banana\"]\n Constraints:\n1 <= s1.length, s2.length <= 200\ns1 and s2 consist of lowercase English letters and spaces.\ns1 and s2 do not have leading or trailing spaces.\nAll the words in s1 and s2 are separated by a single space." }, { "post_href": "https://leetcode.com/problems/spiral-matrix-iii/discuss/2718364/Easy-Python-Solution-Based-on-Spiral-Matrix-I-and-II", "python_solutions": "class Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n ans = []\n left, right = cStart, cStart+1\n top, bottom = rStart, rStart+1\n current = 1\n move = 0\n while current <= rows*cols:\n # fill top\n for i in range(left+move, right+1):\n if self.inbound(top, i, rows, cols):\n ans.append([top, i])\n current += 1\n left -= 1\n # fill right\n for i in range(top+1, bottom+1):\n if self.inbound(i, right, rows, cols):\n ans.append([i, right])\n current += 1\n top -= 1\n # fill bottom\n for i in range(right-1, left-1, -1):\n if self.inbound(bottom, i, rows, cols):\n ans.append([bottom, i])\n current += 1\n right += 1\n # fill left\n for i in range(bottom-1, top-1, -1):\n if self.inbound(i, left, rows, cols):\n ans.append([i, left])\n current += 1\n bottom += 1\n move = 1\n return ans\n def inbound(self, r, c, rows, cols):\n return 0<=r bool:\n dislike = [[] for _ in range(n)]\n for a, b in dislikes:\n dislike[a-1].append(b-1)\n dislike[b-1].append(a-1)\n\n groups = [0] * n\n for p in range(n):\n if groups[p] == 0:\n groups[p] = 1\n q = deque([p])\n while q: # bfs\n a = q.pop()\n for b in dislike[a]:\n if groups[b] == 0:\n groups[b] = 1 if groups[a] == 2 else 2\n q.appendleft(b)\n elif groups[a] == groups[b]:\n return False\n return True", "slug": "possible-bipartition", "post_title": "Clean Python3 | Bipartite Graph w/ BFS | Faster Than 99%", "user": "ryangrayson", "upvotes": 2, "views": 148, "problem_title": "possible bipartition", "number": 886, "acceptance": 0.485, "difficulty": "Medium", "__index_level_0__": 14370, "question": "We want to split a group of n people (labeled from 1 to n) into two groups of any size. Each person may dislike some other people, and they should not go into the same group.\nGiven the integer n and the array dislikes where dislikes[i] = [ai, bi] indicates that the person labeled ai does not like the person labeled bi, return true if it is possible to split everyone into two groups in this way.\n Example 1:\nInput: n = 4, dislikes = [[1,2],[1,3],[2,4]]\nOutput: true\nExplanation: The first group has [1,4], and the second group has [2,3].\nExample 2:\nInput: n = 3, dislikes = [[1,2],[1,3],[2,3]]\nOutput: false\nExplanation: We need at least 3 groups to divide them. We cannot put them in two groups.\n Constraints:\n1 <= n <= 2000\n0 <= dislikes.length <= 104\ndislikes[i].length == 2\n1 <= ai < bi <= n\nAll the pairs of dislikes are unique." }, { "post_href": "https://leetcode.com/problems/super-egg-drop/discuss/1468875/Python3-a-few-solutions", "python_solutions": "class Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n \n @cache\n def fn(n, k):\n \"\"\"Return min moves given n floors and k eggs.\"\"\"\n if k == 1: return n\n if n == 0: return 0 \n lo, hi = 1, n + 1\n while lo < hi: \n mid = lo + hi >> 1\n if fn(mid-1, k-1) < fn(n-mid, k): lo = mid + 1\n else: hi = mid \n return 1 + max(fn(lo-1, k-1), fn(n-lo, k))\n \n return fn(n, k)", "slug": "super-egg-drop", "post_title": "[Python3] a few solutions", "user": "ye15", "upvotes": 4, "views": 210, "problem_title": "super egg drop", "number": 887, "acceptance": 0.272, "difficulty": "Hard", "__index_level_0__": 14384, "question": "You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.\nYou know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\nEach move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\nReturn the minimum number of moves that you need to determine with certainty what the value of f is.\n Example 1:\nInput: k = 1, n = 2\nOutput: 2\nExplanation: \nDrop the egg from floor 1. If it breaks, we know that f = 0.\nOtherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\nIf it does not break, then we know f = 2.\nHence, we need at minimum 2 moves to determine with certainty what the value of f is.\nExample 2:\nInput: k = 2, n = 6\nOutput: 3\nExample 3:\nInput: k = 3, n = 14\nOutput: 4\n Constraints:\n1 <= k <= 100\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/fair-candy-swap/discuss/1088075/Python.-Super-simple-solution.", "python_solutions": "class Solution:\n def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:\n difference = (sum(A) - sum(B)) / 2\n A = set(A)\n for candy in set(B):\n if difference + candy in A:\n return [difference + candy, candy]", "slug": "fair-candy-swap", "post_title": "Python. Super simple solution.", "user": "m-d-f", "upvotes": 9, "views": 1000, "problem_title": "fair candy swap", "number": 888, "acceptance": 0.605, "difficulty": "Easy", "__index_level_0__": 14388, "question": "Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.\nSince they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.\nReturn an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.\n Example 1:\nInput: aliceSizes = [1,1], bobSizes = [2,2]\nOutput: [1,2]\nExample 2:\nInput: aliceSizes = [1,2], bobSizes = [2,3]\nOutput: [1,2]\nExample 3:\nInput: aliceSizes = [2], bobSizes = [1,3]\nOutput: [2,3]\n Constraints:\n1 <= aliceSizes.length, bobSizes.length <= 104\n1 <= aliceSizes[i], bobSizes[j] <= 105\nAlice and Bob have a different total number of candies.\nThere will be at least one valid answer for the given input." }, { "post_href": "https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/discuss/946726/Python3-consistent-soln-for-105-106-and-889", "python_solutions": "class Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n mp = {x: i for i, x in enumerate(inorder)} # relative position \n\t\troot = None\n\t stack = []\n for x in preorder: \n if not root: root = node = TreeNode(x)\n elif mp[x] < mp[stack[-1].val]: stack[-1].left = node = TreeNode(x)\n else: \n while stack and mp[stack[-1].val] < mp[x]: node = stack.pop() # retrace \n node.right = node = TreeNode(x)\n stack.append(node)\n return root", "slug": "construct-binary-tree-from-preorder-and-postorder-traversal", "post_title": "[Python3] consistent soln for 105, 106 and 889", "user": "ye15", "upvotes": 3, "views": 128, "problem_title": "construct binary tree from preorder and postorder traversal", "number": 889, "acceptance": 0.708, "difficulty": "Medium", "__index_level_0__": 14402, "question": "Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.\nIf there exist multiple answers, you can return any of them.\n Example 1:\nInput: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\nOutput: [1,2,3,4,5,6,7]\nExample 2:\nInput: preorder = [1], postorder = [1]\nOutput: [1]\n Constraints:\n1 <= preorder.length <= 30\n1 <= preorder[i] <= preorder.length\nAll the values of preorder are unique.\npostorder.length == preorder.length\n1 <= postorder[i] <= postorder.length\nAll the values of postorder are unique.\nIt is guaranteed that preorder and postorder are the preorder traversal and postorder traversal of the same binary tree." }, { "post_href": "https://leetcode.com/problems/find-and-replace-pattern/discuss/500786/Python-O(-nk-)-sol.-by-pattern-matching.-80%2B-With-explanation", "python_solutions": "class Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n \n def helper( s ):\n \n # dictionary\n # key : character\n # value : serial number in string type\n char_index_dict = dict()\n \n # given each unique character a serial number\n for character in s:\n \n if character not in char_index_dict:\n char_index_dict[character] = str( len(char_index_dict) )\n \n \n # gererate corresponding pattern string\n return ''.join( map(char_index_dict.get, s) )\n\n #-------------------------------------------------------- \n \n pattern_string = helper(pattern)\n \n return [ word for word in words if helper(word) == pattern_string ]", "slug": "find-and-replace-pattern", "post_title": "Python O( nk ) sol. by pattern matching. 80%+ [ With explanation ]", "user": "brianchiang_tw", "upvotes": 9, "views": 835, "problem_title": "find and replace pattern", "number": 890, "acceptance": 0.779, "difficulty": "Medium", "__index_level_0__": 14412, "question": "Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.\nA word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.\nRecall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.\n Example 1:\nInput: words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\nOutput: [\"mee\",\"aqq\"]\nExplanation: \"mee\" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n\"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.\nExample 2:\nInput: words = [\"a\",\"b\",\"c\"], pattern = \"a\"\nOutput: [\"a\",\"b\",\"c\"]\n Constraints:\n1 <= pattern.length <= 20\n1 <= words.length <= 50\nwords[i].length == pattern.length\npattern and words[i] are lowercase English letters." }, { "post_href": "https://leetcode.com/problems/sum-of-subsequence-widths/discuss/2839381/MATH-%2B-DP", "python_solutions": "class Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n n = len(nums)\n nums.sort()\n\n dp = [0] * n\n\n p = 2\n temp = nums[0]\n\n for i in range(1, n):\n dp[i] = ((dp[i-1] + ((p-1)*nums[i])%MOD)%MOD - temp)%MOD\n p = (2*p)%MOD\n temp = ((2*temp)%MOD + nums[i])%MOD\n \n return dp[n-1]", "slug": "sum-of-subsequence-widths", "post_title": "MATH + DP", "user": "roboto7o32oo3", "upvotes": 0, "views": 2, "problem_title": "sum of subsequence widths", "number": 891, "acceptance": 0.365, "difficulty": "Hard", "__index_level_0__": 14458, "question": "The width of a sequence is the difference between the maximum and minimum elements in the sequence.\nGiven an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].\n Example 1:\nInput: nums = [2,1,3]\nOutput: 6\nExplanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\nThe corresponding widths are 0, 0, 0, 1, 1, 2, 2.\nThe sum of these widths is 6.\nExample 2:\nInput: nums = [2]\nOutput: 0\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/surface-area-of-3d-shapes/discuss/2329304/Simple-Python-explained", "python_solutions": "class Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n \n l = len(grid)\n area=0\n for row in range(l):\n for col in range(l):\n if grid[row][col]:\n area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected\n if row: #row>0\n area -= min(grid[row][col],grid[row-1][col])*2 #subtracting as area is common among two blocks\n if col: #col>0\n area -= min(grid[row][col],grid[row][col-1])*2 #subtracting as area is common among two blocks\n return area", "slug": "surface-area-of-3d-shapes", "post_title": "Simple Python explained", "user": "sunakshi132", "upvotes": 3, "views": 153, "problem_title": "surface area of 3d shapes", "number": 892, "acceptance": 0.633, "difficulty": "Easy", "__index_level_0__": 14462, "question": "You are given an n x n grid where you have placed some 1 x 1 x 1 cubes. Each value v = grid[i][j] represents a tower of v cubes placed on top of cell (i, j).\nAfter placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.\nReturn the total surface area of the resulting shapes.\nNote: The bottom face of each shape counts toward its surface area.\n Example 1:\nInput: grid = [[1,2],[3,4]]\nOutput: 34\nExample 2:\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 32\nExample 3:\nInput: grid = [[2,2,2],[2,1,2],[2,2,2]]\nOutput: 46\n Constraints:\nn == grid.length == grid[i].length\n1 <= n <= 50\n0 <= grid[i][j] <= 50" }, { "post_href": "https://leetcode.com/problems/groups-of-special-equivalent-strings/discuss/536199/Python-O(n-*-k-lg-k)-sol.-by-signature.-90%2B-w-Hint", "python_solutions": "class Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n signature = set()\n \n # Use pair of sorted even substring and odd substring as unique key\n \n for idx, s in enumerate(A):\n signature.add( ''.join( sorted( s[::2] ) ) + ''.join( sorted( s[1::2] ) ) )\n \n return len( signature )", "slug": "groups-of-special-equivalent-strings", "post_title": "Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint]", "user": "brianchiang_tw", "upvotes": 8, "views": 512, "problem_title": "groups of special equivalent strings", "number": 893, "acceptance": 0.7090000000000001, "difficulty": "Medium", "__index_level_0__": 14470, "question": "You are given an array of strings of the same length words.\nIn one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].\nTwo strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].\nFor example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -> \"xzzy\" -> \"xyzz\".\nA group of special-equivalent strings from words is a non-empty subset of words such that:\nEvery pair of strings in the group are special equivalent, and\nThe group is the largest size possible (i.e., there is not a string words[i] not in the group such that words[i] is special-equivalent to every string in the group).\nReturn the number of groups of special-equivalent strings from words.\n Example 1:\nInput: words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]\nOutput: 3\nExplanation: \nOne group is [\"abcd\", \"cdab\", \"cbad\"], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.\nThe other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\nNote that in particular, \"zzxy\" is not special equivalent to \"zzyx\".\nExample 2:\nInput: words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\nOutput: 3\n Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length <= 20\nwords[i] consist of lowercase English letters.\nAll the strings are of the same length." }, { "post_href": "https://leetcode.com/problems/all-possible-full-binary-trees/discuss/339611/Python-solution-without-recursion-beets-100-speed", "python_solutions": "class Solution:\n def allPossibleFBT(self, N: int) -> List[TreeNode]:\n\t\t# Any full binary trees should contain odd number of nodes\n\t\t# therefore, if N is even, return 0\n\t\tif N % 2 == 0:\n\t\t\treturn []\n\t\t# for all odd n that are less than N, store all FBTs\n trees_all = collections.defaultdict(list)\n\t\t\n\t\t#when there is one node, only one tree is available\n trees_all[1] = [TreeNode(0)]\n for n in range(3, N+1, 2):\n for k in range(1, n, 2):\n # trees with k nodes on the left\n # trees with n - k - 1 nodes on the right\n\t\t\t\t# consider all potential pairs\n for tree1, tree2 in itertools.product(trees_all[k],\n\t\t\t\t\t\t\t\t\t\t\t\t\t trees_all[n-k-1]):\n tree = TreeNode(0)\n tree.left = tree1\n tree.right = tree2\n trees_all[n].append(tree)\n \n return trees_all[N]", "slug": "all-possible-full-binary-trees", "post_title": "Python solution without recursion, beets 100% speed", "user": "KateMelnykova", "upvotes": 8, "views": 825, "problem_title": "all possible full binary trees", "number": 894, "acceptance": 0.8, "difficulty": "Medium", "__index_level_0__": 14479, "question": "Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.\nEach element of the answer is the root node of one possible tree. You may return the final list of trees in any order.\nA full binary tree is a binary tree where each node has exactly 0 or 2 children.\n Example 1:\nInput: n = 7\nOutput: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]\nExample 2:\nInput: n = 3\nOutput: [[0,0,0]]\n Constraints:\n1 <= n <= 20" }, { "post_href": "https://leetcode.com/problems/monotonic-array/discuss/501946/Python-and-Java-Solution-beat-96-and-100", "python_solutions": "class Solution:\n def isMonotonic(self, A: List[int]) -> bool:\n if A[-1] < A[0]: \n A = A[::-1]\n \n for i in range(1, len(A)):\n if A[i] < A[i-1]:\n return False\n return True", "slug": "monotonic-array", "post_title": "Python and Java Solution beat 96% and 100%", "user": "justin801514", "upvotes": 17, "views": 1800, "problem_title": "monotonic array", "number": 896, "acceptance": 0.583, "difficulty": "Easy", "__index_level_0__": 14494, "question": "An array is monotonic if it is either monotone increasing or monotone decreasing.\nAn array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].\nGiven an integer array nums, return true if the given array is monotonic, or false otherwise.\n Example 1:\nInput: nums = [1,2,2,3]\nOutput: true\nExample 2:\nInput: nums = [6,5,4,4]\nOutput: true\nExample 3:\nInput: nums = [1,3,2]\nOutput: false\n Constraints:\n1 <= nums.length <= 105\n-105 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/increasing-order-search-tree/discuss/526258/Python-O(n)-sol-by-DFS-90%2B-w-Diagram", "python_solutions": "class Solution:\n def increasingBST(self, root: TreeNode) -> TreeNode:\n \n prev_node = None\n \n def helper( node: TreeNode):\n \n if node.right:\n helper( node.right )\n\n # prev_novde always points to next larger element for current node\n nonlocal prev_node\n\n # update right link points to next larger element\n node.right = prev_node\n\n # break the left link of next larger element\n if prev_node:\n prev_node.left = None\n\n # update previous node as current node\n prev_node = node\n\n if node.left:\n helper( node.left)\n \n # ---------------------------------------\n helper( root )\n \n return prev_node", "slug": "increasing-order-search-tree", "post_title": "Python O(n) sol by DFS 90%+ [w/ Diagram ]", "user": "brianchiang_tw", "upvotes": 4, "views": 690, "problem_title": "increasing order search tree", "number": 897, "acceptance": 0.785, "difficulty": "Easy", "__index_level_0__": 14537, "question": "Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.\n Example 1:\nInput: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\nOutput: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\nExample 2:\nInput: root = [5,1,7]\nOutput: [1,null,5,null,7]\n Constraints:\nThe number of nodes in the given tree will be in the range [1, 100].\n0 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/bitwise-ors-of-subarrays/discuss/1240982/python-code-with-comment-might-help-to-understand-or", "python_solutions": "class Solution:\n def subarrayBitwiseORs(self, arr: List[int]) -> int:\n \n \n ans=set(arr)\n \n # each element is a subarry\n \n \n one = set()\n \n # to get the ans for the subarray of size >1\n # starting from 0th element to the ending element\n \n \n one.add(arr[0])\n \n for i in range(1,len(arr)):\n \n two=set()\n \n for j in one:\n \n two.add(j | arr[i])\n \n # subarray from the element in one set to the current ele(i th one)\n \n ans.add(j| arr[i])\n \n \n two.add(arr[i])\n \n # adding curr element to set two so that from next iteration we can take sub array starting from curr element \n \n one = two\n \n return len(ans)", "slug": "bitwise-ors-of-subarrays", "post_title": "python code with comment , might help to understand |", "user": "chikushen99", "upvotes": 3, "views": 423, "problem_title": "bitwise ors of subarrays", "number": 898, "acceptance": 0.369, "difficulty": "Medium", "__index_level_0__": 14572, "question": "Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.\nThe bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer.\nA subarray is a contiguous non-empty sequence of elements within an array.\n Example 1:\nInput: arr = [0]\nOutput: 1\nExplanation: There is only one possible result: 0.\nExample 2:\nInput: arr = [1,1,2]\nOutput: 3\nExplanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\nThese yield the results 1, 1, 2, 1, 3, 3.\nThere are 3 unique values, so the answer is 3.\nExample 3:\nInput: arr = [1,2,4]\nOutput: 6\nExplanation: The possible results are 1, 2, 3, 4, 6, and 7.\n Constraints:\n1 <= arr.length <= 5 * 104\n0 <= arr[i] <= 109" }, { "post_href": "https://leetcode.com/problems/orderly-queue/discuss/2783233/Python-Simple-and-Easy-Way-to-Solve-with-Explanation-or-99-Faster", "python_solutions": "class Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n if k > 1:\n return \"\".join(sorted(s))\n \n res = s\n for i in range(0,len(s)):\n s = s[1:] + s[0]\n res = min(res,s)\n \n return res", "slug": "orderly-queue", "post_title": "\u2714\ufe0f Python Simple and Easy Way to Solve with Explanation | 99% Faster \ud83d\udd25", "user": "pniraj657", "upvotes": 12, "views": 577, "problem_title": "orderly queue", "number": 899, "acceptance": 0.665, "difficulty": "Hard", "__index_level_0__": 14574, "question": "You are given a string s and an integer k. You can choose one of the first k letters of s and append it at the end of the string.\nReturn the lexicographically smallest string you could have after applying the mentioned step any number of moves.\n Example 1:\nInput: s = \"cba\", k = 1\nOutput: \"acb\"\nExplanation: \nIn the first move, we move the 1st character 'c' to the end, obtaining the string \"bac\".\nIn the second move, we move the 1st character 'b' to the end, obtaining the final result \"acb\".\nExample 2:\nInput: s = \"baaca\", k = 3\nOutput: \"aaabc\"\nExplanation: \nIn the first move, we move the 1st character 'b' to the end, obtaining the string \"aacab\".\nIn the second move, we move the 3rd character 'c' to the end, obtaining the final result \"aaabc\".\n Constraints:\n1 <= k <= s.length <= 1000\ns consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/numbers-at-most-n-given-digit-set/discuss/1633530/Python3-NOT-BEGINNER-FRIENDLY-Explained", "python_solutions": "class Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n digits = set(int(d) for d in digits)\n dLen = len(digits)\n nStr = str(n)\n nLen = len(nStr)\n \n res = sum(dLen**i for i in range(1, nLen)) # lower dimensions\n \n def helper(firstDigit, slots):\n if slots == 1:\n return sum(d <= firstDigit for d in digits)\n\n return sum(d < firstDigit for d in digits) * dLen**(slots - 1)\n \n for i in range(nLen):\n curDigit = int(nStr[i])\n\n res += helper(curDigit, nLen - i)\n \n if not curDigit in digits: # makes no sense to continue\n break\n \n return res", "slug": "numbers-at-most-n-given-digit-set", "post_title": "\u2714\ufe0f [Python3] NOT BEGINNER FRIENDLY, Explained", "user": "artod", "upvotes": 8, "views": 364, "problem_title": "numbers at most n given digit set", "number": 902, "acceptance": 0.414, "difficulty": "Hard", "__index_level_0__": 14620, "question": "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'.\nReturn the number of positive integers that can be generated that are less than or equal to a given integer n.\n Example 1:\nInput: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\nOutput: 20\nExplanation: \nThe 20 numbers that can be written are:\n1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\nExample 2:\nInput: digits = [\"1\",\"4\",\"9\"], n = 1000000000\nOutput: 29523\nExplanation: \nWe can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\nIn total, this is 29523 integers that can be written using the digits array.\nExample 3:\nInput: digits = [\"7\"], n = 8\nOutput: 1\n Constraints:\n1 <= digits.length <= 9\ndigits[i].length == 1\ndigits[i] is a digit from '1' to '9'.\nAll the values in digits are unique.\ndigits is sorted in non-decreasing order.\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/valid-permutations-for-di-sequence/discuss/1261833/Python3-top-down-dp", "python_solutions": "class Solution:\n def numPermsDISequence(self, s: str) -> int:\n \n @cache \n def fn(i, x): \n \"\"\"Return number of valid permutation given x numbers smaller than previous one.\"\"\"\n if i == len(s): return 1 \n if s[i] == \"D\": \n if x == 0: return 0 # cannot decrease\n return fn(i, x-1) + fn(i+1, x-1)\n else: \n if x == len(s)-i: return 0 # cannot increase \n return fn(i, x+1) + fn(i+1, x)\n \n return sum(fn(0, x) for x in range(len(s)+1)) % 1_000_000_007", "slug": "valid-permutations-for-di-sequence", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 1, "views": 350, "problem_title": "valid permutations for di sequence", "number": 903, "acceptance": 0.5770000000000001, "difficulty": "Hard", "__index_level_0__": 14629, "question": "You are given a string s of length n where s[i] is either:\n'D' means decreasing, or\n'I' means increasing.\nA permutation perm of n + 1 integers of all the integers in the range [0, n] is called a valid permutation if for all valid i:\nIf s[i] == 'D', then perm[i] > perm[i + 1], and\nIf s[i] == 'I', then perm[i] < perm[i + 1].\nReturn the number of valid permutations perm. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\nInput: s = \"DID\"\nOutput: 5\nExplanation: The 5 valid permutations of (0, 1, 2, 3) are:\n(1, 0, 3, 2)\n(2, 0, 3, 1)\n(2, 1, 3, 0)\n(3, 0, 2, 1)\n(3, 1, 2, 0)\nExample 2:\nInput: s = \"D\"\nOutput: 1\n Constraints:\nn == s.length\n1 <= n <= 200\ns[i] is either 'I' or 'D'." }, { "post_href": "https://leetcode.com/problems/fruit-into-baskets/discuss/1414545/Python-clean-%2B-easy-to-understand-or-Sliding-Window-O(N)", "python_solutions": "class Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n fruit_types = Counter()\n distinct = 0\n max_fruits = 0\n \n left = right = 0\n while right < len(fruits):\n # check if it is a new fruit, and update the counter\n if fruit_types[fruits[right]] == 0:\n distinct += 1\n fruit_types[fruits[right]] += 1\n \n # too many different fruits, so start shrinking window\n while distinct > 2:\n fruit_types[fruits[left]] -= 1\n if fruit_types[fruits[left]] == 0:\n distinct -= 1\n left += 1\n \n # set max_fruits to the max window size\n max_fruits = max(max_fruits, right-left+1)\n right += 1\n \n return max_fruits", "slug": "fruit-into-baskets", "post_title": "Python - clean + easy to understand | Sliding Window O(N)", "user": "afm2", "upvotes": 26, "views": 1900, "problem_title": "fruit into baskets", "number": 904, "acceptance": 0.426, "difficulty": "Medium", "__index_level_0__": 14632, "question": "You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.\nYou want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:\nYou only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.\nStarting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.\nOnce you reach a tree with fruit that cannot fit in your baskets, you must stop.\nGiven the integer array fruits, return the maximum number of fruits you can pick.\n Example 1:\nInput: fruits = [1,2,1]\nOutput: 3\nExplanation: We can pick from all 3 trees.\nExample 2:\nInput: fruits = [0,1,2,2]\nOutput: 3\nExplanation: We can pick from trees [1,2,2].\nIf we had started at the first tree, we would only pick from trees [0,1].\nExample 3:\nInput: fruits = [1,2,3,2,2]\nOutput: 4\nExplanation: We can pick from trees [2,3,2,2].\nIf we had started at the first tree, we would only pick from trees [1,2].\n Constraints:\n1 <= fruits.length <= 105\n0 <= fruits[i] < fruits.length" }, { "post_href": "https://leetcode.com/problems/sort-array-by-parity/discuss/356271/Solution-in-Python-3-(beats-~96)-(short)-(-O(1)-space-)-(-O(n)-speed-)", "python_solutions": "class Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n i, j = 0, len(A) - 1\n while i < j:\n \tif A[i] % 2 == 1 and A[j] % 2 == 0: A[i], A[j] = A[j], A[i]\n \ti, j = i + 1 - A[i] % 2, j - A[j] % 2\n return A", "slug": "sort-array-by-parity", "post_title": "Solution in Python 3 (beats ~96%) (short) ( O(1) space ) ( O(n) speed )", "user": "junaidmansuri", "upvotes": 21, "views": 2300, "problem_title": "sort array by parity", "number": 905, "acceptance": 0.757, "difficulty": "Easy", "__index_level_0__": 14657, "question": "Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.\nReturn any array that satisfies this condition.\n Example 1:\nInput: nums = [3,1,2,4]\nOutput: [2,4,3,1]\nExplanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\nExample 2:\nInput: nums = [0]\nOutput: [0]\n Constraints:\n1 <= nums.length <= 5000\n0 <= nums[i] <= 5000" }, { "post_href": "https://leetcode.com/problems/super-palindromes/discuss/1198991/Runtime%3A-Faster-than-94.87-of-Python3-Memory-Usage-less-than-100", "python_solutions": "class Solution:\n \n \n \n nums = []\n for i in range(1, 10**5):\n odd = int(str(i)+str(i)[:-1][::-1])**2\n even = int(str(i)+str(i)[::-1])**2\n \n if str(odd) == str(odd)[::-1]:\n nums.append(odd)\n \n if str(even) == str(even)[::-1]:\n nums.append(even)\n \n nums = sorted(list(set(nums)))\n def superpalindromesInRange(self, left: str, right: str) -> int:\n output = []\n for n in self.nums:\n if int(left) <= n <= int(right):\n output.append(n)\n \n return len(output)", "slug": "super-palindromes", "post_title": "Runtime: Faster than 94.87% of Python3 Memory Usage less than 100%", "user": "pranshusharma712", "upvotes": 1, "views": 102, "problem_title": "super palindromes", "number": 906, "acceptance": 0.392, "difficulty": "Hard", "__index_level_0__": 14705, "question": "Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\nGiven two positive integers left and right represented as strings, return the number of super-palindromes integers in the inclusive range [left, right].\n Example 1:\nInput: left = \"4\", right = \"1000\"\nOutput: 4\nExplanation: 4, 9, 121, and 484 are superpalindromes.\nNote that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\nExample 2:\nInput: left = \"1\", right = \"2\"\nOutput: 1\n Constraints:\n1 <= left.length, right.length <= 18\nleft and right consist of only digits.\nleft and right cannot have leading zeros.\nleft and right represent integers in the range [1, 1018 - 1].\nleft is less than or equal to right." }, { "post_href": "https://leetcode.com/problems/sum-of-subarray-minimums/discuss/2846444/Python-3Monotonic-stack-boundry", "python_solutions": "class Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n M = 10 ** 9 + 7\n\n # right bound for current number as minimum\n\t\tq = []\n n = len(arr)\n right = [n-1] * n \n \n for i in range(n):\n # must put the equal sign to one of the bound (left or right) for duplicate nums (e.g. [71, 55, 82, 55])\n while q and arr[i] <= arr[q[-1]]:\n right[q.pop()] = i - 1\n q.append(i)\n\n # left bound for current number as minimum\n q = []\n left = [0] * n\n for i in reversed(range(n)):\n while q and arr[i] < arr[q[-1]]:\n left[q.pop()] = i + 1\n q.append(i)\n \n # calculate sum for each number\n ans = 0\n for i in range(n):\n l, r = abs(i - left[i]), abs(i - right[i])\n # for example: xx1xxx\n # left take 0, 1, 2 numbers (3 combs) and right take 0, 1, 2, 3 numbers (4 combs)\n covered = (l + 1) * (r + 1)\n ans = (ans + arr[i] * covered) % M\n \n return ans", "slug": "sum-of-subarray-minimums", "post_title": "[Python 3]Monotonic stack boundry", "user": "chestnut890123", "upvotes": 10, "views": 475, "problem_title": "sum of subarray minimums", "number": 907, "acceptance": 0.346, "difficulty": "Medium", "__index_level_0__": 14712, "question": "Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 109 + 7.\n Example 1:\nInput: arr = [3,1,2,4]\nOutput: 17\nExplanation: \nSubarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \nMinimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\nSum is 17.\nExample 2:\nInput: arr = [11,81,94,43,3]\nOutput: 444\n Constraints:\n1 <= arr.length <= 3 * 104\n1 <= arr[i] <= 3 * 104" }, { "post_href": "https://leetcode.com/problems/smallest-range-i/discuss/535164/Python-O(n)-by-min-and-Max.-85%2B-w-Visualization", "python_solutions": "class Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n\n M, m = max(A), min(A)\n diff, extension = M - m, 2*K\n \n if diff <= extension:\n return 0\n \n else:\n return diff - extension", "slug": "smallest-range-i", "post_title": "Python O(n) by min & Max. 85%+ [w/ Visualization ]", "user": "brianchiang_tw", "upvotes": 17, "views": 872, "problem_title": "smallest range i", "number": 908, "acceptance": 0.6779999999999999, "difficulty": "Easy", "__index_level_0__": 14741, "question": "You are given an integer array nums and an integer k.\nIn one operation, you can choose any index i where 0 <= i < nums.length and change nums[i] to nums[i] + x where x is an integer from the range [-k, k]. You can apply this operation at most once for each index i.\nThe score of nums is the difference between the maximum and minimum elements in nums.\nReturn the minimum score of nums after applying the mentioned operation at most once for each index in it.\n Example 1:\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\nExample 2:\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\nExample 3:\nInput: nums = [1,3,6], k = 3\nOutput: 0\nExplanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.\n Constraints:\n1 <= nums.length <= 104\n0 <= nums[i] <= 104\n0 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/snakes-and-ladders/discuss/2491448/Python-3-oror-BFS-Solution-Using-board-mapping", "python_solutions": "class Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \n # creating a borad map to loop-up the square value\n board_map = {}\n i = 1\n b_rev = board[::-1]\n for d, r in enumerate(b_rev):\n\t\t\t# reverse for even rows - here d is taken as direction \n if d%2 != 0: r = r[::-1] \n for s in r:\n board_map[i] = s\n i += 1\n \n # BFS Algorithm\n q = [(1, 0)] # (curr, moves)\n v = set()\n goal = len(board) * len(board) # end square\n \n while q:\n curr, moves = q.pop(0)\n # win situation\n if curr == goal: return moves\n # BFS on next 6 places (rolling a die)\n for i in range(1, 7):\n # skip square outside board\n if curr+i > goal: continue\n # get value from mapping\n next_pos = curr+i if board_map[curr+i] == -1 else board_map[curr+i]\n if next_pos not in v:\n v.add(next_pos)\n q.append((next_pos, moves+1))\n \n return -1", "slug": "snakes-and-ladders", "post_title": "Python 3 || BFS Solution - Using board mapping", "user": "kevintoms", "upvotes": 1, "views": 161, "problem_title": "snakes and ladders", "number": 909, "acceptance": 0.409, "difficulty": "Medium", "__index_level_0__": 14756, "question": "You are given an n x n integer matrix board where the cells are labeled from 1 to n2 in a Boustrophedon style starting from the bottom left of the board (i.e. board[n - 1][0]) and alternating direction each row.\nYou start on square 1 of the board. In each move, starting from square curr, do the following:\nChoose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].\nThis choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.\nIf next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.\nThe game ends when you reach the square n2.\nA board square on row r and column c has a snake or ladder if board[r][c] != -1. The destination of that snake or ladder is board[r][c]. Squares 1 and n2 do not have a snake or ladder.\nNote that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder.\nFor example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.\nReturn the least number of moves required to reach the square n2. If it is not possible to reach the square, return -1.\n Example 1:\nInput: board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\nOutput: 4\nExplanation: \nIn the beginning, you start at square 1 (at row 5, column 0).\nYou decide to move to square 2 and must take the ladder to square 15.\nYou then decide to move to square 17 and must take the snake to square 13.\nYou then decide to move to square 14 and must take the ladder to square 35.\nYou then decide to move to square 36, ending the game.\nThis is the lowest possible number of moves to reach the last square, so return 4.\nExample 2:\nInput: board = [[-1,-1],[-1,3]]\nOutput: 1\n Constraints:\nn == board.length == board[i].length\n2 <= n <= 20\nboard[i][j] is either -1 or in the range [1, n2].\nThe squares labeled 1 and n2 do not have any ladders or snakes." }, { "post_href": "https://leetcode.com/problems/smallest-range-ii/discuss/980784/Python-3-Solution-Explained-(video-%2B-code)", "python_solutions": "class Solution:\n def smallestRangeII(self, A: List[int], K: int) -> int:\n A.sort()\n res = A[-1] - A[0]\n \n for indx in range(0, len(A) - 1):\n # assuming that A[indx] is the max val\n min_val = min(A[0] + K, A[indx + 1] - K)\n max_val = max(A[indx] + K, A[-1] - K)\n res = min(res, max_val - min_val)\n\n return res", "slug": "smallest-range-ii", "post_title": "[Python 3] Solution Explained (video + code)", "user": "spec_he123", "upvotes": 3, "views": 361, "problem_title": "smallest range ii", "number": 910, "acceptance": 0.346, "difficulty": "Medium", "__index_level_0__": 14760, "question": "You are given an integer array nums and an integer k.\nFor each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.\nThe score of nums is the difference between the maximum and minimum elements in nums.\nReturn the minimum score of nums after changing the values at each index.\n Example 1:\nInput: nums = [1], k = 0\nOutput: 0\nExplanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\nExample 2:\nInput: nums = [0,10], k = 2\nOutput: 6\nExplanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\nExample 3:\nInput: nums = [1,3,6], k = 3\nOutput: 3\nExplanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.\n Constraints:\n1 <= nums.length <= 104\n0 <= nums[i] <= 104\n0 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/sort-an-array/discuss/461394/Python-3-(Eight-Sorting-Algorithms)-(With-Explanation)", "python_solutions": "class Solution:\n def sortArray(self, N: List[int]) -> List[int]:\n L = len(N)\n return [N.pop(min(range(L-i), key = lambda x: N[x])) for i in range(L)]", "slug": "sort-an-array", "post_title": "Python 3 (Eight Sorting Algorithms) (With Explanation)", "user": "junaidmansuri", "upvotes": 125, "views": 9200, "problem_title": "sort an array", "number": 912, "acceptance": 0.594, "difficulty": "Medium", "__index_level_0__": 14763, "question": "Given an array of integers nums, sort the array in ascending order and return it.\nYou must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.\n Example 1:\nInput: nums = [5,2,3,1]\nOutput: [1,2,3,5]\nExplanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).\nExample 2:\nInput: nums = [5,1,1,2,0,0]\nOutput: [0,0,1,1,2,5]\nExplanation: Note that the values of nums are not necessairly unique.\n Constraints:\n1 <= nums.length <= 5 * 104\n-5 * 104 <= nums[i] <= 5 * 104" }, { "post_href": "https://leetcode.com/problems/cat-and-mouse/discuss/1563154/Python3-dp-minimax", "python_solutions": "class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n n = len(graph)\n \n @cache\n def fn(i, m, c): \n \"\"\"Return \"\"\"\n if i == 2*n: return 0 # tie \n if m == 0: return 1 # mouse wins\n if m == c: return 2 # cat wins \n if i&1: # cat's turn \n tie = 0 \n for cc in graph[c]: \n if cc != 0: \n x = fn(i+1, m, cc)\n if x == 2: return 2 \n if x == 0: tie = 1\n if tie: return 0 \n return 1\n else: # mouse's turn \n tie = 0 \n for mm in graph[m]: \n x = fn(i+1, mm, c)\n if x == 1: return 1 \n if x == 0: tie = 1\n if tie: return 0\n return 2 \n \n return fn(0, 1, 2)", "slug": "cat-and-mouse", "post_title": "[Python3] dp - minimax", "user": "ye15", "upvotes": 0, "views": 212, "problem_title": "cat and mouse", "number": 913, "acceptance": 0.351, "difficulty": "Hard", "__index_level_0__": 14803, "question": "A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\nThe graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.\nThe mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.\nDuring each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].\nAdditionally, it is not allowed for the Cat to travel to the Hole (node 0).\nThen, the game can end in three ways:\nIf ever the Cat occupies the same node as the Mouse, the Cat wins.\nIf ever the Mouse reaches the Hole, the Mouse wins.\nIf 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.\nGiven a graph, and assuming both players play optimally, return\n1 if the mouse wins the game,\n2 if the cat wins the game, or\n0 if the game is a draw.\n Example 1:\nInput: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\nOutput: 0\nExample 2:\nInput: graph = [[1,3],[0],[3],[0,2]]\nOutput: 1\n Constraints:\n3 <= graph.length <= 50\n1 <= graph[i].length < graph.length\n0 <= graph[i][j] < graph.length\ngraph[i][j] != i\ngraph[i] is unique.\nThe mouse and the cat can always move. " }, { "post_href": "https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/discuss/2821961/Did-you-known-about-'gcd'-function-%3AD", "python_solutions": "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n x = Counter(deck).values()\n return reduce(gcd, x) > 1", "slug": "x-of-a-kind-in-a-deck-of-cards", "post_title": "Did you known about 'gcd' function? :D", "user": "almazgimaev", "upvotes": 0, "views": 3, "problem_title": "x of a kind in a deck of cards", "number": 914, "acceptance": 0.32, "difficulty": "Easy", "__index_level_0__": 14804, "question": "You are given an integer array deck where deck[i] represents the number written on the ith card.\nPartition the cards into one or more groups such that:\nEach group has exactly x cards where x > 1, and\nAll the cards in one group have the same integer written on them.\nReturn true if such partition is possible, or false otherwise.\n Example 1:\nInput: deck = [1,2,3,4,4,3,2,1]\nOutput: true\nExplanation: Possible partition [1,1],[2,2],[3,3],[4,4].\nExample 2:\nInput: deck = [1,1,1,2,2,2,3,3]\nOutput: false\nExplanation: No possible partition.\n Constraints:\n1 <= deck.length <= 104\n0 <= deck[i] < 104" }, { "post_href": "https://leetcode.com/problems/partition-array-into-disjoint-intervals/discuss/1359686/PYTHON-Best-solution-yet!-EXPLAINED-with-comments-to-make-life-easier.-O(n)-and-O(1)", "python_solutions": "class Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n \"\"\"\n Intuition(logic) is to find two maximums.\n One maximum is for left array and other maximum is for right array.\n \n But the condition is that, the right maximum should be such that, \n no element after that right maximum should be less than the left maximum. \n \n If there is any element after right maximum which is less than left maximum,\n that means there is another right maximum possible and therefore in that case assign\n left maximum to right maximum and keep searching the array for correct right\n maximum till the end.\n \"\"\"\n #start with both left maximum and right maximum with first element.\n left_max = right_max = nums[0]\n # our current index\n partition_ind = 0\n # Iterate from 1 to end of the array\n for i in range(1,len(nums)):\n #update right_max always after comparing with each nums\n #in order to find our correct right maximum\n right_max = max(nums[i], right_max)\n \"\"\"\n\t\t\tif current element is less than left maximum, that means this \n element must belong to the left subarray. \n * so our partition index will be updated to current index \n * and left maximum will be updated to right maximum. \n Why left maximum updated to right maximum ?\n Because when we find any element less than left_maximum, that \n means the right maximum which we had till now is not valid and we have\n to find the valid right maximum again while iterating through the end of the loop.\n\t\t\t\"\"\"\n if nums[i] < left_max:\n left_max = right_max\n partition_ind = i\n \n return partition_ind+1", "slug": "partition-array-into-disjoint-intervals", "post_title": "[PYTHON] Best solution yet! EXPLAINED with comments to make life easier. O(n) & O(1)", "user": "er1shivam", "upvotes": 7, "views": 352, "problem_title": "partition array into disjoint intervals", "number": 915, "acceptance": 0.486, "difficulty": "Medium", "__index_level_0__": 14812, "question": "Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:\nEvery element in left is less than or equal to every element in right.\nleft and right are non-empty.\nleft has the smallest possible size.\nReturn the length of left after such a partitioning.\nTest cases are generated such that partitioning exists.\n Example 1:\nInput: nums = [5,0,3,8,6]\nOutput: 3\nExplanation: left = [5,0,3], right = [8,6]\nExample 2:\nInput: nums = [1,1,1,0,6,12]\nOutput: 4\nExplanation: left = [1,1,1,0], right = [6,12]\n Constraints:\n2 <= nums.length <= 105\n0 <= nums[i] <= 106\nThere is at least one valid answer for the given input." }, { "post_href": "https://leetcode.com/problems/word-subsets/discuss/2353565/Solution-Using-Counter-in-Python", "python_solutions": "class Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n result = []\n tempDict = Counter()\n for w in words2:\n tempDict |= Counter(w)\n print(tempDict)\n \n for w in words1:\n if not tempDict - Counter(w):\n result.append(w)\n return result", "slug": "word-subsets", "post_title": "Solution Using Counter in Python", "user": "AY_", "upvotes": 26, "views": 1200, "problem_title": "word subsets", "number": 916, "acceptance": 0.54, "difficulty": "Medium", "__index_level_0__": 14831, "question": "You are given two string arrays words1 and words2.\nA string b is a subset of string a if every letter in b occurs in a including multiplicity.\nFor example, \"wrr\" is a subset of \"warrior\" but is not a subset of \"world\".\nA string a from words1 is universal if for every string b in words2, b is a subset of a.\nReturn an array of all the universal strings in words1. You may return the answer in any order.\n Example 1:\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\nOutput: [\"facebook\",\"google\",\"leetcode\"]\nExample 2:\nInput: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]\nOutput: [\"apple\",\"google\",\"leetcode\"]\n Constraints:\n1 <= words1.length, words2.length <= 104\n1 <= words1[i].length, words2[i].length <= 10\nwords1[i] and words2[i] consist only of lowercase English letters.\nAll the strings of words1 are unique." }, { "post_href": "https://leetcode.com/problems/reverse-only-letters/discuss/337853/Solution-in-Python-3", "python_solutions": "class Solution:\n def reverseOnlyLetters(self, S: str) -> str:\n \tS = list(S)\n \tc = [c for c in S if c.isalpha()]\n \tfor i in range(-1,-len(S)-1,-1):\n \t\tif S[i].isalpha(): S[i] = c.pop(0)\n \treturn \"\".join(S)\n\t\t\n\t\t\n- Python 3\n- Junaid Mansuri", "slug": "reverse-only-letters", "post_title": "Solution in Python 3", "user": "junaidmansuri", "upvotes": 9, "views": 1100, "problem_title": "reverse only letters", "number": 917, "acceptance": 0.615, "difficulty": "Easy", "__index_level_0__": 14860, "question": "Given a string s, reverse the string according to the following rules:\nAll the characters that are not English letters remain in the same position.\nAll the English letters (lowercase or uppercase) should be reversed.\nReturn s after reversing it.\n Example 1:\nInput: s = \"ab-cd\"\nOutput: \"dc-ba\"\nExample 2:\nInput: s = \"a-bC-dEf-ghIj\"\nOutput: \"j-Ih-gfE-dCba\"\nExample 3:\nInput: s = \"Test1ng-Leet=code-Q!\"\nOutput: \"Qedo1ct-eeLg=ntse-T!\"\n Constraints:\n1 <= s.length <= 100\ns consists of characters with ASCII values in the range [33, 122].\ns does not contain '\\\"' or '\\\\'." }, { "post_href": "https://leetcode.com/problems/maximum-sum-circular-subarray/discuss/633106/Python-O(n)-Kadane-DP-w-Visualization", "python_solutions": "class Solution:\n def maxSubarraySumCircular(self, A: List[int]) -> int:\n \n array_sum = 0\n \n local_min_sum, global_min_sum = 0, float('inf')\n local_max_sum, global_max_sum = 0, float('-inf')\n \n for number in A:\n \n local_min_sum = min( local_min_sum + number, number )\n global_min_sum = min( global_min_sum, local_min_sum )\n \n local_max_sum = max( local_max_sum + number, number )\n global_max_sum = max( global_max_sum, local_max_sum )\n \n array_sum += number\n \n \n \n # global_max_sum denotes the maximum subarray sum without crossing boundary\n # arry_sum - global_min_sum denotes the maximum subarray sum with crossing boundary\n \n if global_max_sum > 0:\n return max( array_sum - global_min_sum, global_max_sum )\n else:\n # corner case handle for all number are negative\n return global_max_sum", "slug": "maximum-sum-circular-subarray", "post_title": "Python O(n) Kadane // DP [w/ Visualization]", "user": "brianchiang_tw", "upvotes": 12, "views": 1100, "problem_title": "maximum sum circular subarray", "number": 918, "acceptance": 0.382, "difficulty": "Medium", "__index_level_0__": 14898, "question": "Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.\nA circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].\nA subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.\n Example 1:\nInput: nums = [1,-2,3,-2]\nOutput: 3\nExplanation: Subarray [3] has maximum sum 3.\nExample 2:\nInput: nums = [5,-3,5]\nOutput: 10\nExplanation: Subarray [5,5] has maximum sum 5 + 5 = 10.\nExample 3:\nInput: nums = [-3,-2,-3]\nOutput: -2\nExplanation: Subarray [-2] has maximum sum -2.\n Constraints:\nn == nums.length\n1 <= n <= 3 * 104\n-3 * 104 <= nums[i] <= 3 * 104" }, { "post_href": "https://leetcode.com/problems/number-of-music-playlists/discuss/1358218/Python3-top-down-dp", "python_solutions": "class Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n \n @cache\n def fn(i, x): \n \"\"\"Return number starting from ith position with x songs already appeared.\"\"\"\n if i == goal: return x == n \n ans = 0 \n if x < n: ans += (n-x) * fn(i+1, x+1) # a new song\n if k < x: ans += (x-k) * fn(i+1, x) # an old song\n return ans % 1_000_000_007\n \n return fn(0, 0)", "slug": "number-of-music-playlists", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 132, "problem_title": "number of music playlists", "number": 920, "acceptance": 0.506, "difficulty": "Hard", "__index_level_0__": 14905, "question": "Your music player contains n different songs. You want to listen to goal songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:\nEvery song is played at least once.\nA song can only be played again only if k other songs have been played.\nGiven n, goal, and k, return the number of possible playlists that you can create. Since the answer can be very large, return it modulo 109 + 7.\n Example 1:\nInput: n = 3, goal = 3, k = 1\nOutput: 6\nExplanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].\nExample 2:\nInput: n = 2, goal = 3, k = 0\nOutput: 6\nExplanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].\nExample 3:\nInput: n = 2, goal = 3, k = 1\nOutput: 2\nExplanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].\n Constraints:\n0 <= k < n <= goal <= 100" }, { "post_href": "https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/discuss/1230943/Python3-Simple-Solution", "python_solutions": "class Solution:\n def minAddToMakeValid(self, s: str) -> int:\n count = 0\n \n x = y = 0\n \n for i in s:\n if(i == '('):\n x += 1\n else:\n x -= 1\n \n if(x < 0):\n count += 1\n x = 0\n if(y < 0):\n count += 1\n y = 0\n \n return count + x + y", "slug": "minimum-add-to-make-parentheses-valid", "post_title": "[Python3] Simple Solution", "user": "VoidCupboard", "upvotes": 4, "views": 72, "problem_title": "minimum add to make parentheses valid", "number": 921, "acceptance": 0.762, "difficulty": "Medium", "__index_level_0__": 14906, "question": "A parentheses string is valid if and only if:\nIt is the empty string,\nIt can be written as AB (A concatenated with B), where A and B are valid strings, or\nIt can be written as (A), where A is a valid string.\nYou are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.\nFor example, if s = \"()))\", you can insert an opening parenthesis to be \"(()))\" or a closing parenthesis to be \"())))\".\nReturn the minimum number of moves required to make s valid.\n Example 1:\nInput: s = \"())\"\nOutput: 1\nExample 2:\nInput: s = \"(((\"\nOutput: 3\n Constraints:\n1 <= s.length <= 1000\ns[i] is either '(' or ')'." }, { "post_href": "https://leetcode.com/problems/sort-array-by-parity-ii/discuss/1490850/Simple-to-understand-oror-For-Beginners-oror-91-faster", "python_solutions": "class Solution:\ndef sortArrayByParityII(self, nums: List[int]) -> List[int]:\n \n odd,even = [],[]\n for n in nums:\n if n%2: odd.append(n)\n else: even.append(n)\n \n o,e = 0,0\n for i in range(len(nums)):\n if i%2==0:\n nums[i]=even[e]\n e+=1\n else:\n nums[i]=odd[o]\n o+=1\n \n return nums", "slug": "sort-array-by-parity-ii", "post_title": "\ud83d\udccc\ud83d\udccc Simple to understand || For Beginners || 91% faster \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 6, "views": 283, "problem_title": "sort array by parity ii", "number": 922, "acceptance": 0.7070000000000001, "difficulty": "Easy", "__index_level_0__": 14947, "question": "Given an array of integers nums, half of the integers in nums are odd, and the other half are even.\nSort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.\nReturn any answer array that satisfies this condition.\n Example 1:\nInput: nums = [4,2,5,7]\nOutput: [4,5,2,7]\nExplanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\nExample 2:\nInput: nums = [2,3]\nOutput: [2,3]\n Constraints:\n2 <= nums.length <= 2 * 104\nnums.length is even.\nHalf of the integers in nums are even.\n0 <= nums[i] <= 1000\n Follow Up: Could you solve it in-place?" }, { "post_href": "https://leetcode.com/problems/3sum-with-multiplicity/discuss/1918718/Python-3Sum-Approach-with-Explanation", "python_solutions": "class Solution:\n def threeSumMulti(self, arr: List[int], target: int) -> int:\n arr.sort()\n\t\t# the rest of the code here", "slug": "3sum-with-multiplicity", "post_title": "[Python] 3Sum Approach with Explanation", "user": "zayne-siew", "upvotes": 89, "views": 5500, "problem_title": "3sum with multiplicity", "number": 923, "acceptance": 0.4539999999999999, "difficulty": "Medium", "__index_level_0__": 14976, "question": "Given an integer array arr, and an integer target, return the number of tuples i, j, k such that i < j < k and arr[i] + arr[j] + arr[k] == target.\nAs the answer can be very large, return it modulo 109 + 7.\n Example 1:\nInput: arr = [1,1,2,2,3,3,4,4,5,5], target = 8\nOutput: 20\nExplanation: \nEnumerating by the values (arr[i], arr[j], arr[k]):\n(1, 2, 5) occurs 8 times;\n(1, 3, 4) occurs 8 times;\n(2, 2, 4) occurs 2 times;\n(2, 3, 3) occurs 2 times.\nExample 2:\nInput: arr = [1,1,2,2,2,2], target = 5\nOutput: 12\nExplanation: \narr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\nWe choose one 1 from [1,1] in 2 ways,\nand two 2s from [2,2,2,2] in 6 ways.\nExample 3:\nInput: arr = [2,1,3], target = 6\nOutput: 1\nExplanation: (1, 2, 3) occured one time in the array so we return 1.\n Constraints:\n3 <= arr.length <= 3000\n0 <= arr[i] <= 100\n0 <= target <= 300" }, { "post_href": "https://leetcode.com/problems/minimize-malware-spread/discuss/1934636/Simple-Python-DFS-with-no-Hashmap", "python_solutions": "class Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n initial = set(initial)\n \n def dfs(i):\n nodes.add(i)\n for j, conn in enumerate(graph[i]):\n if conn and j not in nodes:\n dfs(j)\n \n maxRemoval, minNode = -1, float('inf')\n for node in initial:\n nodes = set()\n dfs(node)\n \n if nodes & initial == {node}:\n l = len(nodes)\n if l > maxRemoval or (l == maxRemoval and node < minNode):\n minNode = node\n maxRemoval = l\n \n return minNode if maxRemoval > -1 else min(initial)", "slug": "minimize-malware-spread", "post_title": "Simple Python DFS with no Hashmap", "user": "totoslg", "upvotes": 0, "views": 29, "problem_title": "minimize malware spread", "number": 924, "acceptance": 0.421, "difficulty": "Hard", "__index_level_0__": 14985, "question": "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.\nSome nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\nSuppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.\nReturn the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\nNote that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.\n Example 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\nExample 2:\nInput: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\nOutput: 0\nExample 3:\nInput: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\nOutput: 1\n Constraints:\nn == graph.length\nn == graph[i].length\n2 <= n <= 300\ngraph[i][j] is 0 or 1.\ngraph[i][j] == graph[j][i]\ngraph[i][i] == 1\n1 <= initial.length <= n\n0 <= initial[i] <= n - 1\nAll the integers in initial are unique." }, { "post_href": "https://leetcode.com/problems/long-pressed-name/discuss/1343001/Python3-2-pointers", "python_solutions": "class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n ni = 0 # index of name\n ti = 0 # index of typed\n while ni <= len(name) and ti < len(typed):\n if ni < len(name) and typed[ti] == name[ni]:\n ti += 1\n ni += 1\n elif typed[ti] == name[ni-1] and ni != 0:\n ti += 1\n else:\n return False\n \n return ni == len(name) and ti == len(typed)", "slug": "long-pressed-name", "post_title": "[Python3] 2 pointers", "user": "samirpaul1", "upvotes": 6, "views": 521, "problem_title": "long pressed name", "number": 925, "acceptance": 0.337, "difficulty": "Easy", "__index_level_0__": 14986, "question": "Your friend is typing his name into a keyboard. Sometimes, when typing a character c, the key might get long pressed, and the character will be typed 1 or more times.\nYou examine the typed characters of the keyboard. Return True if it is possible that it was your friends name, with some characters (possibly none) being long pressed.\n Example 1:\nInput: name = \"alex\", typed = \"aaleex\"\nOutput: true\nExplanation: 'a' and 'e' in 'alex' were long pressed.\nExample 2:\nInput: name = \"saeed\", typed = \"ssaaedd\"\nOutput: false\nExplanation: 'e' must have been pressed twice, but it was not in the typed output.\n Constraints:\n1 <= name.length, typed.length <= 1000\nname and typed consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/flip-string-to-monotone-increasing/discuss/1535758/Python3", "python_solutions": "class Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n \"\"\"\n 0 0 1 1 0\n oneCount: 0 0 1 2 2\n zeroCount: 1 1 0 0 1\n flipCount: 0 0 0 0 1\n \n \n 0 1 0 1 0\n oneCount: 0 1 1 2 2\n zeroCount: 1 0 1 1 2\n flipCount: 0 0 1 1 2\n \n 0 0 0 1 1 0 0 0\n oneCount: 0 0 0 1 2 2 2 2\n zeroCount: 1 1 1 0 0 1 2 3\n flipCount: 0 0 0 0 0 1 2 2\n \"\"\"\n oneCount = 0\n zeroCount = 0\n flipCount = 0\n for c in s:\n if c == \"1\":\n oneCount += 1\n if c == \"0\":\n zeroCount += 1\n flipCount = min(zeroCount,oneCount)\n zeroCount = flipCount\n return flipCount", "slug": "flip-string-to-monotone-increasing", "post_title": "[Python3]", "user": "zhanweiting", "upvotes": 2, "views": 165, "problem_title": "flip string to monotone increasing", "number": 926, "acceptance": 0.596, "difficulty": "Medium", "__index_level_0__": 15002, "question": "A binary string is monotone increasing if it consists of some number of 0's (possibly none), followed by some number of 1's (also possibly none).\nYou are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.\nReturn the minimum number of flips to make s monotone increasing.\n Example 1:\nInput: s = \"00110\"\nOutput: 1\nExplanation: We flip the last digit to get 00111.\nExample 2:\nInput: s = \"010110\"\nOutput: 2\nExplanation: We flip to get 011111, or alternatively 000111.\nExample 3:\nInput: s = \"00011000\"\nOutput: 2\nExplanation: We flip to get 00000000.\n Constraints:\n1 <= s.length <= 105\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/three-equal-parts/discuss/1343709/2-clean-Python-linear-solutions", "python_solutions": "class Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n # count number of ones\n ones = sum(arr)\n if ones % 3 != 0:\n return [-1, -1]\n elif ones == 0: # special case: all zeros\n return [0, 2]\n \n # find the start index of each group of ones\n c = 0\n starts = []\n for i, d in enumerate(arr):\n if d == 1:\n if c % (ones // 3) == 0:\n starts.append(i)\n c += 1\n\n # scan the groups in parallel to compare digits\n i, j, k = starts\n while k < len(arr): # note that the last/rightmost group must include all digits till the end\n if arr[i] == arr[j] == arr[k]:\n i += 1\n j += 1\n k += 1\n else:\n return [-1, -1]\n return [i-1, j]", "slug": "three-equal-parts", "post_title": "2 clean Python linear solutions", "user": "cthlo", "upvotes": 7, "views": 265, "problem_title": "three equal parts", "number": 927, "acceptance": 0.396, "difficulty": "Hard", "__index_level_0__": 15021, "question": "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.\nIf it is possible, return any [i, j] with i + 1 < j, such that:\narr[0], arr[1], ..., arr[i] is the first part,\narr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and\narr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.\nAll three parts have equal binary values.\nIf it is not possible, return [-1, -1].\nNote that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.\n Example 1:\nInput: arr = [1,0,1,0,1]\nOutput: [0,3]\nExample 2:\nInput: arr = [1,1,0,1,1]\nOutput: [-1,-1]\nExample 3:\nInput: arr = [1,1,0,0,1]\nOutput: [0,2]\n Constraints:\n3 <= arr.length <= 3 * 104\narr[i] is 0 or 1" }, { "post_href": "https://leetcode.com/problems/minimize-malware-spread-ii/discuss/2845885/Python-9-lines-O(kn2)-BFS", "python_solutions": "class Solution:\n # the key observation for me is the fact that we don't need to\n # really delete the initial in the graph. We can simply ignore\n # the deleted initial while we are doing BFS. So basically we\n # do BFS with each deleted value on initial, and we get the\n # minimal count of the connected graph. Note if two deleted\n # values give same count of connected graph, then we choose\n # smaller value. that's why I used a tuple, (BFS(a), a) this \n # will first compare BFS(a), if they are equal then it compares\n # a.\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n def BFS(delval):\n seen, lst = set(), list(initial)\n while lst:\n node = lst.pop()\n if node == delval or node in seen: continue\n seen.add(node)\n lst += [i for i, val in enumerate(graph[node]) if val]\n return len(seen)\n return min(initial, key=lambda a: (BFS(a), a))", "slug": "minimize-malware-spread-ii", "post_title": "Python 9 lines O(kn^2) BFS", "user": "tinmanSimon", "upvotes": 0, "views": 2, "problem_title": "minimize malware spread ii", "number": 928, "acceptance": 0.426, "difficulty": "Hard", "__index_level_0__": 15027, "question": "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.\nSome nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\nSuppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.\nWe will remove exactly one node from initial, completely removing it and any connections from this node to any other node.\nReturn the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\n Example 1:\nInput: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\nOutput: 0\nExample 2:\nInput: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\nOutput: 1\nExample 3:\nInput: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\nOutput: 1\n Constraints:\nn == graph.length\nn == graph[i].length\n2 <= n <= 300\ngraph[i][j] is 0 or 1.\ngraph[i][j] == graph[j][i]\ngraph[i][i] == 1\n1 <= initial.length < n\n0 <= initial[i] <= n - 1\nAll the integers in initial are unique." }, { "post_href": "https://leetcode.com/problems/unique-email-addresses/discuss/261959/Easy-understanding-python-solution-(44ms-faster-than-99.3)", "python_solutions": "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n def parse(email):\n local, domain = email.split('@')\n local = local.split('+')[0].replace('.',\"\")\n return f\"{local}@{domain}\"\n \n return len(set(map(parse, emails)))", "slug": "unique-email-addresses", "post_title": "Easy-understanding python solution (44ms, faster than 99.3%)", "user": "ShaneTsui", "upvotes": 19, "views": 1300, "problem_title": "unique email addresses", "number": 929, "acceptance": 0.672, "difficulty": "Easy", "__index_level_0__": 15029, "question": "Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'.\nFor example, in \"alice@leetcode.com\", \"alice\" is the local name, and \"leetcode.com\" is the domain name.\nIf you add periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule does not apply to domain names.\nFor example, \"alice.z@leetcode.com\" and \"alicez@leetcode.com\" forward to the same email address.\nIf you add a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that this rule does not apply to domain names.\nFor example, \"m.y+name@email.com\" will be forwarded to \"my@email.com\".\nIt is possible to use both of these rules at the same time.\nGiven an array of strings emails where we send one email to each emails[i], return the number of different addresses that actually receive mails.\n Example 1:\nInput: emails = [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"]\nOutput: 2\nExplanation: \"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails.\nExample 2:\nInput: emails = [\"a@leetcode.com\",\"b@leetcode.com\",\"c@leetcode.com\"]\nOutput: 3\n Constraints:\n1 <= emails.length <= 100\n1 <= emails[i].length <= 100\nemails[i] consist of lowercase English letters, '+', '.' and '@'.\nEach emails[i] contains exactly one '@' character.\nAll local and domain names are non-empty.\nLocal names do not start with a '+' character.\nDomain names end with the \".com\" suffix." }, { "post_href": "https://leetcode.com/problems/binary-subarrays-with-sum/discuss/957414/Python3-hash-O(N)", "python_solutions": "class Solution:\n def numSubarraysWithSum(self, A: List[int], S: int) -> int:\n ans = prefix = 0\n seen = {0: 1}\n for x in A:\n prefix += x\n ans += seen.get(prefix - S, 0)\n seen[prefix] = 1 + seen.get(prefix, 0)\n return ans", "slug": "binary-subarrays-with-sum", "post_title": "[Python3] hash O(N)", "user": "ye15", "upvotes": 2, "views": 167, "problem_title": "binary subarrays with sum", "number": 930, "acceptance": 0.511, "difficulty": "Medium", "__index_level_0__": 15073, "question": "Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.\nA subarray is a contiguous part of the array.\n Example 1:\nInput: nums = [1,0,1,0,1], goal = 2\nOutput: 4\nExplanation: The 4 subarrays are bolded and underlined below:\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\n[1,0,1,0,1]\nExample 2:\nInput: nums = [0,0,0,0,0], goal = 0\nOutput: 15\n Constraints:\n1 <= nums.length <= 3 * 104\nnums[i] is either 0 or 1.\n0 <= goal <= nums.length" }, { "post_href": "https://leetcode.com/problems/minimum-falling-path-sum/discuss/1628101/Easy-and-Simple-Python-solution", "python_solutions": "class Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n \n r=len(matrix)\n c=len(matrix[0])\n \n for i in range(1,r):\n for j in range(c):\n \n if j==0:\n matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j+1])\n \n elif j==c-1:\n matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j-1])\n \n else:\n matrix[i][j]+=min(matrix[i-1][j],matrix[i-1][j-1],matrix[i-1][j+1])\n \n \n return min(matrix[r-1])", "slug": "minimum-falling-path-sum", "post_title": "Easy and Simple Python solution", "user": "diksha_choudhary", "upvotes": 2, "views": 87, "problem_title": "minimum falling path sum", "number": 931, "acceptance": 0.685, "difficulty": "Medium", "__index_level_0__": 15084, "question": "Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.\nA falling path starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position (row, col) will be (row + 1, col - 1), (row + 1, col), or (row + 1, col + 1).\n Example 1:\nInput: matrix = [[2,1,3],[6,5,4],[7,8,9]]\nOutput: 13\nExplanation: There are two falling paths with a minimum sum as shown.\nExample 2:\nInput: matrix = [[-19,57],[-40,-5]]\nOutput: -59\nExplanation: The falling path with a minimum sum is shown.\n Constraints:\nn == matrix.length == matrix[i].length\n1 <= n <= 100\n-100 <= matrix[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/beautiful-array/discuss/1368125/Detailed-Explanation-with-Diagrams.-A-Collection-of-Ideas-from-Multiple-Posts.-Python3", "python_solutions": "class Solution:\n def recurse(self, nums):\n if len(nums) <= 2: return nums\n return self.recurse(nums[::2]) + self.recurse(nums[1::2])\n \n def beautifulArray(self, n: int) -> List[int]:\n return self.recurse([i for i in range(1, n+1)])", "slug": "beautiful-array", "post_title": "Detailed Explanation with Diagrams. A Collection of Ideas from Multiple Posts. [Python3]", "user": "chaudhary1337", "upvotes": 45, "views": 1500, "problem_title": "beautiful array", "number": 932, "acceptance": 0.6509999999999999, "difficulty": "Medium", "__index_level_0__": 15133, "question": "An array nums of length n is beautiful if:\nnums is a permutation of the integers in the range [1, n].\nFor every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j].\nGiven the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n.\n Example 1:\nInput: n = 4\nOutput: [2,1,4,3]\nExample 2:\nInput: n = 5\nOutput: [3,1,2,5,4]\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/shortest-bridge/discuss/958926/Python3-DFS-and-BFS", "python_solutions": "class Solution:\n def shortestBridge(self, A: List[List[int]]) -> int:\n m, n = len(A), len(A[0])\n i, j = next((i, j) for i in range(m) for j in range(n) if A[i][j])\n \n # dfs \n stack = [(i, j)]\n seen = set(stack)\n while stack: \n i, j = stack.pop()\n seen.add((i, j)) # mark as visited \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and A[ii][jj] and (ii, jj) not in seen: \n stack.append((ii, jj))\n seen.add((ii, jj))\n \n # bfs \n ans = 0\n queue = list(seen)\n while queue:\n newq = []\n for i, j in queue: \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen: \n if A[ii][jj] == 1: return ans \n newq.append((ii, jj))\n seen.add((ii, jj))\n queue = newq\n ans += 1", "slug": "shortest-bridge", "post_title": "[Python3] DFS & BFS", "user": "ye15", "upvotes": 7, "views": 512, "problem_title": "shortest bridge", "number": 934, "acceptance": 0.54, "difficulty": "Medium", "__index_level_0__": 15139, "question": "You are given an n x n binary matrix grid where 1 represents land and 0 represents water.\nAn island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.\nYou may change 0's to 1's to connect the two islands to form one island.\nReturn the smallest number of 0's you must flip to connect the two islands.\n Example 1:\nInput: grid = [[0,1],[1,0]]\nOutput: 1\nExample 2:\nInput: grid = [[0,1,0],[0,0,0],[0,0,1]]\nOutput: 2\nExample 3:\nInput: grid = [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]\nOutput: 1\n Constraints:\nn == grid.length == grid[i].length\n2 <= n <= 100\ngrid[i][j] is either 0 or 1.\nThere are exactly two islands in grid." }, { "post_href": "https://leetcode.com/problems/knight-dialer/discuss/1544986/Python-simple-dp-O(n)-time-O(1)-space", "python_solutions": "class Solution:\n def knightDialer(self, n: int) -> int:\n arr = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n \n \n for _ in range(n-1):\n dp = [0 for _ in range(10)]\n dp[0] = arr[5] + arr[7]\n dp[1] = arr[6] + arr[8]\n dp[2] = arr[3] + arr[7]\n dp[3] = arr[2] + arr[8] + arr[9]\n dp[4] = 0\n dp[5] = arr[0] + arr[6] + arr[9]\n dp[6] = arr[1] + arr[5]\n dp[7] = arr[0] + arr[2]\n dp[8] = arr[1] + arr[3]\n dp[9] = arr[3] + arr[5]\n arr = dp\n return sum(arr) % (10**9+7)", "slug": "knight-dialer", "post_title": "Python simple dp, O(n) time O(1) space", "user": "byuns9334", "upvotes": 3, "views": 493, "problem_title": "knight dialer", "number": 935, "acceptance": 0.5, "difficulty": "Medium", "__index_level_0__": 15150, "question": "The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram:\nA chess knight can move as indicated in the chess diagram below:\nWe have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).\nGiven an integer n, return how many distinct phone numbers of length n we can dial.\nYou are allowed to place the knight on any numeric cell initially and then you should perform n - 1 jumps to dial a number of length n. All jumps should be valid knight jumps.\nAs the answer may be very large, return the answer modulo 109 + 7.\n Example 1:\nInput: n = 1\nOutput: 10\nExplanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.\nExample 2:\nInput: n = 2\nOutput: 20\nExplanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]\nExample 3:\nInput: n = 3131\nOutput: 136006598\nExplanation: Please take care of the mod.\n Constraints:\n1 <= n <= 5000" }, { "post_href": "https://leetcode.com/problems/stamping-the-sequence/discuss/1888562/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SIMPLE-ITERATION-oror-EASIEST-YOU-WILL-FIND-EVER-!!-oror", "python_solutions": "class Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n N,M = len(target),len(stamp)\n move = 0\n maxmove = 10*N\n ans = []\n def check(string):\n for i in range(M):\n if string[i] == stamp[i] or string[i] == '?':\n continue\n else:\n return False\n return True\n \n while move < maxmove:\n premove = move\n for i in range(N-M+1):\n if check(target[i:i+M]):\n move += 1\n ans.append(i)\n target = target[:i] + \"?\"*M + target[i+M:]\n if target == \"?\"*N : return ans[::-1]\n if premove == move:return []\n return []", "slug": "stamping-the-sequence", "post_title": "PYTHON SOL || WELL EXPLAINED || SIMPLE ITERATION || EASIEST YOU WILL FIND EVER !! ||", "user": "reaper_27", "upvotes": 7, "views": 258, "problem_title": "stamping the sequence", "number": 936, "acceptance": 0.633, "difficulty": "Hard", "__index_level_0__": 15162, "question": "You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.\nIn one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.\nFor example, if stamp = \"abc\" and target = \"abcba\", then s is \"?????\" initially. In one turn you can:\nplace stamp at index 0 of s to obtain \"abc??\",\nplace stamp at index 1 of s to obtain \"?abc?\", or\nplace stamp at index 2 of s to obtain \"??abc\".\nNote that stamp must be fully contained in the boundaries of s in order to stamp (i.e., you cannot place stamp at index 3 of s).\nWe want to convert s to target using at most 10 * target.length turns.\nReturn an array of the index of the left-most letter being stamped at each turn. If we cannot obtain target from s within 10 * target.length turns, return an empty array.\n Example 1:\nInput: stamp = \"abc\", target = \"ababc\"\nOutput: [0,2]\nExplanation: Initially s = \"?????\".\n- Place stamp at index 0 to get \"abc??\".\n- Place stamp at index 2 to get \"ababc\".\n[1,0,2] would also be accepted as an answer, as well as some other answers.\nExample 2:\nInput: stamp = \"abca\", target = \"aabcaca\"\nOutput: [3,0,1]\nExplanation: Initially s = \"???????\".\n- Place stamp at index 3 to get \"???abca\".\n- Place stamp at index 0 to get \"abcabca\".\n- Place stamp at index 1 to get \"aabcaca\".\n Constraints:\n1 <= stamp.length <= target.length <= 1000\nstamp and target consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/reorder-data-in-log-files/discuss/1135934/Python3-simple-solution", "python_solutions": "class Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n l = []\n d = []\n for i in logs:\n if i.split()[1].isdigit():\n d.append(i)\n else:\n l.append(i)\n l.sort(key = lambda x : x.split()[0])\n l.sort(key = lambda x : x.split()[1:])\n return l + d", "slug": "reorder-data-in-log-files", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 12, "views": 495, "problem_title": "reorder data in log files", "number": 937, "acceptance": 0.564, "difficulty": "Medium", "__index_level_0__": 15172, "question": "You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.\nThere are two types of logs:\nLetter-logs: All words (except the identifier) consist of lowercase English letters.\nDigit-logs: All words (except the identifier) consist of digits.\nReorder these logs so that:\nThe letter-logs come before all digit-logs.\nThe letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.\nThe digit-logs maintain their relative ordering.\nReturn the final order of the logs.\n Example 1:\nInput: logs = [\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"]\nOutput: [\"let1 art can\",\"let3 art zero\",\"let2 own kit dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]\nExplanation:\nThe letter-log contents are all different, so their ordering is \"art can\", \"art zero\", \"own kit dig\".\nThe digit-logs have a relative order of \"dig1 8 1 5 1\", \"dig2 3 6\".\nExample 2:\nInput: logs = [\"a1 9 2 3 1\",\"g1 act car\",\"zo4 4 7\",\"ab1 off key dog\",\"a8 act zoo\"]\nOutput: [\"g1 act car\",\"a8 act zoo\",\"ab1 off key dog\",\"a1 9 2 3 1\",\"zo4 4 7\"]\n Constraints:\n1 <= logs.length <= 100\n3 <= logs[i].length <= 100\nAll the tokens of logs[i] are separated by a single space.\nlogs[i] is guaranteed to have an identifier and at least one word after the identifier." }, { "post_href": "https://leetcode.com/problems/range-sum-of-bst/discuss/1627963/Python3-ITERATIVE-BFS-Explained", "python_solutions": "class Solution:\n def rangeSumBST(self, root: Optional[TreeNode], lo: int, hi: int) -> int:\n res = 0\n \n q = deque([root])\n while q:\n c = q.popleft()\n v, l, r = c.val, c.left, c.right\n\n if lo <= v and v <= hi:\n res += v\n \n if l and (lo < v or v > hi):\n q.append(l)\n \n if r and (lo > v or v < hi):\n q.append(r)\n \n return res", "slug": "range-sum-of-bst", "post_title": "\u2714\ufe0f [Python3] ITERATIVE BFS, Explained", "user": "artod", "upvotes": 3, "views": 237, "problem_title": "range sum of bst", "number": 938, "acceptance": 0.8540000000000001, "difficulty": "Easy", "__index_level_0__": 15196, "question": "Given the root node of a binary search tree and two integers low and high, return the sum of values of all nodes with a value in the inclusive range [low, high].\n Example 1:\nInput: root = [10,5,15,3,7,null,18], low = 7, high = 15\nOutput: 32\nExplanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\nExample 2:\nInput: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\nOutput: 23\nExplanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n Constraints:\nThe number of nodes in the tree is in the range [1, 2 * 104].\n1 <= Node.val <= 105\n1 <= low <= high <= 105\nAll Node.val are unique." }, { "post_href": "https://leetcode.com/problems/minimum-area-rectangle/discuss/1888886/PYTHON-SOLUTION-oror-PASSED-ALL-CASES-oror-WELL-EXPLAINED-oror-EASY-SOL-oror", "python_solutions": "class Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n x_axis = defaultdict(dict)\n y_axis = defaultdict(dict)\n d = {}\n points.sort()\n \n ans = float('inf')\n \n for point in points:\n x_axis[point[0]][point[1]] = True\n y_axis[point[1]][point[0]] = True\n d[(point[0],point[1])] = True\n\n for point in points:\n x1 = point[0]\n y1 = point[1]\n for y2 in x_axis[x1]:\n if y2 == y1:continue\n for x2 in y_axis[y2]:\n if x2 == x1:continue\n if (x2,y1) in d:\n tmp = abs(x2-x1) * abs(y2-y1)\n if tmp < ans : ans = tmp\n return ans if ans!=float('inf') else 0", "slug": "minimum-area-rectangle", "post_title": "PYTHON SOLUTION || PASSED ALL CASES || WELL EXPLAINED || EASY SOL ||", "user": "reaper_27", "upvotes": 1, "views": 489, "problem_title": "minimum area rectangle", "number": 939, "acceptance": 0.53, "difficulty": "Medium", "__index_level_0__": 15226, "question": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi].\nReturn the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.\n Example 1:\nInput: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\nOutput: 4\nExample 2:\nInput: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\nOutput: 2\n Constraints:\n1 <= points.length <= 500\npoints[i].length == 2\n0 <= xi, yi <= 4 * 104\nAll the given points are unique." }, { "post_href": "https://leetcode.com/problems/distinct-subsequences-ii/discuss/1894186/PYTHON-SOL-oror-DP-oror-EXPLAINED-oror-FULL-APPROACH-EXPLAINED-oror-TLE-TO-OPTIMIZED-SOL-oror", "python_solutions": "class Solution:\n def distinctSubseqII(self, s: str) -> int:\n n = len(s)\n MOD = 1000000007\n dp = {}\n \n def recursion(string,index):\n ans = 1 if index > 0 else 0\n used = {}\n for idx in range(index,n):\n if s[idx] in used:continue\n used[s[idx]] = True\n ans += recursion(string + s[idx] , idx + 1)\n \n return ans\n \n res = recursion(\"\",0)%MOD\n return res", "slug": "distinct-subsequences-ii", "post_title": "PYTHON SOL || DP || EXPLAINED || FULL APPROACH EXPLAINED || TLE TO OPTIMIZED SOL ||", "user": "reaper_27", "upvotes": 0, "views": 102, "problem_title": "distinct subsequences ii", "number": 940, "acceptance": 0.4429999999999999, "difficulty": "Hard", "__index_level_0__": 15230, "question": "Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., \"ace\" is a subsequence of \"abcde\" while \"aec\" is not.\n Example 1:\nInput: s = \"abc\"\nOutput: 7\nExplanation: The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".\nExample 2:\nInput: s = \"aba\"\nOutput: 6\nExplanation: The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".\nExample 3:\nInput: s = \"aaa\"\nOutput: 3\nExplanation: The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".\n Constraints:\n1 <= s.length <= 2000\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/valid-mountain-array/discuss/338636/Python-solution-using-Two-pointer-from-opposite-sides", "python_solutions": "class Solution:\n def validMountainArray(self, A: List[int]) -> bool:\n if len(A)<3:return False\n l=len(A)\n i,j=0,l-1\n while i0 and A[j]= 3\nThere exists some i with 0 < i < arr.length - 1 such that:\narr[0] < arr[1] < ... < arr[i - 1] < arr[i] \narr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n Example 1:\nInput: arr = [2,1]\nOutput: false\nExample 2:\nInput: arr = [3,5,5]\nOutput: false\nExample 3:\nInput: arr = [0,3,2,1]\nOutput: true\n Constraints:\n1 <= arr.length <= 104\n0 <= arr[i] <= 104" }, { "post_href": "https://leetcode.com/problems/di-string-match/discuss/1199072/Python3-Simple-And-Readable-Solution", "python_solutions": "class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n a , b = 0 , len(s)\n \n for i in s:\n if(i == 'I'):\n ans.append(a)\n a += 1\n else:\n ans.append(b)\n b -= 1\n \n if(s[-1] == 'D'):\n ans.append(a)\n else:\n ans.append(b)\n \n return ans", "slug": "di-string-match", "post_title": "[Python3] Simple And Readable Solution", "user": "VoidCupboard", "upvotes": 7, "views": 157, "problem_title": "di string match", "number": 942, "acceptance": 0.768, "difficulty": "Easy", "__index_level_0__": 15279, "question": "A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:\ns[i] == 'I' if perm[i] < perm[i + 1], and\ns[i] == 'D' if perm[i] > perm[i + 1].\nGiven a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.\n Example 1:\nInput: s = \"IDID\"\nOutput: [0,4,1,3,2]\nExample 2:\nInput: s = \"III\"\nOutput: [0,1,2,3]\nExample 3:\nInput: s = \"DDI\"\nOutput: [3,2,0,1]\n Constraints:\n1 <= s.length <= 105\ns[i] is either 'I' or 'D'." }, { "post_href": "https://leetcode.com/problems/find-the-shortest-superstring/discuss/1231147/Python3-travelling-sales-person-(TSP)", "python_solutions": "class Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n n = len(words)\n graph = [[0]*n for _ in range(n)] # graph as adjacency matrix \n \n for i in range(n):\n for j in range(n): \n if i != j: \n for k in range(len(words[j])): \n if words[i].endswith(words[j][:k]): \n graph[i][j] = len(words[j]) - k \n \n @cache\n def fn(prev, mask): \n \"\"\"Return length of shortest superstring & current choice of word.\"\"\"\n if mask == 0: return 0, None\n vv, kk = inf, None\n for k in range(n): \n if mask & 1< int:\n zipped=list(map(list,zip(*A)))\n count=0\n for item in zipped:\n if item!=sorted(item):\n count+=1\n return count", "slug": "delete-columns-to-make-sorted", "post_title": "Python3 6 line 96ms beats 99%, easy to understand", "user": "wangzi100", "upvotes": 3, "views": 244, "problem_title": "delete columns to make sorted", "number": 944, "acceptance": 0.696, "difficulty": "Easy", "__index_level_0__": 15304, "question": "You are given an array of n strings strs, all of the same length.\nThe strings can be arranged such that there is one on each line, making a grid.\nFor example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as follows:\nabc\nbce\ncae\nYou want to delete the columns that are not sorted lexicographically. In the above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are sorted, while column 1 ('b', 'c', 'a') is not, so you would delete column 1.\nReturn the number of columns that you will delete.\n Example 1:\nInput: strs = [\"cba\",\"daf\",\"ghi\"]\nOutput: 1\nExplanation: The grid looks as follows:\n cba\n daf\n ghi\nColumns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.\nExample 2:\nInput: strs = [\"a\",\"b\"]\nOutput: 0\nExplanation: The grid looks as follows:\n a\n b\nColumn 0 is the only column and is sorted, so you will not delete any columns.\nExample 3:\nInput: strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput: 3\nExplanation: The grid looks as follows:\n zyx\n wvu\n tsr\nAll 3 columns are not sorted, so you will delete all 3.\n Constraints:\nn == strs.length\n1 <= n <= 100\n1 <= strs[i].length <= 1000\nstrs[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-increment-to-make-array-unique/discuss/1897470/PYTHON-SOL-oror-WELL-EXPLAINED-oror-SORTING-ororGREEDYoror-APPROACH-EXPLAINED-oror-SIMPLE-oror-O(n*log(n))oror", "python_solutions": "class Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n ans = 0\n for i in range(1,n):\n if nums[i] <= nums[i-1]:\n # this is the case for making item unique\n diff = nums[i-1] + 1 - nums[i]\n ans += diff\n nums[i] = nums[i-1] + 1\n return ans", "slug": "minimum-increment-to-make-array-unique", "post_title": "PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))||", "user": "reaper_27", "upvotes": 8, "views": 271, "problem_title": "minimum increment to make array unique", "number": 945, "acceptance": 0.504, "difficulty": "Medium", "__index_level_0__": 15323, "question": "You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.\nReturn the minimum number of moves to make every value in nums unique.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\nInput: nums = [1,2,2]\nOutput: 1\nExplanation: After 1 move, the array could be [1, 2, 3].\nExample 2:\nInput: nums = [3,2,1,2,1,7]\nOutput: 6\nExplanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\nIt can be shown with 5 or less moves that it is impossible for the array to have all unique values.\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/validate-stack-sequences/discuss/1106110/Easy-python-solution-or-86-memory-86-time", "python_solutions": "class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack = []\n for i in pushed:\n stack.append(i)\n while stack and popped and stack[-1] == popped[0]:\n stack.pop()\n popped.pop(0)\n return not stack", "slug": "validate-stack-sequences", "post_title": "Easy python solution | 86% memory 86% time", "user": "vanigupta20024", "upvotes": 6, "views": 259, "problem_title": "validate stack sequences", "number": 946, "acceptance": 0.6759999999999999, "difficulty": "Medium", "__index_level_0__": 15333, "question": "Given two integer arrays pushed and popped each with distinct values, return true if this could have been the result of a sequence of push and pop operations on an initially empty stack, or false otherwise.\n Example 1:\nInput: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\nOutput: true\nExplanation: We might do the following sequence:\npush(1), push(2), push(3), push(4),\npop() -> 4,\npush(5),\npop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\nExample 2:\nInput: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\nOutput: false\nExplanation: 1 cannot be popped before 2.\n Constraints:\n1 <= pushed.length <= 1000\n0 <= pushed[i] <= 1000\nAll the elements of pushed are unique.\npopped.length == pushed.length\npopped is a permutation of pushed." }, { "post_href": "https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/discuss/1689443/For-Beginners-oror-Count-Number-of-Connected-Graphs-O(N)-oror-94-Faster", "python_solutions": "class Solution:\n\t\tdef removeStones(self, stones: List[List[int]]) -> int:\n\t\t\t\n\t\t\tdef remove_point(a,b): # Function to remove connected points from the ongoing graph. \n\t\t\t\tpoints.discard((a,b))\n\t\t\t\tfor y in x_dic[a]:\n\t\t\t\t\tif (a,y) in points:\n\t\t\t\t\t\tremove_point(a,y)\n\n\t\t\t\tfor x in y_dic[b]:\n\t\t\t\t\tif (x,b) in points:\n\t\t\t\t\t\tremove_point(x,b)\n\n\t\t\tx_dic = defaultdict(list)\n\t\t\ty_dic = defaultdict(list)\n\t\t\tpoints= {(i,j) for i,j in stones}\n\t\t\t\n\t\t\tfor i,j in stones: # Construction of graph by x_coordinates and y_coordinates.\n\t\t\t\tx_dic[i].append(j)\n\t\t\t\ty_dic[j].append(i)\n\n\t\t\tcnt = 0\n\t\t\tfor a,b in stones: # counting of distinct connected graph.\n\t\t\t\tif (a,b) in points:\n\t\t\t\t\tremove_point(a,b)\n\t\t\t\t\tcnt+=1\n\n\t\t\treturn len(stones)-cnt", "slug": "most-stones-removed-with-same-row-or-column", "post_title": "\ud83d\udccc\ud83d\udccc For Beginners || Count Number of Connected Graphs O(N) || 94% Faster \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 22, "views": 1500, "problem_title": "most stones removed with same row or column", "number": 947, "acceptance": 0.588, "difficulty": "Medium", "__index_level_0__": 15374, "question": "On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.\nA stone can be removed if it shares either the same row or the same column as another stone that has not been removed.\nGiven an array stones of length n where stones[i] = [xi, yi] represents the location of the ith stone, return the largest possible number of stones that can be removed.\n Example 1:\nInput: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\nOutput: 5\nExplanation: One way to remove 5 stones is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,1].\n2. Remove stone [2,1] because it shares the same column as [0,1].\n3. Remove stone [1,2] because it shares the same row as [1,0].\n4. Remove stone [1,0] because it shares the same column as [0,0].\n5. Remove stone [0,1] because it shares the same row as [0,0].\nStone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.\nExample 2:\nInput: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\nOutput: 3\nExplanation: One way to make 3 moves is as follows:\n1. Remove stone [2,2] because it shares the same row as [2,0].\n2. Remove stone [2,0] because it shares the same column as [0,0].\n3. Remove stone [0,2] because it shares the same row as [0,0].\nStones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.\nExample 3:\nInput: stones = [[0,0]]\nOutput: 0\nExplanation: [0,0] is the only stone on the plane, so you cannot remove it.\n Constraints:\n1 <= stones.length <= 1000\n0 <= xi, yi <= 104\nNo two stones are at the same coordinate point." }, { "post_href": "https://leetcode.com/problems/bag-of-tokens/discuss/2564480/Easy-python-solution-TC%3A-O(nlogn)-SC%3A-O(1)", "python_solutions": "class Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n score=0\n tokens.sort()\n i=0\n j=len(tokens)-1\n mx=0\n while i<=j:\n if tokens[i]<=power:\n power-=tokens[i]\n score+=1\n i+=1\n mx=max(mx,score)\n elif score>0:\n score-=1\n power+=tokens[j]\n j-=1\n else:\n break\n return mx", "slug": "bag-of-tokens", "post_title": "Easy python solution TC: O(nlogn), SC: O(1)", "user": "shubham_1307", "upvotes": 10, "views": 820, "problem_title": "bag of tokens", "number": 948, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 15407, "question": "You start with an initial power of power, an initial score of 0, and a bag of tokens given as an integer array tokens, where each tokens[i] denotes the value of tokeni.\nYour goal is to maximize the total score by strategically playing these tokens. In one move, you can play an unplayed token in one of the two ways (but not both for the same token):\nFace-up: If your current power is at least tokens[i], you may play tokeni, losing tokens[i] power and gaining 1 score.\nFace-down: If your current score is at least 1, you may play tokeni, gaining tokens[i] power and losing 1 score.\nReturn the maximum possible score you can achieve after playing any number of tokens.\n Example 1:\nInput: tokens = [100], power = 50\nOutput: 0\nExplanation: Since your score is 0 initially, you cannot play the token face-down. You also cannot play it face-up since your power (50) is less than tokens[0] (100).\nExample 2:\nInput: tokens = [200,100], power = 150\nOutput: 1\nExplanation: Play token1 (100) face-up, reducing your power to 50 and increasing your score to 1.\nThere is no need to play token0, since you cannot play it face-up to add to your score. The maximum score achievable is 1.\nExample 3:\nInput: tokens = [100,200,300,400], power = 200\nOutput: 2\nExplanation: Play the tokens in this order to get a score of 2:\nPlay token0 (100) face-up, reducing power to 100 and increasing score to 1.\nPlay token3 (400) face-down, increasing power to 500 and reducing score to 0.\nPlay token1 (200) face-up, reducing power to 300 and increasing score to 1.\nPlay token2 (300) face-up, reducing power to 0 and increasing score to 2.\nThe maximum score achievable is 2.\n Constraints:\n0 <= tokens.length <= 1000\n0 <= tokens[i], power < 104" }, { "post_href": "https://leetcode.com/problems/largest-time-for-given-digits/discuss/406661/Python3-6-line-via-permutation", "python_solutions": "class Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n hh = mm = -1\n for x in set(permutations(A, 4)): \n h = 10*x[0] + x[1]\n m = 10*x[2] + x[3]\n if h < 24 and m < 60 and 60*h + m > 60*hh + mm: hh, mm = h, m\n return f\"{hh:02}:{mm:02}\" if hh >= 0 else \"\"", "slug": "largest-time-for-given-digits", "post_title": "[Python3] 6-line via permutation", "user": "ye15", "upvotes": 2, "views": 124, "problem_title": "largest time for given digits", "number": 949, "acceptance": 0.352, "difficulty": "Medium", "__index_level_0__": 15445, "question": "Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.\n24-hour times are formatted as \"HH:MM\", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.\nReturn the latest 24-hour time in \"HH:MM\" format. If no valid time can be made, return an empty string.\n Example 1:\nInput: arr = [1,2,3,4]\nOutput: \"23:41\"\nExplanation: The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.\nExample 2:\nInput: arr = [5,5,5,5]\nOutput: \"\"\nExplanation: There are no valid 24-hour times as \"55:55\" is not valid.\n Constraints:\narr.length == 4\n0 <= arr[i] <= 9" }, { "post_href": "https://leetcode.com/problems/reveal-cards-in-increasing-order/discuss/394028/Solution-in-Python-3-(Deque)-(three-lines)", "python_solutions": "class Solution:\n def deckRevealedIncreasing(self, D: List[int]) -> List[int]:\n \tL, Q, _ = len(D)-1, collections.deque(), D.sort()\n \tfor _ in range(L): Q.appendleft(D.pop()), Q.appendleft(Q.pop())\n \treturn D + list(Q)\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "reveal-cards-in-increasing-order", "post_title": "Solution in Python 3 (Deque) (three lines)", "user": "junaidmansuri", "upvotes": 5, "views": 803, "problem_title": "reveal cards in increasing order", "number": 950, "acceptance": 0.778, "difficulty": "Medium", "__index_level_0__": 15455, "question": "You are given an integer array deck. There is a deck of cards where every card has a unique integer. The integer on the ith card is deck[i].\nYou can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.\nYou will do the following steps repeatedly until all cards are revealed:\nTake the top card of the deck, reveal it, and take it out of the deck.\nIf there are still cards in the deck then put the next top card of the deck at the bottom of the deck.\nIf there are still unrevealed cards, go back to step 1. Otherwise, stop.\nReturn an ordering of the deck that would reveal the cards in increasing order.\nNote that the first entry in the answer is considered to be the top of the deck.\n Example 1:\nInput: deck = [17,13,11,2,3,5,7]\nOutput: [2,13,3,11,5,17,7]\nExplanation: \nWe get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\nAfter reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\nWe reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\nWe reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\nWe reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\nWe reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\nWe reveal 11, and move 17 to the bottom. The deck is now [13,17].\nWe reveal 13, and move 17 to the bottom. The deck is now [17].\nWe reveal 17.\nSince all the cards revealed are in increasing order, the answer is correct.\nExample 2:\nInput: deck = [1,1000]\nOutput: [1,1000]\n Constraints:\n1 <= deck.length <= 1000\n1 <= deck[i] <= 106\nAll the values of deck are unique." }, { "post_href": "https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/1985423/Python-oror-4-line-93", "python_solutions": "class Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 or not root2:\n return not root1 and not root2\n if root1.val != root2.val: return False\n return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))", "slug": "flip-equivalent-binary-trees", "post_title": "Python || 4-line 93%", "user": "gulugulugulugulu", "upvotes": 2, "views": 69, "problem_title": "flip equivalent binary trees", "number": 951, "acceptance": 0.6679999999999999, "difficulty": "Medium", "__index_level_0__": 15461, "question": "For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.\nA binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.\nGiven the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.\n Example 1:\nInput: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]\nOutput: true\nExplanation: We flipped at nodes with values 1, 3, and 5.\nExample 2:\nInput: root1 = [], root2 = []\nOutput: true\nExample 3:\nInput: root1 = [], root2 = [1]\nOutput: false\n Constraints:\nThe number of nodes in each tree is in the range [0, 100].\nEach tree will have unique node values in the range [0, 99]." }, { "post_href": "https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1546345/Python3-union-find", "python_solutions": "class Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n m = max(nums)\n uf = UnionFind(m+1)\n for x in nums: \n for p in range(2, int(sqrt(x))+1): \n if x%p == 0: \n uf.union(x, p)\n uf.union(x, x//p)\n freq = Counter(uf.find(x) for x in nums)\n return max(freq.values())", "slug": "largest-component-size-by-common-factor", "post_title": "[Python3] union-find", "user": "ye15", "upvotes": 4, "views": 259, "problem_title": "largest component size by common factor", "number": 952, "acceptance": 0.4039999999999999, "difficulty": "Hard", "__index_level_0__": 15470, "question": "You are given an integer array of unique positive integers nums. Consider the following graph:\nThere are nums.length nodes, labeled nums[0] to nums[nums.length - 1],\nThere is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\nReturn the size of the largest connected component in the graph.\n Example 1:\nInput: nums = [4,6,15,35]\nOutput: 4\nExample 2:\nInput: nums = [20,50,9,63]\nOutput: 2\nExample 3:\nInput: nums = [2,3,6,7,4,12,21,39]\nOutput: 8\n Constraints:\n1 <= nums.length <= 2 * 104\n1 <= nums[i] <= 105\nAll the values of nums are unique." }, { "post_href": "https://leetcode.com/problems/verifying-an-alien-dictionary/discuss/1370816/Python3-fast-and-easy-to-understand-28-ms-faster-than-96.25", "python_solutions": "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n hm = {ch: i for i, ch in enumerate(order)}\n\n prev_repr = list(hm[ch] for ch in words[0])\n for i in range(1, len(words)):\n cur_repr = list(hm[ch] for ch in words[i])\n\n if cur_repr < prev_repr:\n return False\n\n prev_repr = cur_repr\n\n return True", "slug": "verifying-an-alien-dictionary", "post_title": "Python3, fast and easy to understand, 28 ms, faster than 96.25%", "user": "MihailP", "upvotes": 5, "views": 364, "problem_title": "verifying an alien dictionary", "number": 953, "acceptance": 0.527, "difficulty": "Easy", "__index_level_0__": 15473, "question": "In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.\nGiven a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.\n Example 1:\nInput: words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"\nOutput: true\nExplanation: As 'h' comes before 'l' in this language, then the sequence is sorted.\nExample 2:\nInput: words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"\nOutput: false\nExplanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.\nExample 3:\nInput: words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"\nOutput: false\nExplanation: The first three characters \"app\" match, and the second string is shorter (in size.) According to lexicographical rules \"apple\" > \"app\", because 'l' > '\u2205', where '\u2205' is defined as the blank character which is less than any other character (More info).\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 20\norder.length == 26\nAll characters in words[i] and order are English lowercase letters." }, { "post_href": "https://leetcode.com/problems/array-of-doubled-pairs/discuss/1840844/python-3-oror-O(nlogn)", "python_solutions": "class Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n count = collections.Counter(arr)\n for n in sorted(arr, key=abs):\n if count[n] == 0:\n continue\n if count[n * 2] == 0:\n return False\n count[n] -= 1\n count[n * 2] -= 1\n \n return True", "slug": "array-of-doubled-pairs", "post_title": "python 3 || O(nlogn)", "user": "dereky4", "upvotes": 1, "views": 81, "problem_title": "array of doubled pairs", "number": 954, "acceptance": 0.391, "difficulty": "Medium", "__index_level_0__": 15507, "question": "Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.\n Example 1:\nInput: arr = [3,1,3,6]\nOutput: false\nExample 2:\nInput: arr = [2,1,2,6]\nOutput: false\nExample 3:\nInput: arr = [4,-2,2,-4]\nOutput: true\nExplanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].\n Constraints:\n2 <= arr.length <= 3 * 104\narr.length is even.\n-105 <= arr[i] <= 105" }, { "post_href": "https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/844457/Python-3-or-Greedy-DP-(28-ms)-or-Explanation", "python_solutions": "class Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and current step rows are not in order, remove this column\n if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break \n\t\t\t\t# previous step, rows are not in order, but they are in order now\n elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True\n\t\t\t# if column wasn't removed, update the row order information\n else: in_order = tmp_in_order \n # not necessary, but speed things up\n if all(in_order): return ans \n return ans", "slug": "delete-columns-to-make-sorted-ii", "post_title": "Python 3 | Greedy, DP (28 ms) | Explanation", "user": "idontknoooo", "upvotes": 6, "views": 550, "problem_title": "delete columns to make sorted ii", "number": 955, "acceptance": 0.346, "difficulty": "Medium", "__index_level_0__": 15514, "question": "You are given an array of n strings strs, all of the same length.\nWe may choose any deletion indices, and we delete all the characters in those indices for each string.\nFor example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\nSuppose we chose a set of deletion indices answer such that after deletions, the final array has its elements in lexicographic order (i.e., strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]). Return the minimum possible value of answer.length.\n Example 1:\nInput: strs = [\"ca\",\"bb\",\"ac\"]\nOutput: 1\nExplanation: \nAfter deleting the first column, strs = [\"a\", \"b\", \"c\"].\nNow strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\nWe require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.\nExample 2:\nInput: strs = [\"xc\",\"yb\",\"za\"]\nOutput: 0\nExplanation: \nstrs is already in lexicographic order, so we do not need to delete anything.\nNote that the rows of strs are not necessarily in lexicographic order:\ni.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)\nExample 3:\nInput: strs = [\"zyx\",\"wvu\",\"tsr\"]\nOutput: 3\nExplanation: We have to delete every column.\n Constraints:\nn == strs.length\n1 <= n <= 100\n1 <= strs[i].length <= 100\nstrs[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/tallest-billboard/discuss/1561795/Python3-dp-and-binary-search", "python_solutions": "class Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n dp = {0: 0}\n for x in rods: \n for k, v in dp.copy().items(): \n dp[k+x] = max(dp.get(k+x, 0), v)\n if k >= x: dp[k-x] = max(dp.get(k-x, 0), v+x)\n else: dp[x-k] = max(dp.get(x-k, 0), v+k)\n return dp[0]", "slug": "tallest-billboard", "post_title": "[Python3] dp & binary search", "user": "ye15", "upvotes": 0, "views": 273, "problem_title": "tallest billboard", "number": 956, "acceptance": 0.3989999999999999, "difficulty": "Hard", "__index_level_0__": 15517, "question": "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.\nYou are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.\nReturn the largest possible height of your billboard installation. If you cannot support the billboard, return 0.\n Example 1:\nInput: rods = [1,2,3,6]\nOutput: 6\nExplanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\nExample 2:\nInput: rods = [1,2,3,4,5,6]\nOutput: 10\nExplanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\nExample 3:\nInput: rods = [1,2]\nOutput: 0\nExplanation: The billboard cannot be supported, so we return 0.\n Constraints:\n1 <= rods.length <= 20\n1 <= rods[i] <= 1000\nsum(rods[i]) <= 5000" }, { "post_href": "https://leetcode.com/problems/prison-cells-after-n-days/discuss/347500/Python3-Prison-Cells-After-N-days%3A-dictionary-to-store-pattern", "python_solutions": "class Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n def nextday(cells):\n next_day_cells = [0] *len(cells)\n for i in range(1,len(cells)-1):\n if cells[i-1] == cells[i+1]: \n next_day_cells[i] = 1\n else:\n next_day_cells[i] = 0\n return next_day_cells\n \n seen = {}\n while N > 0:\n c = tuple(cells)\n if c in seen:\n N %= seen[c] - N\n seen[c] = N\n\n if N >= 1:\n N -= 1\n cells = nextday(cells)\n\n return cells", "slug": "prison-cells-after-n-days", "post_title": "[Python3] Prison Cells After N days: dictionary to store pattern", "user": "zhanweiting", "upvotes": 33, "views": 3800, "problem_title": "prison cells after n days", "number": 957, "acceptance": 0.391, "difficulty": "Medium", "__index_level_0__": 15519, "question": "There are 8 prison cells in a row and each cell is either occupied or vacant.\nEach day, whether the cell is occupied or vacant changes according to the following rules:\nIf a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.\nOtherwise, it becomes vacant.\nNote that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.\nYou are given an integer array cells where cells[i] == 1 if the ith cell is occupied and cells[i] == 0 if the ith cell is vacant, and you are given an integer n.\nReturn the state of the prison after n days (i.e., n such changes described above).\n Example 1:\nInput: cells = [0,1,0,1,1,0,0,1], n = 7\nOutput: [0,0,1,1,0,0,0,0]\nExplanation: The following table summarizes the state of the prison on each day:\nDay 0: [0, 1, 0, 1, 1, 0, 0, 1]\nDay 1: [0, 1, 1, 0, 0, 0, 0, 0]\nDay 2: [0, 0, 0, 0, 1, 1, 1, 0]\nDay 3: [0, 1, 1, 0, 0, 1, 0, 0]\nDay 4: [0, 0, 0, 0, 0, 1, 0, 0]\nDay 5: [0, 1, 1, 1, 0, 1, 0, 0]\nDay 6: [0, 0, 1, 0, 1, 1, 0, 0]\nDay 7: [0, 0, 1, 1, 0, 0, 0, 0]\nExample 2:\nInput: cells = [1,0,0,1,0,0,1,0], n = 1000000000\nOutput: [0,0,1,1,1,1,1,0]\n Constraints:\ncells.length == 8\ncells[i] is either 0 or 1.\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/check-completeness-of-a-binary-tree/discuss/2287813/Python3-oror-bfs-8-lines-w-explanation-oror-TM%3A-9797", "python_solutions": "class Solution:\n def isCompleteTree(self, root: TreeNode) -> bool:\n # The criteria for an n-level complete tree:\n #\n # \u2022 The first n-1 rows have no null nodes.\n #\n # \u2022 The nth row has no non-null nodes to the right of the left-most null\n # node encountered (if it exists).\n #\n # The plan is to bfs the tree, left to right, level by level. We mark the\n # instance of the first null popped from the queue and then ensure the remaining\n # queue is only null nodes. If so, both criteria are satisfied and True is\n # returned. If not, False is returned.\n\n queue = deque([root]) # <-- initialize the queue\n\n while queue[0]: # <-- if and while top queue node is not null, pop \n node = queue.popleft() # it and then push its left child and right \n queue.extend([node.left, node.right]) # child onto the queue.\n\n while queue and not queue[0]: # <-- if and while top queue node is null, pop it. \n queue.popleft() # \n\n if queue: return False # <-- If the queue is not empty, it must be non-null, so \n return True # return False; if the queue is empty, return True.", "slug": "check-completeness-of-a-binary-tree", "post_title": "Python3 || bfs, 8 lines, w/ explanation || T/M: 97%/97%", "user": "warrenruud", "upvotes": 3, "views": 111, "problem_title": "check completeness of a binary tree", "number": 958, "acceptance": 0.5379999999999999, "difficulty": "Medium", "__index_level_0__": 15531, "question": "Given the root of a binary tree, determine if it is a complete binary tree.\nIn a complete binary tree, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.\n Example 1:\nInput: root = [1,2,3,4,5,6]\nOutput: true\nExplanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.\nExample 2:\nInput: root = [1,2,3,4,5,null,7]\nOutput: false\nExplanation: The node with value 7 isn't as far left as possible.\n Constraints:\nThe number of nodes in the tree is in the range [1, 100].\n1 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/regions-cut-by-slashes/discuss/205674/DFS-on-upscaled-grid", "python_solutions": "class Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n def dfs(i: int, j: int) -> int:\n if min(i, j) < 0 or max(i, j) >= len(g) or g[i][j] != 0:\n return 0\n g[i][j] = 1\n return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1)\n n, regions = len(grid), 0\n g = [[0] * n * 3 for i in range(n * 3)]\n for i in range(n):\n for j in range(n):\n if grid[i][j] == '/':\n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1\n elif grid[i][j] == '\\\\':\n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1\n for i in range(n * 3):\n for j in range(n * 3):\n regions += 1 if dfs(i, j) > 0 else 0\n return regions", "slug": "regions-cut-by-slashes", "post_title": "DFS on upscaled grid", "user": "votrubac", "upvotes": 733, "views": 23400, "problem_title": "regions cut by slashes", "number": 959, "acceptance": 0.691, "difficulty": "Medium", "__index_level_0__": 15536, "question": "An n x n grid is composed of 1 x 1 squares where each 1 x 1 square consists of a '/', '\\', or blank space ' '. These characters divide the square into contiguous regions.\nGiven the grid grid represented as a string array, return the number of regions.\nNote that backslash characters are escaped, so a '\\' is represented as '\\\\'.\n Example 1:\nInput: grid = [\" /\",\"/ \"]\nOutput: 2\nExample 2:\nInput: grid = [\" /\",\" \"]\nOutput: 1\nExample 3:\nInput: grid = [\"/\\\\\",\"\\\\/\"]\nOutput: 5\nExplanation: Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.\n Constraints:\nn == grid.length == grid[i].length\n1 <= n <= 30\ngrid[i][j] is either '/', '\\', or ' '." }, { "post_href": "https://leetcode.com/problems/delete-columns-to-make-sorted-iii/discuss/1258211/Python3-top-down-dp", "python_solutions": "class Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0]) # dimensions\n \n @cache \n def fn(k, prev):\n \"\"\"Return min deleted columns to make sorted.\"\"\"\n if k == n: return 0 \n ans = 1 + fn(k+1, prev) # delete kth column\n if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(m)): \n ans = min(ans, fn(k+1, k)) # retain kth column\n return ans \n \n return fn(0, -1)", "slug": "delete-columns-to-make-sorted-iii", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 139, "problem_title": "delete columns to make sorted iii", "number": 960, "acceptance": 0.5710000000000001, "difficulty": "Hard", "__index_level_0__": 15542, "question": "You are given an array of n strings strs, all of the same length.\nWe may choose any deletion indices, and we delete all the characters in those indices for each string.\nFor example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\nSuppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.\n Example 1:\nInput: strs = [\"babca\",\"bbazb\"]\nOutput: 3\nExplanation: After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\nBoth these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\nNote that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.\nExample 2:\nInput: strs = [\"edcba\"]\nOutput: 4\nExplanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.\nExample 3:\nInput: strs = [\"ghi\",\"def\",\"abc\"]\nOutput: 0\nExplanation: All rows are already lexicographically sorted.\n Constraints:\nn == strs.length\n1 <= n <= 100\n1 <= strs[i].length <= 100\nstrs[i] consists of lowercase English letters.\n " }, { "post_href": "https://leetcode.com/problems/n-repeated-element-in-size-2n-array/discuss/1337509/PYTHON-3-%3A-SUPER-EASY-99.52-FASTER", "python_solutions": "class Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n list1 = []\n for i in nums :\n if i in list1 :\n return i\n else :\n list1.append(i)", "slug": "n-repeated-element-in-size-2n-array", "post_title": "PYTHON 3 : SUPER EASY 99.52% FASTER", "user": "rohitkhairnar", "upvotes": 11, "views": 510, "problem_title": "n repeated element in size 2n array", "number": 961, "acceptance": 0.759, "difficulty": "Easy", "__index_level_0__": 15543, "question": "You are given an integer array nums with the following properties:\nnums.length == 2 * n.\nnums contains n + 1 unique elements.\nExactly one element of nums is repeated n times.\nReturn the element that is repeated n times.\n Example 1:\nInput: nums = [1,2,3,3]\nOutput: 3\nExample 2:\nInput: nums = [2,1,2,5,3,2]\nOutput: 2\nExample 3:\nInput: nums = [5,1,5,2,5,3,5,4]\nOutput: 5\n Constraints:\n2 <= n <= 5000\nnums.length == 2 * n\n0 <= nums[i] <= 104\nnums contains n + 1 unique elements and one of them is repeated exactly n times." }, { "post_href": "https://leetcode.com/problems/maximum-width-ramp/discuss/977244/Python3-binary-search-O(NlogN)-and-stack-O(N)", "python_solutions": "class Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n ans = 0\n stack = []\n for i in range(len(A)): \n if not stack or A[stack[-1]] > A[i]: stack.append(i)\n else: \n lo, hi = 0, len(stack)\n while lo < hi: \n mid = lo + hi >> 1\n if A[stack[mid]] <= A[i]: hi = mid\n else: lo = mid + 1\n ans = max(ans, i - stack[lo])\n return ans", "slug": "maximum-width-ramp", "post_title": "[Python3] binary search O(NlogN) & stack O(N)", "user": "ye15", "upvotes": 8, "views": 299, "problem_title": "maximum width ramp", "number": 962, "acceptance": 0.49, "difficulty": "Medium", "__index_level_0__": 15580, "question": "A ramp in an integer array nums is a pair (i, j) for which i < j and nums[i] <= nums[j]. The width of such a ramp is j - i.\nGiven an integer array nums, return the maximum width of a ramp in nums. If there is no ramp in nums, return 0.\n Example 1:\nInput: nums = [6,0,8,2,1,5]\nOutput: 4\nExplanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.\nExample 2:\nInput: nums = [9,8,1,0,1,9,4,0,4,1]\nOutput: 7\nExplanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.\n Constraints:\n2 <= nums.length <= 5 * 104\n0 <= nums[i] <= 5 * 104" }, { "post_href": "https://leetcode.com/problems/minimum-area-rectangle-ii/discuss/980956/Python3-center-point-O(N2)", "python_solutions": "class Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n ans = inf\n seen = {}\n for i, (x0, y0) in enumerate(points):\n for x1, y1 in points[i+1:]:\n cx = (x0 + x1)/2\n cy = (y0 + y1)/2\n d2 = (x0 - x1)**2 + (y0 - y1)**2\n for xx, yy in seen.get((cx, cy, d2), []): \n area = sqrt(((x0-xx)**2 + (y0-yy)**2) * ((x1-xx)**2 + (y1-yy)**2))\n ans = min(ans, area)\n seen.setdefault((cx, cy, d2), []).append((x0, y0))\n return ans if ans < inf else 0", "slug": "minimum-area-rectangle-ii", "post_title": "[Python3] center point O(N^2)", "user": "ye15", "upvotes": 28, "views": 1200, "problem_title": "minimum area rectangle ii", "number": 963, "acceptance": 0.547, "difficulty": "Medium", "__index_level_0__": 15584, "question": "You are given an array of points in the X-Y plane points where points[i] = [xi, yi].\nReturn the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return 0.\nAnswers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: points = [[1,2],[2,1],[1,0],[0,1]]\nOutput: 2.00000\nExplanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.\nExample 2:\nInput: points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\nOutput: 1.00000\nExplanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.\nExample 3:\nInput: points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\nOutput: 0\nExplanation: There is no possible rectangle to form from these points.\n Constraints:\n1 <= points.length <= 50\npoints[i].length == 2\n0 <= xi, yi <= 4 * 104\nAll the given points are unique." }, { "post_href": "https://leetcode.com/problems/least-operators-to-express-number/discuss/1367268/Python3-top-down-dp", "python_solutions": "class Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n \n @cache\n def fn(val): \n \"\"\"Return min ops to express val.\"\"\"\n if val < x: return min(2*val-1, 2*(x-val))\n k = int(log(val)//log(x))\n ans = k + fn(val - x**k)\n if x**(k+1) < 2*val: \n ans = min(ans, k + 1 + fn(x**(k+1) - val))\n return ans \n \n return fn(target)", "slug": "least-operators-to-express-number", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 4, "views": 277, "problem_title": "least operators to express number", "number": 964, "acceptance": 0.48, "difficulty": "Hard", "__index_level_0__": 15586, "question": "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.\nWhen writing such an expression, we adhere to the following conventions:\nThe division operator (/) returns rational numbers.\nThere are no parentheses placed anywhere.\nWe use the usual order of operations: multiplication and division happen before addition and subtraction.\nIt 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.\nWe would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.\n Example 1:\nInput: x = 3, target = 19\nOutput: 5\nExplanation: 3 * 3 + 3 * 3 + 3 / 3.\nThe expression contains 5 operations.\nExample 2:\nInput: x = 5, target = 501\nOutput: 8\nExplanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\nThe expression contains 8 operations.\nExample 3:\nInput: x = 100, target = 100000000\nOutput: 3\nExplanation: 100 * 100 * 100 * 100.\nThe expression contains 3 operations.\n Constraints:\n2 <= x <= 100\n1 <= target <= 2 * 108" }, { "post_href": "https://leetcode.com/problems/univalued-binary-tree/discuss/1569046/python-dfs-recursion-faster-than-97", "python_solutions": "class Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n val = root.val\n \n def helper(root):\n return root is None or (root.val == val and helper(root.left) and helper(root.right))\n \n return helper(root)", "slug": "univalued-binary-tree", "post_title": "python dfs recursion faster than 97%", "user": "dereky4", "upvotes": 2, "views": 89, "problem_title": "univalued binary tree", "number": 965, "acceptance": 0.693, "difficulty": "Easy", "__index_level_0__": 15588, "question": "A binary tree is uni-valued if every node in the tree has the same value.\nGiven the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.\n Example 1:\nInput: root = [1,1,1,1,1,null,1]\nOutput: true\nExample 2:\nInput: root = [2,2,2,5,2]\nOutput: false\n Constraints:\nThe number of nodes in the tree is in the range [1, 100].\n0 <= Node.val < 100" }, { "post_href": "https://leetcode.com/problems/vowel-spellchecker/discuss/1121773/Python-One-Case-At-A-Time", "python_solutions": "class Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n \n # Convert words and vowels to sets for O(1) lookup times\n words = set(wordlist)\n vowels = set('aeiouAEIOU')\n \n # Create two maps. \n # One for case insensitive word to all words that match \"key\" -> [\"Key\", \"kEy\", \"KEY\"]\n # The other for vowel insensitive words \"k*t*\" -> [\"Kite\", \"kato\", \"KUTA\"]\n case_insensitive = collections.defaultdict(list) \n vowel_insensitive = collections.defaultdict(list)\n for word in wordlist:\n case_insensitive[word.lower()].append(word)\n key = ''.join(char.lower() if char not in vowels else '*' for char in word)\n vowel_insensitive[key].append(word)\n\n res = []\n for word in queries:\n\n # Case 1: When query exactly matches a word\n if word in words:\n res.append(word)\n continue\n\n # Case 2: When query matches a word up to capitalization\n low = word.lower()\n if low in case_insensitive:\n res.append(case_insensitive[low][0])\n continue\n\n # Case 3: When query matches a word up to vowel errors\n key = ''.join(char.lower() if char not in vowels else '*' for char in word)\n if key in vowel_insensitive:\n res.append(vowel_insensitive[key][0])\n continue\n\n res.append('')\n\n return res", "slug": "vowel-spellchecker", "post_title": "[Python] One Case At A Time", "user": "rowe1227", "upvotes": 5, "views": 288, "problem_title": "vowel spellchecker", "number": 966, "acceptance": 0.514, "difficulty": "Medium", "__index_level_0__": 15608, "question": "Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.\nFor a given query word, the spell checker handles two categories of spelling mistakes:\nCapitalization: If the query matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the case in the wordlist.\nExample: wordlist = [\"yellow\"], query = \"YellOw\": correct = \"yellow\"\nExample: wordlist = [\"Yellow\"], query = \"yellow\": correct = \"Yellow\"\nExample: wordlist = [\"yellow\"], query = \"yellow\": correct = \"yellow\"\nVowel Errors: If after replacing the vowels ('a', 'e', 'i', 'o', 'u') of the query word with any vowel individually, it matches a word in the wordlist (case-insensitive), then the query word is returned with the same case as the match in the wordlist.\nExample: wordlist = [\"YellOw\"], query = \"yollow\": correct = \"YellOw\"\nExample: wordlist = [\"YellOw\"], query = \"yeellow\": correct = \"\" (no match)\nExample: wordlist = [\"YellOw\"], query = \"yllw\": correct = \"\" (no match)\nIn addition, the spell checker operates under the following precedence rules:\nWhen the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.\nWhen the query matches a word up to capitlization, you should return the first such match in the wordlist.\nWhen the query matches a word up to vowel errors, you should return the first such match in the wordlist.\nIf the query has no matches in the wordlist, you should return the empty string.\nGiven some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].\n Example 1:\nInput: wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\nOutput: [\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]\nExample 2:\nInput: wordlist = [\"yellow\"], queries = [\"YellOw\"]\nOutput: [\"yellow\"]\n Constraints:\n1 <= wordlist.length, queries.length <= 5000\n1 <= wordlist[i].length, queries[i].length <= 7\nwordlist[i] and queries[i] consist only of only English letters." }, { "post_href": "https://leetcode.com/problems/numbers-with-same-consecutive-differences/discuss/2521416/44ms-PYTHON-91-Faster-93-Memory-Efficient-Solution-MULTIPLE-APPROACHES", "python_solutions": "class Solution:\n\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\tgraph = defaultdict(list)\n\t\tfor i in range(0, 10):\n\t\t\tif i-k >= 0:\n\t\t\t\tgraph[i].append(i-k)\n\t\t\tif i +k < 10:\n\t\t\t\tgraph[i].append(i+k)\n\t\tstart = [i for i in graph if i!= 0]\n\t\tfor j in range(n-1):\n\t\t\tnew = set()\n\t\t\tfor i in start:\n\t\t\t\tlast = i%10\n\t\t\t\tfor k in graph[last]:\n\t\t\t\t\tnew.add(i*10 + k)\n\t\t\tstart = new\n\t\treturn list(start)", "slug": "numbers-with-same-consecutive-differences", "post_title": "\ud83d\udd2544ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES \ud83d\udd25", "user": "anuvabtest", "upvotes": 5, "views": 421, "problem_title": "numbers with same consecutive differences", "number": 967, "acceptance": 0.5710000000000001, "difficulty": "Medium", "__index_level_0__": 15618, "question": "Given two integers n and k, return an array of all the integers of length n where the difference between every two consecutive digits is k. You may return the answer in any order.\nNote that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.\n Example 1:\nInput: n = 3, k = 7\nOutput: [181,292,707,818,929]\nExplanation: Note that 070 is not a valid number, because it has leading zeroes.\nExample 2:\nInput: n = 2, k = 1\nOutput: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]\n Constraints:\n2 <= n <= 9\n0 <= k <= 9" }, { "post_href": "https://leetcode.com/problems/binary-tree-cameras/discuss/2160386/Python-Making-a-Hard-Problem-Easy!-Postorder-Traversal-with-Explanation", "python_solutions": "class Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n # set the value of camera nodes to 1\n # set the value of monitored parent nodes to 2\n def dfs(node: Optional[TreeNode]) -> int:\n if not node:\n return 0\n res = dfs(node.left)+dfs(node.right)\n # find out if current node is a root node / next node in line to be monitored\n curr = min(node.left.val if node.left else float('inf'), node.right.val if node.right else float('inf'))\n if curr == 0:\n # at least one child node requires monitoring, this node must have a camera\n node.val = 1\n res += 1\n elif curr == 1:\n # at least one child node is a camera, this node is already monitored\n node.val = 2\n # if curr == float('inf'), the current node is a leaf node; let the parent node monitor this node\n # if curr == 2, all child nodes are being monitored; treat the current node as a leaf node\n return res\n # ensure that root node is monitored, otherwise, add a camera onto root node\n return dfs(root)+(root.val == 0)", "slug": "binary-tree-cameras", "post_title": "[Python] Making a Hard Problem Easy! Postorder Traversal with Explanation", "user": "zayne-siew", "upvotes": 50, "views": 2100, "problem_title": "binary tree cameras", "number": 968, "acceptance": 0.4679999999999999, "difficulty": "Hard", "__index_level_0__": 15660, "question": "You are given the root of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.\nReturn the minimum number of cameras needed to monitor all nodes of the tree.\n Example 1:\nInput: root = [0,0,null,0,0]\nOutput: 1\nExplanation: One camera is enough to monitor all nodes if placed as shown.\nExample 2:\nInput: root = [0,0,null,0,null,0,null,null,0]\nOutput: 2\nExplanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.\n Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\nNode.val == 0" }, { "post_href": "https://leetcode.com/problems/pancake-sorting/discuss/2844744/Kind-of-a-simulation-solution", "python_solutions": "class Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n\n if arr == sorted(arr):\n return []\n \n flips = []\n end = len(arr) - 1\n \n # find the max flip all the numbers from the first position to the max position \n # ==> from 0 to max_position = k\n # ==> if max not at the end : flip again until the max is at the end of the array \n # ==> from 0 to max_position = k\n # end = end - 1\n # repeat previous steps\n\n while end > 0:\n \n max_num = max(arr[:end+1])\n index_num = arr.index(max_num)\n \n if index_num != end:\n k = index_num + 1\n arr = arr[0:k][::-1] + arr[k:]\n flips.append(k)\n arr = arr[:end+1][::-1] + arr[end+1:]\n flips.append(end+1)\n else:\n k = end\n arr = arr[0:k][::-1] + arr[k:]\n flips.append(k)\n \n end -= 1\n\n return flips", "slug": "pancake-sorting", "post_title": "Kind of a simulation solution", "user": "khaled_achech", "upvotes": 0, "views": 1, "problem_title": "pancake sorting", "number": 969, "acceptance": 0.7, "difficulty": "Medium", "__index_level_0__": 15673, "question": "Given an array of integers arr, sort the array by performing a series of pancake flips.\nIn one pancake flip we do the following steps:\nChoose an integer k where 1 <= k <= arr.length.\nReverse the sub-array arr[0...k-1] (0-indexed).\nFor example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.\nReturn an array of the k-values corresponding to a sequence of pancake flips that sort arr. Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.\n Example 1:\nInput: arr = [3,2,4,1]\nOutput: [4,2,4,3]\nExplanation: \nWe perform 4 pancake flips, with k values 4, 2, 4, and 3.\nStarting state: arr = [3, 2, 4, 1]\nAfter 1st flip (k = 4): arr = [1, 4, 2, 3]\nAfter 2nd flip (k = 2): arr = [4, 1, 2, 3]\nAfter 3rd flip (k = 4): arr = [3, 2, 1, 4]\nAfter 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.\nExample 2:\nInput: arr = [1,2,3]\nOutput: []\nExplanation: The input is already sorted, so there is no need to flip anything.\nNote that other answers, such as [3, 3], would also be accepted.\n Constraints:\n1 <= arr.length <= 100\n1 <= arr[i] <= arr.length\nAll integers in arr are unique (i.e. arr is a permutation of the integers from 1 to arr.length)." }, { "post_href": "https://leetcode.com/problems/powerful-integers/discuss/1184254/Python3-brute-force", "python_solutions": "class Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n bx = int(log(bound)/log(x)) if x > 1 else 0\n by = int(log(bound)/log(y)) if y > 1 else 0 \n \n ans = set()\n for i in range(bx+1): \n for j in range(by+1):\n if x**i + y**j <= bound: \n ans.add(x**i + y**j)\n return ans", "slug": "powerful-integers", "post_title": "[Python3] brute force", "user": "ye15", "upvotes": 2, "views": 45, "problem_title": "powerful integers", "number": 970, "acceptance": 0.436, "difficulty": "Medium", "__index_level_0__": 15684, "question": "Given three integers x, y, and bound, return a list of all the powerful integers that have a value less than or equal to bound.\nAn integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.\nYou may return the answer in any order. In your answer, each value should occur at most once.\n Example 1:\nInput: x = 2, y = 3, bound = 10\nOutput: [2,3,4,5,7,9,10]\nExplanation:\n2 = 20 + 30\n3 = 21 + 30\n4 = 20 + 31\n5 = 21 + 31\n7 = 22 + 31\n9 = 23 + 30\n10 = 20 + 32\nExample 2:\nInput: x = 3, y = 5, bound = 15\nOutput: [2,4,6,8,10,14]\n Constraints:\n1 <= x, y <= 100\n0 <= bound <= 106" }, { "post_href": "https://leetcode.com/problems/flip-binary-tree-to-match-preorder-traversal/discuss/1343381/Elegant-Python-Iterative-and-Recursive-Preorder-Traversals", "python_solutions": "class Solution:\n def __init__(self):\n self.flipped_nodes = []\n self.index = 0\n \n def flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:\n queue = deque([root])\n while queue:\n node = queue.pop()\n if not node: continue\n if node.val != voyage[self.index]: return [-1]\n self.index += 1\n if node.left and node.left.val != voyage[self.index]:\n self.flipped_nodes.append(node.val)\n node.left, node.right = node.right, node.left\n queue.append(node.right), queue.append(node.left)\n return self.flipped_nodes", "slug": "flip-binary-tree-to-match-preorder-traversal", "post_title": "Elegant Python Iterative & Recursive Preorder Traversals", "user": "soma28", "upvotes": 0, "views": 75, "problem_title": "flip binary tree to match preorder traversal", "number": 971, "acceptance": 0.499, "difficulty": "Medium", "__index_level_0__": 15696, "question": "You are given the root of a binary tree with n nodes, where each node is uniquely assigned a value from 1 to n. You are also given a sequence of n values voyage, which is the desired pre-order traversal of the binary tree.\nAny node in the binary tree can be flipped by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:\nFlip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.\nReturn a list of the values of all flipped nodes. You may return the answer in any order. If it is impossible to flip the nodes in the tree to make the pre-order traversal match voyage, return the list [-1].\n Example 1:\nInput: root = [1,2], voyage = [2,1]\nOutput: [-1]\nExplanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.\nExample 2:\nInput: root = [1,2,3], voyage = [1,3,2]\nOutput: [1]\nExplanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.\nExample 3:\nInput: root = [1,2,3], voyage = [1,2,3]\nOutput: []\nExplanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.\n Constraints:\nThe number of nodes in the tree is n.\nn == voyage.length\n1 <= n <= 100\n1 <= Node.val, voyage[i] <= n\nAll the values in the tree are unique.\nAll the values in voyage are unique." }, { "post_href": "https://leetcode.com/problems/equal-rational-numbers/discuss/405505/Python-3-(beats-~99)-(six-lines)", "python_solutions": "class Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n L, A = [len(S), len(T)], [S,T]\n for i,p in enumerate([S,T]):\n if '(' in p:\n I = p.index('(')\n A[i] = p[0:I] + 7*p[I+1:L[i]-1]\n return abs(float(A[0])-float(A[1])) < 1E-7\n\t\t\n\t\t\n- Junaid Mansuri", "slug": "equal-rational-numbers", "post_title": "Python 3 (beats ~99%) (six lines)", "user": "junaidmansuri", "upvotes": 1, "views": 119, "problem_title": "equal rational numbers", "number": 972, "acceptance": 0.43, "difficulty": "Hard", "__index_level_0__": 15702, "question": "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.\nA rational number can be represented using up to three parts: , , and a . The number will be represented in one of the following three ways:\n\nFor example, 12, 0, and 123.\n<.>\nFor example, 0.5, 1., 2.12, and 123.0001.\n<.><(><)>\nFor example, 0.1(6), 1.(9), 123.00(1212).\nThe repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).\n Example 1:\nInput: s = \"0.(52)\", t = \"0.5(25)\"\nOutput: true\nExplanation: Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.\nExample 2:\nInput: s = \"0.1666(6)\", t = \"0.166(66)\"\nOutput: true\nExample 3:\nInput: s = \"0.9(9)\", t = \"1.\"\nOutput: true\nExplanation: \"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n\"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".\n Constraints:\nEach part consists only of digits.\nThe does not have leading zeros (except for the zero itself).\n1 <= .length <= 4\n0 <= .length <= 4\n1 <= .length <= 4" }, { "post_href": "https://leetcode.com/problems/k-closest-points-to-origin/discuss/1647325/Python3-ONE-LINER-Explained", "python_solutions": "class Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n return sorted(points, key = lambda p: p[0]**2 + p[1]**2)[0:k]", "slug": "k-closest-points-to-origin", "post_title": "\u2714\ufe0f [Python3] ONE-LINER, Explained", "user": "artod", "upvotes": 9, "views": 2000, "problem_title": "k closest points to origin", "number": 973, "acceptance": 0.6579999999999999, "difficulty": "Medium", "__index_level_0__": 15707, "question": "Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).\nThe distance between two points on the X-Y plane is the Euclidean distance (i.e., \u221a(x1 - x2)2 + (y1 - y2)2).\nYou may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).\n Example 1:\nInput: points = [[1,3],[-2,2]], k = 1\nOutput: [[-2,2]]\nExplanation:\nThe distance between (1, 3) and the origin is sqrt(10).\nThe distance between (-2, 2) and the origin is sqrt(8).\nSince sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\nWe only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].\nExample 2:\nInput: points = [[3,3],[5,-1],[-2,4]], k = 2\nOutput: [[3,3],[-2,4]]\nExplanation: The answer [[-2,4],[3,3]] would also be accepted.\n Constraints:\n1 <= k <= points.length <= 104\n-104 <= xi, yi <= 104" }, { "post_href": "https://leetcode.com/problems/subarray-sums-divisible-by-k/discuss/1060120/Python3-O(N)-HashMap-and-Prefix-Sum", "python_solutions": "class Solution:\n def subarraysDivByK(self, A: List[int], k: int) -> int:\n dic = collections.defaultdict(int)\n dic[0] = 1\n ans = 0\n presum = 0\n for num in A:\n presum += num\n ans += dic[presum%k]\n dic[presum%k] += 1\n return ans\n\t```", "slug": "subarray-sums-divisible-by-k", "post_title": "Python3 O(N) HashMap and Prefix Sum", "user": "coffee90", "upvotes": 9, "views": 590, "problem_title": "subarray sums divisible by k", "number": 974, "acceptance": 0.536, "difficulty": "Medium", "__index_level_0__": 15747, "question": "Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.\nA subarray is a contiguous part of an array.\n Example 1:\nInput: nums = [4,5,0,-2,-3,1], k = 5\nOutput: 7\nExplanation: There are 7 subarrays with a sum divisible by k = 5:\n[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\nExample 2:\nInput: nums = [5], k = 9\nOutput: 0\n Constraints:\n1 <= nums.length <= 3 * 104\n-104 <= nums[i] <= 104\n2 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/odd-even-jump/discuss/1293059/Python-O(nlogn)-bottom-up-DP-easy-to-understand-260ms", "python_solutions": "class Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n \n\t\t# find next index of current index that is the least larger/smaller\n def getNextIndex(sortedIdx):\n stack = []\n result = [None] * len(sortedIdx)\n \n for i in sortedIdx:\n while stack and i > stack[-1]:\n result[stack.pop()] = i\n stack.append(i)\n return result\n \n sortedIdx = sorted(range(len(A)), key= lambda x: A[x])\n oddIndexes = getNextIndex(sortedIdx)\n sortedIdx.sort(key=lambda x: -A[x])\n evenIndexes = getNextIndex(sortedIdx)\n \n\t\t# [odd, even], the 0th jump is even\n dp = [[0,1] for _ in range(len(A))]\n \n for i in range(len(A)):\n if oddIndexes[i] is not None:\n dp[oddIndexes[i]][0] += dp[i][1]\n if evenIndexes[i] is not None:\n dp[evenIndexes[i]][1] += dp[i][0]\n\t\t\t\t\n return dp[-1][0] + dp[-1][1]", "slug": "odd-even-jump", "post_title": "Python O(nlogn) bottom-up DP easy to understand 260ms", "user": "ScoutBoi", "upvotes": 9, "views": 966, "problem_title": "odd even jump", "number": 975, "acceptance": 0.389, "difficulty": "Hard", "__index_level_0__": 15767, "question": "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.\nYou may jump forward from index i to index j (with i < j) in the following way:\nDuring 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.\nDuring 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.\nIt may be the case that for some index i, there are no legal jumps.\nA starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).\nReturn the number of good starting indices.\n Example 1:\nInput: arr = [10,13,12,14,15]\nOutput: 2\nExplanation: \nFrom starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\nFrom starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\nFrom starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\nFrom starting index i = 4, we have reached the end already.\nIn total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\njumps.\nExample 2:\nInput: arr = [2,3,1,1,4]\nOutput: 3\nExplanation: \nFrom starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\nDuring our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\nDuring our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\nDuring our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\nWe can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\nIn a similar manner, we can deduce that:\nFrom starting index i = 1, we jump to i = 4, so we reach the end.\nFrom starting index i = 2, we jump to i = 3, and then we can't jump anymore.\nFrom starting index i = 3, we jump to i = 4, so we reach the end.\nFrom starting index i = 4, we are already at the end.\nIn total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\nnumber of jumps.\nExample 3:\nInput: arr = [5,1,3,4,2]\nOutput: 3\nExplanation: We can reach the end from starting indices 1, 2, and 4.\n Constraints:\n1 <= arr.length <= 2 * 104\n0 <= arr[i] < 105" }, { "post_href": "https://leetcode.com/problems/largest-perimeter-triangle/discuss/915905/Python-3-98-better-explained-with-simple-logic", "python_solutions": "class Solution:\n def largestPerimeter(self, A: List[int]) -> int:\n A.sort(reverse = True)\n for i in range(3,len(A)+1):\n if(A[i-3] < A[i-2] + A[i-1]):\n return sum(A[i-3:i])\n return 0", "slug": "largest-perimeter-triangle", "post_title": "Python 3, 98% better, explained with simple logic", "user": "apurva_101", "upvotes": 14, "views": 2300, "problem_title": "largest perimeter triangle", "number": 976, "acceptance": 0.544, "difficulty": "Easy", "__index_level_0__": 15769, "question": "Given an integer array nums, return the largest perimeter of a triangle with a non-zero area, formed from three of these lengths. If it is impossible to form any triangle of a non-zero area, return 0.\n Example 1:\nInput: nums = [2,1,2]\nOutput: 5\nExplanation: You can form a triangle with three side lengths: 1, 2, and 2.\nExample 2:\nInput: nums = [1,2,1,10]\nOutput: 0\nExplanation: \nYou cannot use the side lengths 1, 1, and 2 to form a triangle.\nYou cannot use the side lengths 1, 1, and 10 to form a triangle.\nYou cannot use the side lengths 1, 2, and 10 to form a triangle.\nAs we cannot use any three side lengths to form a triangle of non-zero area, we return 0.\n Constraints:\n3 <= nums.length <= 104\n1 <= nums[i] <= 106" }, { "post_href": "https://leetcode.com/problems/squares-of-a-sorted-array/discuss/310865/Python%3A-A-comparison-of-lots-of-approaches!-Sorting-two-pointers-deque-iterator-generator", "python_solutions": "class Solution:\n def sortedSquares(self, A: List[int]) -> List[int]:\n return_array = [0] * len(A)\n write_pointer = len(A) - 1\n left_read_pointer = 0\n right_read_pointer = len(A) - 1\n left_square = A[left_read_pointer] ** 2\n right_square = A[right_read_pointer] ** 2\n while write_pointer >= 0:\n if left_square > right_square:\n return_array[write_pointer] = left_square\n left_read_pointer += 1\n left_square = A[left_read_pointer] ** 2\n else:\n return_array[write_pointer] = right_square\n right_read_pointer -= 1\n right_square = A[right_read_pointer] ** 2\n write_pointer -= 1\n return return_array", "slug": "squares-of-a-sorted-array", "post_title": "Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator]", "user": "Hai_dee", "upvotes": 386, "views": 20500, "problem_title": "squares of a sorted array", "number": 977, "acceptance": 0.7190000000000001, "difficulty": "Easy", "__index_level_0__": 15822, "question": "Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.\n Example 1:\nInput: nums = [-4,-1,0,3,10]\nOutput: [0,1,9,16,100]\nExplanation: After squaring, the array becomes [16,1,0,9,100].\nAfter sorting, it becomes [0,1,9,16,100].\nExample 2:\nInput: nums = [-7,-3,2,3,11]\nOutput: [4,9,9,49,121]\n Constraints:\n1 <= nums.length <= 104\n-104 <= nums[i] <= 104\nnums is sorted in non-decreasing order.\n Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?" }, { "post_href": "https://leetcode.com/problems/longest-turbulent-subarray/discuss/1464950/Python3-Longest-Turbulent-Subarray-O(n)-(one-pass)", "python_solutions": "class Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n cur, mx, t = 1, 1, None\n for i in range(1, len(arr)):\n # Start of subarray\n if t == None:\n if arr[i] != arr[i-1]: \n cur = 2\n t = arr[i] > arr[i-1]\n # Valid element in subarray, continue cur subarray\n elif (t and arr[i] < arr[i-1]) or (not t and arr[i] > arr[i-1]):\n cur += 1; t = not t\n # Invalid element in subarray, start new subarray\n else:\n if arr[i] == arr[i-1]: t = None\n mx = max(mx, cur)\n cur = 2\n \n return max(mx, cur)", "slug": "longest-turbulent-subarray", "post_title": "\u2705 [Python3] Longest Turbulent Subarray O(n) (one pass)", "user": "vscala", "upvotes": 2, "views": 207, "problem_title": "longest turbulent subarray", "number": 978, "acceptance": 0.474, "difficulty": "Medium", "__index_level_0__": 15877, "question": "Given an integer array arr, return the length of a maximum size turbulent subarray of arr.\nA subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.\nMore formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:\nFor i <= k < j:\narr[k] > arr[k + 1] when k is odd, and\narr[k] < arr[k + 1] when k is even.\nOr, for i <= k < j:\narr[k] > arr[k + 1] when k is even, and\narr[k] < arr[k + 1] when k is odd.\n Example 1:\nInput: arr = [9,4,2,10,7,8,8,1,9]\nOutput: 5\nExplanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]\nExample 2:\nInput: arr = [4,8,12,16]\nOutput: 2\nExample 3:\nInput: arr = [100]\nOutput: 1\n Constraints:\n1 <= arr.length <= 4 * 104\n0 <= arr[i] <= 109" }, { "post_href": "https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/2797049/Very-short-concise-Python-solution-with-DFS", "python_solutions": "class Solution:\n def distributeCoins(self, v: Optional[TreeNode], parent=None) -> int:\n if v is None:\n return 0\n m = self.distributeCoins(v.left, v) + self.distributeCoins(v.right, v)\n if v.val != 1:\n parent.val += v.val - 1\n m += abs(v.val - 1)\n return m", "slug": "distribute-coins-in-binary-tree", "post_title": "Very short, concise Python solution with DFS", "user": "metaphysicalist", "upvotes": 0, "views": 4, "problem_title": "distribute coins in binary tree", "number": 979, "acceptance": 0.721, "difficulty": "Medium", "__index_level_0__": 15891, "question": "You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.\nIn one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.\nReturn the minimum number of moves required to make every node have exactly one coin.\n Example 1:\nInput: root = [3,0,0]\nOutput: 2\nExplanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.\nExample 2:\nInput: root = [0,3,0]\nOutput: 3\nExplanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.\n Constraints:\nThe number of nodes in the tree is n.\n1 <= n <= 100\n0 <= Node.val <= n\nThe sum of all Node.val is n." }, { "post_href": "https://leetcode.com/problems/unique-paths-iii/discuss/1535158/Python-Backtracking%3A-Easy-to-understand-with-Explanation", "python_solutions": "class Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n\t\t# first, prepare the starting and ending points\n\t\t# simultaneously, record all the non-obstacle coordinates\n start = end = None\n visit = set()\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 0:\n visit.add((i, j))\n elif grid[i][j] == 1:\n start = (i, j)\n elif grid[i][j] == 2:\n end = (i, j)\n visit.add((i, j))\n \n def backtrack(x, y, visit):\n if (x, y) == end:\n\t\t\t\t# implement success condition: valid only if there are no more coordinates to visit\n return len(visit) == 0\n result = 0 # assume no valid paths by default\n\t\t\t\n\t\t\t# we need to try every possible path from this coordinate\n if (x-1, y) in visit:\n\t\t\t\t# the coordinate directly above this one is non-obstacle, try that path\n visit.remove((x-1, y)) # first, note down the 'visited status' of the coordinate\n result += backtrack(x-1, y, visit) # then, DFS to find all valid paths from that coordinate\n visit.add((x-1, y)) # last, reset the 'visited status' of the coordinate\n if (x+1, y) in visit:\n\t\t\t\t# the coordinate directly below this one is non-obstacle, try that path\n visit.remove((x+1, y))\n result += backtrack(x+1, y, visit)\n visit.add((x+1, y))\n if (x, y-1) in visit:\n\t\t\t\t# the coordinate directly to the left of this one is non-obstacle, try that path\n visit.remove((x, y-1))\n result += backtrack(x, y-1, visit)\n visit.add((x, y-1))\n if (x, y+1) in visit:\n\t\t\t\t# the coordinate directly to the right of this one is non-obstacle, try that path\n visit.remove((x, y+1))\n result += backtrack(x, y+1, visit)\n visit.add((x, y+1))\n return result\n \n return backtrack(start[0], start[1], visit) # we start from the starting point, backtrack all the way back, and consolidate the result", "slug": "unique-paths-iii", "post_title": "Python Backtracking: Easy-to-understand with Explanation", "user": "zayne-siew", "upvotes": 74, "views": 3500, "problem_title": "unique paths iii", "number": 980, "acceptance": 0.797, "difficulty": "Hard", "__index_level_0__": 15895, "question": "You are given an m x n integer array grid where grid[i][j] could be:\n1 representing the starting square. There is exactly one starting square.\n2 representing the ending square. There is exactly one ending square.\n0 representing empty squares we can walk over.\n-1 representing obstacles that we cannot walk over.\nReturn the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n Example 1:\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\nOutput: 2\nExplanation: We have the following two paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\nExample 2:\nInput: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\nOutput: 4\nExplanation: We have the following four paths: \n1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\nExample 3:\nInput: grid = [[0,1],[2,0]]\nOutput: 0\nExplanation: There is no path that walks over every empty square exactly once.\nNote that the starting and ending square can be anywhere in the grid.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 20\n1 <= m * n <= 20\n-1 <= grid[i][j] <= 2\nThere is exactly one starting cell and one ending cell." }, { "post_href": "https://leetcode.com/problems/triples-with-bitwise-and-equal-to-zero/discuss/1257470/Python3-hash-table", "python_solutions": "class Solution:\n def countTriplets(self, nums: List[int]) -> int:\n freq = defaultdict(int)\n for x in nums: \n for y in nums: \n freq[x&y] += 1\n \n ans = 0\n for x in nums: \n mask = x = x ^ 0xffff\n while x: \n ans += freq[x]\n x = mask & (x-1)\n ans += freq[0]\n return ans", "slug": "triples-with-bitwise-and-equal-to-zero", "post_title": "[Python3] hash table", "user": "ye15", "upvotes": 4, "views": 222, "problem_title": "triples with bitwise and equal to zero", "number": 982, "acceptance": 0.5770000000000001, "difficulty": "Hard", "__index_level_0__": 15925, "question": "Given an integer array nums, return the number of AND triples.\nAn AND triple is a triple of indices (i, j, k) such that:\n0 <= i < nums.length\n0 <= j < nums.length\n0 <= k < nums.length\nnums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.\n Example 1:\nInput: nums = [2,1,3]\nOutput: 12\nExplanation: We could choose the following i, j, k triples:\n(i=0, j=0, k=1) : 2 & 2 & 1\n(i=0, j=1, k=0) : 2 & 1 & 2\n(i=0, j=1, k=1) : 2 & 1 & 1\n(i=0, j=1, k=2) : 2 & 1 & 3\n(i=0, j=2, k=1) : 2 & 3 & 1\n(i=1, j=0, k=0) : 1 & 2 & 2\n(i=1, j=0, k=1) : 1 & 2 & 1\n(i=1, j=0, k=2) : 1 & 2 & 3\n(i=1, j=1, k=0) : 1 & 1 & 2\n(i=1, j=2, k=0) : 1 & 3 & 2\n(i=2, j=0, k=1) : 3 & 2 & 1\n(i=2, j=1, k=0) : 3 & 1 & 2\nExample 2:\nInput: nums = [0,0,0]\nOutput: 27\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] < 216" }, { "post_href": "https://leetcode.com/problems/minimum-cost-for-tickets/discuss/1219272/Python-O(N)-Runtime-O(N)-with-explanation", "python_solutions": "class Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n\t\t#create the total costs for the days \n costForDays = [0 for _ in range(days[-1] + 1) ]\n\t\t#since days are sorted in ascending order, we only need the index of the days we haven't visited yet\n curIdx = 0\n\t\t\n for d in range(1, len(costForDays)):\n\t\t\t#if we do not need to travel that day\n\t\t\t#we don't need to add extra costs\n if d < days[curIdx]:\n costForDays[d] = costForDays[d - 1]\n continue\n \n\t\t\t#else this means we need to travel this day\n\t\t\t#find the cost if we were to buy a 1-day pass, 7-day pass and 30-day pass\n costs_extra_1 = costForDays[d - 1] + costs[0]\n costs_extra_7 = costForDays[max(0, d - 7)] + costs[1] \n costs_extra_30 = costForDays[max(0, d - 30)] + costs[2]\n \n\t\t\t#get the minimum value\n costForDays[d] = min(costs_extra_1, costs_extra_7, costs_extra_30)\n\t\t\t\n\t\t\t#update the index to the next day we need to travel\n curIdx += 1\n\t\t\t\n return costForDays[-1]", "slug": "minimum-cost-for-tickets", "post_title": "Python O(N) Runtime O(N) with explanation", "user": "sherlockieee", "upvotes": 3, "views": 244, "problem_title": "minimum cost for tickets", "number": 983, "acceptance": 0.644, "difficulty": "Medium", "__index_level_0__": 15928, "question": "You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array days. Each day is an integer from 1 to 365.\nTrain tickets are sold in three different ways:\na 1-day pass is sold for costs[0] dollars,\na 7-day pass is sold for costs[1] dollars, and\na 30-day pass is sold for costs[2] dollars.\nThe passes allow that many days of consecutive travel.\nFor example, if we get a 7-day pass on day 2, then we can travel for 7 days: 2, 3, 4, 5, 6, 7, and 8.\nReturn the minimum number of dollars you need to travel every day in the given list of days.\n Example 1:\nInput: days = [1,4,6,7,8,20], costs = [2,7,15]\nOutput: 11\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\nOn day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\nOn day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\nIn total, you spent $11 and covered all the days of your travel.\nExample 2:\nInput: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\nOutput: 17\nExplanation: For example, here is one way to buy passes that lets you travel your travel plan:\nOn day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\nOn day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\nIn total, you spent $17 and covered all the days of your travel.\n Constraints:\n1 <= days.length <= 365\n1 <= days[i] <= 365\ndays is in strictly increasing order.\ncosts.length == 3\n1 <= costs[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/string-without-aaa-or-bbb/discuss/1729883/Python-beats-91", "python_solutions": "class Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n res = []\n while a + b > 0:\n if len(res) >= 2 and res[-2:] == ['a', 'a']:\n res.append('b')\n b-=1\n elif len(res) >= 2 and res[-2:] == ['b', 'b']:\n res.append('a')\n a-=1\n elif a > b:\n res.append('a')\n a-=1\n else:\n res.append('b')\n b-=1\n \n return ''.join(res)", "slug": "string-without-aaa-or-bbb", "post_title": "Python beats 91%", "user": "leopardcoderd", "upvotes": 1, "views": 104, "problem_title": "string without aaa or bbb", "number": 984, "acceptance": 0.43, "difficulty": "Medium", "__index_level_0__": 15944, "question": "Given two integers a and b, return any string s such that:\ns has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,\nThe substring 'aaa' does not occur in s, and\nThe substring 'bbb' does not occur in s.\n Example 1:\nInput: a = 1, b = 2\nOutput: \"abb\"\nExplanation: \"abb\", \"bab\" and \"bba\" are all correct answers.\nExample 2:\nInput: a = 4, b = 1\nOutput: \"aabaa\"\n Constraints:\n0 <= a, b <= 100\nIt is guaranteed such an s exists for the given a and b." }, { "post_href": "https://leetcode.com/problems/sum-of-even-numbers-after-queries/discuss/2603372/LeetCode-The-Hard-Way-Explained-Line-By-Line", "python_solutions": "class Solution:\n # the idea is we don't calculate the even sum from scratch for each query\n # instead, we calculate it at the beginning\n # since each query only updates one value, \n # so we can adjust the even sum base on the original value and new value\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n # calculate the sum of all even numbers\n evenSum = sum(x for x in nums if x % 2 == 0)\n ans = []\n for val, idx in queries:\n # if original nums[idx] is even, then we deduct it from evenSum\n if nums[idx] % 2 == 0: evenSum -= nums[idx]\n # in-place update nums\n nums[idx] += val\n # check if we need to update evenSum for the new value\n if nums[idx] % 2 == 0: evenSum += nums[idx]\n # then we have evenSum after this query, push it to ans \n ans.append(evenSum)\n return ans", "slug": "sum-of-even-numbers-after-queries", "post_title": "\ud83d\udd25 [LeetCode The Hard Way] \ud83d\udd25 Explained Line By Line", "user": "wingkwong", "upvotes": 58, "views": 3200, "problem_title": "sum of even numbers after queries", "number": 985, "acceptance": 0.682, "difficulty": "Medium", "__index_level_0__": 15949, "question": "You are given an integer array nums and an array queries where queries[i] = [vali, indexi].\nFor each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.\nReturn an integer array answer where answer[i] is the answer to the ith query.\n Example 1:\nInput: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\nOutput: [8,6,2,4]\nExplanation: At the beginning, the array is [1,2,3,4].\nAfter adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\nAfter adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\nAfter adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\nAfter adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\nExample 2:\nInput: nums = [1], queries = [[4,0]]\nOutput: [0]\n Constraints:\n1 <= nums.length <= 104\n-104 <= nums[i] <= 104\n1 <= queries.length <= 104\n-104 <= vali <= 104\n0 <= indexi < nums.length" }, { "post_href": "https://leetcode.com/problems/interval-list-intersections/discuss/646939/Python-O(m%2Bn)-by-two-pointers.w-Graph", "python_solutions": "class Solution:\n def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n \n idx_a, idx_b = 0, 0\n size_a, size_b = len(A), len(B)\n \n intersection = []\n \n # Scan each possible interval pair\n while idx_a < size_a and idx_b < size_b :\n \n # Get start-time as well as end-time\n start_a, end_a = A[idx_a]\n start_b, end_b = B[idx_b]\n \n \n # Compute common start time and end time for current interval pair\n common_start = max( start_a, start_b )\n common_end = min( end_a, end_b )\n \n if common_start <= common_end:\n # Find one common overlapped interval\n intersection.append( [common_start, common_end] )\n \n if end_a <= end_b:\n # Try next interval of A\n idx_a += 1\n \n else:\n # Try next interval of B\n idx_b += 1\n \n return intersection", "slug": "interval-list-intersections", "post_title": "Python O(m+n) by two-pointers.[w/ Graph]", "user": "brianchiang_tw", "upvotes": 3, "views": 264, "problem_title": "interval list intersections", "number": 986, "acceptance": 0.7140000000000001, "difficulty": "Medium", "__index_level_0__": 15997, "question": "You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order.\nReturn the intersection of these two interval lists.\nA closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.\nThe intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].\n Example 1:\nInput: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\nOutput: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\nExample 2:\nInput: firstList = [[1,3],[5,9]], secondList = []\nOutput: []\n Constraints:\n0 <= firstList.length, secondList.length <= 1000\nfirstList.length + secondList.length >= 1\n0 <= starti < endi <= 109\nendi < starti+1\n0 <= startj < endj <= 109 \nendj < startj+1" }, { "post_href": "https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/discuss/2526928/Python-BFS-%2B-Hashmap", "python_solutions": "class Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n results = defaultdict(list)\n \n queue = [ (root, 0, 0) ]\n \n while queue:\n node, pos, depth = queue.pop(0)\n if not node: continue\n results[(pos,depth)].append(node.val)\n results[(pos,depth)].sort()\n queue.extend( [ (node.left, pos-1, depth+1), (node.right, pos+1, depth+1) ] )\n \n \n res = defaultdict(list)\n keys = sorted(list(results.keys()), key=lambda x: (x[0], x[1]))\n \n \n for k in keys:\n pos, depth = k\n res[pos].extend(results[k])\n\n return res.values()", "slug": "vertical-order-traversal-of-a-binary-tree", "post_title": "Python BFS + Hashmap", "user": "complete_noob", "upvotes": 13, "views": 1700, "problem_title": "vertical order traversal of a binary tree", "number": 987, "acceptance": 0.447, "difficulty": "Hard", "__index_level_0__": 16025, "question": "Given the root of a binary tree, calculate the vertical order traversal of the binary tree.\nFor each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).\nThe vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.\nReturn the vertical order traversal of the binary tree.\n Example 1:\nInput: root = [3,9,20,null,null,15,7]\nOutput: [[9],[3,15],[20],[7]]\nExplanation:\nColumn -1: Only node 9 is in this column.\nColumn 0: Nodes 3 and 15 are in this column in that order from top to bottom.\nColumn 1: Only node 20 is in this column.\nColumn 2: Only node 7 is in this column.\nExample 2:\nInput: root = [1,2,3,4,5,6,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nColumn -2: Only node 4 is in this column.\nColumn -1: Only node 2 is in this column.\nColumn 0: Nodes 1, 5, and 6 are in this column.\n 1 is at the top, so it comes first.\n 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.\nColumn 1: Only node 3 is in this column.\nColumn 2: Only node 7 is in this column.\nExample 3:\nInput: root = [1,2,3,4,6,5,7]\nOutput: [[4],[2],[1,5,6],[3],[7]]\nExplanation:\nThis case is the exact same as example 2, but with nodes 5 and 6 swapped.\nNote that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.\n Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\n0 <= Node.val <= 1000" }, { "post_href": "https://leetcode.com/problems/smallest-string-starting-from-leaf/discuss/422855/Python-readable.-44ms-99.7-14MB-100", "python_solutions": "class Solution:\n res = 'z' * 13 # init max result, tree depth, 12< log2(8000) < 13\n \n def smallestFromLeaf(self, root: TreeNode) -> str:\n \n def helper(node: TreeNode, prev):\n prev = chr(97 + node.val) + prev\n \n if not node.left and not node.right:\n self.res = min(self.res, prev)\n return\n \n if node.left:\n helper(node.left, prev)\n if node.right:\n helper(node.right, prev)\n \n helper(root, \"\")\n return self.res", "slug": "smallest-string-starting-from-leaf", "post_title": "Python readable. 44ms 99.7% 14MB 100%", "user": "lsy7905", "upvotes": 3, "views": 331, "problem_title": "smallest string starting from leaf", "number": 988, "acceptance": 0.497, "difficulty": "Medium", "__index_level_0__": 16051, "question": "You are given the root of a binary tree where each node has a value in the range [0, 25] representing the letters 'a' to 'z'.\nReturn the lexicographically smallest string that starts at a leaf of this tree and ends at the root.\nAs a reminder, any shorter prefix of a string is lexicographically smaller.\nFor example, \"ab\" is lexicographically smaller than \"aba\".\nA leaf of a node is a node that has no children.\n Example 1:\nInput: root = [0,1,2,3,4,3,4]\nOutput: \"dba\"\nExample 2:\nInput: root = [25,1,3,1,3,0,2]\nOutput: \"adz\"\nExample 3:\nInput: root = [2,2,1,null,1,0,null,0]\nOutput: \"abc\"\n Constraints:\nThe number of nodes in the tree is in the range [1, 8500].\n0 <= Node.val <= 25" }, { "post_href": "https://leetcode.com/problems/add-to-array-form-of-integer/discuss/2037608/Python3-or-One-line-solution", "python_solutions": "class Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n return list(str(int(\"\".join([str(x) for x in num])) + k))", "slug": "add-to-array-form-of-integer", "post_title": "Python3 | One line solution", "user": "manfrommoon", "upvotes": 2, "views": 186, "problem_title": "add to array form of integer", "number": 989, "acceptance": 0.455, "difficulty": "Easy", "__index_level_0__": 16063, "question": "The array-form of an integer num is an array representing its digits in left to right order.\nFor example, for num = 1321, the array form is [1,3,2,1].\nGiven num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.\n Example 1:\nInput: num = [1,2,0,0], k = 34\nOutput: [1,2,3,4]\nExplanation: 1200 + 34 = 1234\nExample 2:\nInput: num = [2,7,4], k = 181\nOutput: [4,5,5]\nExplanation: 274 + 181 = 455\nExample 3:\nInput: num = [2,1,5], k = 806\nOutput: [1,0,2,1]\nExplanation: 215 + 806 = 1021\n Constraints:\n1 <= num.length <= 104\n0 <= num[i] <= 9\nnum does not contain any leading zeros except for the zero itself.\n1 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/satisfiability-of-equality-equations/discuss/2624938/python3-oror-13-lines-sets-oror-1-TM%3A-8967", "python_solutions": "class Solution: # Here's the plan:\n # 1) We make an undirected graph in which the nodes are integers\n # (as lower-case letters) and each edge connects integers\n # that are equal.\n # 2) We use a union-find process to determine the connected graphs\n # 3) We keep track of the pairs (a,b) such that a =! b. If the any\n # such pair are in the same connected graph, then return False,\n # otherwise return True.\n def equationsPossible(self, equations: List[str]) -> bool:\n parent, diff = {}, []\n\n def find(x):\n if x not in parent: return x\n else: return find(parent[x])\n\n for s in equations: # <-- 1)\n a, b = s[0], s[3]\n\n if s[1]== \"=\": # <-- 2)\n x, y = find(a), find(b)\n if x!=y:\n parent[y] = x\n else: \n diff.append((a,b)) # <-- 3)\n\n return all(find(a)!=find(b) for a, b in diff)", "slug": "satisfiability-of-equality-equations", "post_title": "python3 || 13 lines, sets || 1 T/M: 89%/67%", "user": "warrenruud", "upvotes": 26, "views": 1800, "problem_title": "satisfiability of equality equations", "number": 990, "acceptance": 0.508, "difficulty": "Medium", "__index_level_0__": 16109, "question": "You are given an array of strings equations that represent relationships between variables where each string equations[i] is of length 4 and takes one of two different forms: \"xi==yi\" or \"xi!=yi\".Here, xi and yi are lowercase letters (not necessarily different) that represent one-letter variable names.\nReturn true if it is possible to assign integers to variable names so as to satisfy all the given equations, or false otherwise.\n Example 1:\nInput: equations = [\"a==b\",\"b!=a\"]\nOutput: false\nExplanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\nThere is no way to assign the variables to satisfy both equations.\nExample 2:\nInput: equations = [\"b==a\",\"a==b\"]\nOutput: true\nExplanation: We could assign a = 1 and b = 1 to satisfy both equations.\n Constraints:\n1 <= equations.length <= 500\nequations[i].length == 4\nequations[i][0] is a lowercase letter.\nequations[i][1] is either '=' or '!'.\nequations[i][2] is '='.\nequations[i][3] is a lowercase letter." }, { "post_href": "https://leetcode.com/problems/broken-calculator/discuss/1033822/Easy-and-Clear-Solution-Python-3", "python_solutions": "class Solution:\n def brokenCalc(self, x: int, y: int) -> int:\n if y<=x:\n return x-y\n else:\n res=0\n while x 4 -> 3}.\nExample 2:\nInput: startValue = 5, target = 8\nOutput: 2\nExplanation: Use decrement and then double {5 -> 4 -> 8}.\nExample 3:\nInput: startValue = 3, target = 10\nOutput: 3\nExplanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n Constraints:\n1 <= startValue, target <= 109" }, { "post_href": "https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/1215277/Python-Sliding-Window-or-Set-%2B-HashMap", "python_solutions": "class Solution:\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n \n def window(nums, k):\n left = 0\n right = 0\n\n res = 0\n in_set = set()\n hash_map = collections.Counter()\n\n while right < len(nums):\n in_set.add(nums[right])\n hash_map[nums[right]] += 1\n\n while len(in_set) > k:\n hash_map[nums[left]] -= 1\n if hash_map[nums[left]] == 0:\n in_set.remove(nums[left])\n left += 1\n\n res += (right - left + 1)\n\n right += 1\n return res\n \n return window(nums, k) - window(nums, k - 1)", "slug": "subarrays-with-k-different-integers", "post_title": "[Python] Sliding Window | Set + HashMap", "user": "Sai-Adarsh", "upvotes": 5, "views": 813, "problem_title": "subarrays with k different integers", "number": 992, "acceptance": 0.545, "difficulty": "Hard", "__index_level_0__": 16146, "question": "Given an integer array nums and an integer k, return the number of good subarrays of nums.\nA good array is an array where the number of different integers in that array is exactly k.\nFor example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.\nA subarray is a contiguous part of an array.\n Example 1:\nInput: nums = [1,2,1,2,3], k = 2\nOutput: 7\nExplanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]\nExample 2:\nInput: nums = [1,2,1,3,4], k = 3\nOutput: 3\nExplanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n Constraints:\n1 <= nums.length <= 2 * 104\n1 <= nums[i], k <= nums.length" }, { "post_href": "https://leetcode.com/problems/cousins-in-binary-tree/discuss/1527334/Python-BFS%3A-Easy-to-understand-solution-w-Explanation", "python_solutions": "class Solution:\n def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:\n\t\t# Check if root node is x or y\n if root.val == x or root.val == y:\n return False\n\t\t# Prepare for BFS, initialise variables\n curr, flag = [root.left, root.right], False\n\t\t\n while curr:\n tmp = []\n\t\t\t# Check nodes two-by-two\n for i in range(0, len(curr), 2):\n\t\t\t\t# Case 1: x and y are both found\n\t\t\t\t# This indicates that they have the same parent\n if curr[i] and curr[i+1] and \\\n ((curr[i].val == x and curr[i+1].val == y) or \\\n (curr[i+1].val == x and curr[i].val == y)):\n return False\n\t\t\t\t# Case 2: Either one of x or y is found\n elif (curr[i] and (curr[i].val == x or curr[i].val == y)) or \\\n (curr[i+1] and (curr[i+1].val == x or curr[i+1].val == y)):\n if flag:\n\t\t\t\t\t\t# Previously, the other node has been found in the same depth\n\t\t\t\t\t\t# This is our success condition, return True\n return True\n\t\t\t\t\t# Otherwise, this is the first node in the current depth to be found\n flag = True\n\t\t\t\t\n\t\t\t\t# Simultaneously, we can prepare the nodes for the subsequent depth\n\t\t\t\t# Note to append both left and right regardless of existence\n if curr[i]:\n tmp.append(curr[i].left)\n tmp.append(curr[i].right)\n if curr[i+1]:\n tmp.append(curr[i+1].left)\n tmp.append(curr[i+1].right)\n\t\t\t\n\t\t\t# Before we proceed to the next depth, check:\n if flag:\n\t\t\t\t# One of the nodes has already been found\n\t\t\t\t# This means that the other node cannot be of the same depth\n\t\t\t\t# By definition, this means that the two nodes are not cousins\n return False\n curr = tmp # Assign the new nodes as the current ones\n\t\t\n\t\t# The program will never reach here since x and y are guaranteed to be found\n\t\t# But you can return False if you want", "slug": "cousins-in-binary-tree", "post_title": "Python BFS: Easy-to-understand solution w Explanation", "user": "zayne-siew", "upvotes": 8, "views": 423, "problem_title": "cousins in binary tree", "number": 993, "acceptance": 0.542, "difficulty": "Easy", "__index_level_0__": 16153, "question": "Given the root of a binary tree with unique values and the values of two different nodes of the tree x and y, return true if the nodes corresponding to the values x and y in the tree are cousins, or false otherwise.\nTwo nodes of a binary tree are cousins if they have the same depth with different parents.\nNote that in a binary tree, the root node is at the depth 0, and children of each depth k node are at the depth k + 1.\n Example 1:\nInput: root = [1,2,3,4], x = 4, y = 3\nOutput: false\nExample 2:\nInput: root = [1,2,3,null,4,null,5], x = 5, y = 4\nOutput: true\nExample 3:\nInput: root = [1,2,3,null,4], x = 2, y = 3\nOutput: false\n Constraints:\nThe number of nodes in the tree is in the range [2, 100].\n1 <= Node.val <= 100\nEach node has a unique value.\nx != y\nx and y are exist in the tree." }, { "post_href": "https://leetcode.com/problems/rotting-oranges/discuss/1546489/Python-BFS%3A-Easy-to-understand-with-Explanation", "python_solutions": "class Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n visit, curr = set(), deque()\n\t\t# find all fresh and rotten oranges\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n visit.add((i, j))\n elif grid[i][j] == 2:\n curr.append((i, j))\n result = 0\n while visit and curr:\n\t\t\t# BFS iteration\n for _ in range(len(curr)):\n i, j = curr.popleft() # obtain recent rotten orange\n for coord in ((i-1, j), (i+1, j), (i, j-1), (i, j+1)):\n if coord in visit: # check if adjacent orange is fresh\n visit.remove(coord)\n curr.append(coord)\n result += 1\n\t\t# check if fresh oranges remain and return accordingly\n return -1 if visit else result", "slug": "rotting-oranges", "post_title": "Python BFS: Easy-to-understand with Explanation", "user": "zayne-siew", "upvotes": 59, "views": 3900, "problem_title": "rotting oranges", "number": 994, "acceptance": 0.525, "difficulty": "Medium", "__index_level_0__": 16179, "question": "You are given an m x n grid where each cell can have one of three values:\n0 representing an empty cell,\n1 representing a fresh orange, or\n2 representing a rotten orange.\nEvery minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.\nReturn the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.\n Example 1:\nInput: grid = [[2,1,1],[1,1,0],[0,1,1]]\nOutput: 4\nExample 2:\nInput: grid = [[2,1,1],[0,1,1],[1,0,1]]\nOutput: -1\nExplanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.\nExample 3:\nInput: grid = [[0,2]]\nOutput: 0\nExplanation: Since there are already no fresh oranges at minute 0, the answer is just 0.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 10\ngrid[i][j] is 0, 1, or 2." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-k-consecutive-bit-flips/discuss/2122927/Python-O(N)-S(N)-Queue-solution", "python_solutions": "class Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n ans = 0\n q = []\n for i in range(len(nums)):\n if len(q) % 2 == 0:\n if nums[i] == 0:\n if i+k-1 <= len(nums)-1:\n ans += 1\n q.append(i+k-1)\n else:\n return -1\n else:\n if nums[i] == 1:\n if i+k-1 <= len(nums)-1:\n ans += 1\n q.append(i+k-1)\n else:\n return -1\n if q:\n if q[0] == i:\n q.pop(0)\n return ans", "slug": "minimum-number-of-k-consecutive-bit-flips", "post_title": "Python O(N) S(N) Queue solution", "user": "DietCoke777", "upvotes": 0, "views": 64, "problem_title": "minimum number of k consecutive bit flips", "number": 995, "acceptance": 0.512, "difficulty": "Hard", "__index_level_0__": 16219, "question": "You are given a binary array nums and an integer k.\nA k-bit flip is choosing a subarray of length k from nums and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0.\nReturn the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.\nA subarray is a contiguous part of an array.\n Example 1:\nInput: nums = [0,1,0], k = 1\nOutput: 2\nExplanation: Flip nums[0], then flip nums[2].\nExample 2:\nInput: nums = [1,1,0], k = 2\nOutput: -1\nExplanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].\nExample 3:\nInput: nums = [0,0,0,1,0,1,1,0], k = 3\nOutput: 3\nExplanation: \nFlip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\nFlip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\nFlip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]\n Constraints:\n1 <= nums.length <= 105\n1 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/number-of-squareful-arrays/discuss/1375586/python-simple-backtracking.-20ms", "python_solutions": "class Solution(object):\n def numSquarefulPerms(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n def dfs(temp,num,count = 0):\n if len(num)==0:\n return count+1\n for i in xrange(len(num)):\n if (i>0 and num[i]==num[i-1]) or (len(temp) > 0 and math.sqrt(num[i] + temp[-1]) % 1 != 0):\n continue\n count = dfs(temp+[num[i]],num[:i]+num[i+1:],count)\n return count\n \n nums.sort()\n res = dfs([],nums)\n return res", "slug": "number-of-squareful-arrays", "post_title": "python simple backtracking. 20ms", "user": "leah123", "upvotes": 1, "views": 305, "problem_title": "number of squareful arrays", "number": 996, "acceptance": 0.492, "difficulty": "Hard", "__index_level_0__": 16221, "question": "An array is squareful if the sum of every pair of adjacent elements is a perfect square.\nGiven an integer array nums, return the number of permutations of nums that are squareful.\nTwo permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].\n Example 1:\nInput: nums = [1,17,8]\nOutput: 2\nExplanation: [1,8,17] and [17,8,1] are the valid permutations.\nExample 2:\nInput: nums = [2,2,2]\nOutput: 1\n Constraints:\n1 <= nums.length <= 12\n0 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/find-the-town-judge/discuss/1663344/C%2B%2BJavaPython3Javascript-Everything-you-need-to-know-from-start-to-end-.", "python_solutions": "class Solution:\n def findJudge(self, N: int, trust: List[List[int]]) -> int:\n Trusted = [0] * (N+1)\n for (a, b) in trust:\n Trusted[a] -= 1\n Trusted[b] += 1\n \n for i in range(1, len(Trusted)):\n if Trusted[i] == N-1:\n return i\n return -1", "slug": "find-the-town-judge", "post_title": "[C++/Java/Python3/Javascript] Everything you need to know from start to end .", "user": "Cosmic_Phantom", "upvotes": 144, "views": 9500, "problem_title": "find the town judge", "number": 997, "acceptance": 0.493, "difficulty": "Easy", "__index_level_0__": 16228, "question": "In a town, there are n people labeled from 1 to n. There is a rumor that one of these people is secretly the town judge.\nIf the town judge exists, then:\nThe town judge trusts nobody.\nEverybody (except for the town judge) trusts the town judge.\nThere is exactly one person that satisfies properties 1 and 2.\nYou are given an array trust where trust[i] = [ai, bi] representing that the person labeled ai trusts the person labeled bi. If a trust relationship does not exist in trust array, then such a trust relationship does not exist.\nReturn the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.\n Example 1:\nInput: n = 2, trust = [[1,2]]\nOutput: 2\nExample 2:\nInput: n = 3, trust = [[1,3],[2,3]]\nOutput: 3\nExample 3:\nInput: n = 3, trust = [[1,3],[2,3],[3,1]]\nOutput: -1\n Constraints:\n1 <= n <= 1000\n0 <= trust.length <= 104\ntrust[i].length == 2\nAll the pairs of trust are unique.\nai != bi\n1 <= ai, bi <= n" }, { "post_href": "https://leetcode.com/problems/maximum-binary-tree-ii/discuss/2709985/Python-short-python-solution", "python_solutions": "class Solution:\n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n if not root: return TreeNode(val)\n if val > root.val: return TreeNode(val, root)\n root.right = self.insertIntoMaxTree(root.right, val)\n return root", "slug": "maximum-binary-tree-ii", "post_title": "[Python] short python solution", "user": "scrptgeek", "upvotes": 0, "views": 6, "problem_title": "maximum binary tree ii", "number": 998, "acceptance": 0.665, "difficulty": "Medium", "__index_level_0__": 16266, "question": "A maximum tree is a tree where every node has a value greater than any other value in its subtree.\nYou are given the root of a maximum binary tree and an integer val.\nJust as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:\nIf a is empty, return null.\nOtherwise, let a[i] be the largest element of a. Create a root node with the value a[i].\nThe left child of root will be Construct([a[0], a[1], ..., a[i - 1]]).\nThe right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]).\nReturn root.\nNote that we were not given a directly, only a root node root = Construct(a).\nSuppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.\nReturn Construct(b).\n Example 1:\nInput: root = [4,1,3,null,null,2], val = 5\nOutput: [5,4,null,1,3,null,null,2]\nExplanation: a = [1,4,2,3], b = [1,4,2,3,5]\nExample 2:\nInput: root = [5,2,4,null,1], val = 3\nOutput: [5,2,4,null,1,null,3]\nExplanation: a = [2,1,5,4], b = [2,1,5,4,3]\nExample 3:\nInput: root = [5,2,3,null,1], val = 4\nOutput: [5,2,4,null,1,3]\nExplanation: a = [2,1,5,3], b = [2,1,5,3,4]\n Constraints:\nThe number of nodes in the tree is in the range [1, 100].\n1 <= Node.val <= 100\nAll the values of the tree are unique.\n1 <= val <= 100" }, { "post_href": "https://leetcode.com/problems/available-captures-for-rook/discuss/356593/Solution-in-Python-3-(beats-~97)-(three-lines)", "python_solutions": "class Solution:\n def numRookCaptures(self, b: List[List[str]]) -> int:\n I, J = divmod(sum(b,[]).index('R'),8)\n C = \"\".join([i for i in [b[I]+['B']+[b[i][J] for i in range(8)]][0] if i != '.'])\n return C.count('Rp') + C.count('pR')\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "available-captures-for-rook", "post_title": "Solution in Python 3 (beats ~97%) (three lines)", "user": "junaidmansuri", "upvotes": 8, "views": 839, "problem_title": "available captures for rook", "number": 999, "acceptance": 0.679, "difficulty": "Easy", "__index_level_0__": 16270, "question": "On an 8 x 8 chessboard, there is exactly one white rook 'R' and some number of white bishops 'B', black pawns 'p', and empty squares '.'.\nWhen the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking.\nReturn the number of available captures for the white rook.\n Example 1:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation: In this example, the rook is attacking all the pawns.\nExample 2:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"B\",\"R\",\"B\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"B\",\"p\",\"p\",\".\",\".\"],[\".\",\"p\",\"p\",\"p\",\"p\",\"p\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 0\nExplanation: The bishops are blocking the rook from attacking any of the pawns.\nExample 3:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\nOutput: 3\nExplanation: The rook is attacking the pawns at positions b5, d6, and f5.\n Constraints:\nboard.length == 8\nboard[i].length == 8\nboard[i][j] is either 'R', '.', 'B', or 'p'\nThere is exactly one cell with board[i][j] == 'R'" }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-merge-stones/discuss/1465680/Python3-dp", "python_solutions": "class Solution:\n def mergeStones(self, stones: List[int], k: int) -> int:\n if (len(stones)-1) % (k-1): return -1 # impossible\n \n prefix = [0]\n for x in stones: prefix.append(prefix[-1] + x)\n \n @cache\n def fn(lo, hi): \n \"\"\"Return min cost of merging stones[lo:hi].\"\"\"\n if hi - lo < k: return 0 # not enough stones\n ans = inf \n for mid in range(lo+1, hi, k-1): \n ans = min(ans, fn(lo, mid) + fn(mid, hi))\n if (hi-lo-1) % (k-1) == 0: ans += prefix[hi] - prefix[lo]\n return ans \n \n return fn(0, len(stones))", "slug": "minimum-cost-to-merge-stones", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 1, "views": 654, "problem_title": "minimum cost to merge stones", "number": 1000, "acceptance": 0.423, "difficulty": "Hard", "__index_level_0__": 16291, "question": "There are n piles of stones arranged in a row. The ith pile has stones[i] stones.\nA move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles.\nReturn the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.\n Example 1:\nInput: stones = [3,2,4,1], k = 2\nOutput: 20\nExplanation: We start with [3, 2, 4, 1].\nWe merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\nWe merge [4, 1] for a cost of 5, and we are left with [5, 5].\nWe merge [5, 5] for a cost of 10, and we are left with [10].\nThe total cost was 20, and this is the minimum possible.\nExample 2:\nInput: stones = [3,2,4,1], k = 3\nOutput: -1\nExplanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.\nExample 3:\nInput: stones = [3,5,1,2,6], k = 3\nOutput: 25\nExplanation: We start with [3, 5, 1, 2, 6].\nWe merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\nWe merge [3, 8, 6] for a cost of 17, and we are left with [17].\nThe total cost was 25, and this is the minimum possible.\n Constraints:\nn == stones.length\n1 <= n <= 30\n1 <= stones[i] <= 100\n2 <= k <= 30" }, { "post_href": "https://leetcode.com/problems/grid-illumination/discuss/1233528/Python-or-HashMap-or-O(L%2BQ)-or-928ms", "python_solutions": "class Solution:\n def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n lamps = {(r, c) for r, c in lamps}\n \n row, col, left, right = dict(), dict(), dict(), dict()\n for r, c in lamps:\n row[r] = row.get(r, 0) + 1\n col[c] = col.get(c, 0) + 1\n left[r - c] = left.get(r - c, 0) + 1\n right[r + c] = right.get(r + c, 0) + 1\n\n res = list()\n for qr, qc in queries:\n if row.get(qr, 0) or col.get(qc, 0) or left.get(qr - qc, 0) or right.get(qr + qc, 0):\n res.append(1)\n else:\n res.append(0)\n\n for r, c in product(range(qr - 1, qr + 2), range(qc - 1, qc + 2)):\n if (r, c) in lamps:\n lamps.remove((r, c))\n row[r] -= 1\n col[c] -= 1\n left[r - c] -= 1\n right[r + c] -= 1\n\n return res", "slug": "grid-illumination", "post_title": "Python | HashMap | O(L+Q) | 928ms", "user": "PuneethaPai", "upvotes": 2, "views": 103, "problem_title": "grid illumination", "number": 1001, "acceptance": 0.362, "difficulty": "Hard", "__index_level_0__": 16294, "question": "There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.\nYou are given a 2D array of lamp positions lamps, where lamps[i] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on. Even if the same lamp is listed more than once, it is turned on.\nWhen a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\nYou are also given another 2D array queries, where queries[j] = [rowj, colj]. For the jth query, determine whether grid[rowj][colj] is illuminated or not. After answering the jth query, turn off the lamp at grid[rowj][colj] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[rowj][colj].\nReturn an array of integers ans, where ans[j] should be 1 if the cell in the jth query was illuminated, or 0 if the lamp was not.\n Example 1:\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\nOutput: [1,0]\nExplanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\nThe 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\nThe 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\nExample 2:\nInput: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\nOutput: [1,1]\nExample 3:\nInput: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\nOutput: [1,1,0]\n Constraints:\n1 <= n <= 109\n0 <= lamps.length <= 20000\n0 <= queries.length <= 20000\nlamps[i].length == 2\n0 <= rowi, coli < n\nqueries[j].length == 2\n0 <= rowj, colj < n" }, { "post_href": "https://leetcode.com/problems/find-common-characters/discuss/721548/Python-Faster-than-77.67-and-Better-Space-than-86.74", "python_solutions": "class Solution:\n def commonChars(self, A: List[str]) -> List[str]:\n alphabet = string.ascii_lowercase\n d = {c: 0 for c in alphabet}\n \n for k, v in d.items():\n d[k] = min([word.count(k) for word in A])\n\n res = []\n for c, n in d.items():\n if n > 0:\n res += [c] * n\n return res", "slug": "find-common-characters", "post_title": "Python Faster than 77.67% and Better Space than 86.74", "user": "parkershamblin", "upvotes": 8, "views": 997, "problem_title": "find common characters", "number": 1002, "acceptance": 0.6829999999999999, "difficulty": "Easy", "__index_level_0__": 16301, "question": "Given a string array words, return an array of all characters that show up in all strings within the words (including duplicates). You may return the answer in any order.\n Example 1:\nInput: words = [\"bella\",\"label\",\"roller\"]\nOutput: [\"e\",\"l\",\"l\"]\nExample 2:\nInput: words = [\"cool\",\"lock\",\"cook\"]\nOutput: [\"c\",\"o\"]\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 100\nwords[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/check-if-word-is-valid-after-substitutions/discuss/1291378/python-solution-using-stack", "python_solutions": "class Solution:\n def isValid(self, s: str) -> bool:\n stack=[]\n for i in s:\n if i == 'a':stack.append(i)\n elif i=='b':\n if not stack:return False\n else:\n if stack[-1]=='a':stack.pop()\n else:return False\n stack.append(i)\n else:\n if not stack:return False\n else:\n if stack[-1]=='b':stack.pop()\n else:return False\n\n return len(stack)==0", "slug": "check-if-word-is-valid-after-substitutions", "post_title": "python solution using stack", "user": "chikushen99", "upvotes": 2, "views": 94, "problem_title": "check if word is valid after substitutions", "number": 1003, "acceptance": 0.5820000000000001, "difficulty": "Medium", "__index_level_0__": 16339, "question": "Given a string s, determine if it is valid.\nA string s is valid if, starting with an empty string t = \"\", you can transform t into s after performing the following operation any number of times:\nInsert string \"abc\" into any position in t. More formally, t becomes tleft + \"abc\" + tright, where t == tleft + tright. Note that tleft and tright may be empty.\nReturn true if s is a valid string, otherwise, return false.\n Example 1:\nInput: s = \"aabcbc\"\nOutput: true\nExplanation:\n\"\" -> \"abc\" -> \"aabcbc\"\nThus, \"aabcbc\" is valid.\nExample 2:\nInput: s = \"abcabcababcc\"\nOutput: true\nExplanation:\n\"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\nThus, \"abcabcababcc\" is valid.\nExample 3:\nInput: s = \"abccba\"\nOutput: false\nExplanation: It is impossible to get \"abccba\" using the operation.\n Constraints:\n1 <= s.length <= 2 * 104\ns consists of letters 'a', 'b', and 'c'" }, { "post_href": "https://leetcode.com/problems/max-consecutive-ones-iii/discuss/1793625/Python-3-Very-typical-sliding-window-%2B-hashmap-problem.", "python_solutions": "class Solution:\n def longestOnes(self, nums: List[int], k: int) -> int:\n left = 0\n answer = 0\n counts = {0: 0, 1: 0}\n \n for right, num in enumerate(nums):\n counts[num] += 1\n \n while counts[0] > k:\n counts[nums[left]] -= 1\n left += 1\n \n curr_window_size = right - left + 1\n answer = max(answer, curr_window_size)\n \n return answer", "slug": "max-consecutive-ones-iii", "post_title": "[Python 3] Very typical sliding window + hashmap problem.", "user": "seankala", "upvotes": 5, "views": 152, "problem_title": "max consecutive ones iii", "number": 1004, "acceptance": 0.634, "difficulty": "Medium", "__index_level_0__": 16356, "question": "Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.\n Example 1:\nInput: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\nOutput: 6\nExplanation: [1,1,1,0,0,1,1,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\nExample 2:\nInput: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\nOutput: 10\nExplanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\nBolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n Constraints:\n1 <= nums.length <= 105\nnums[i] is either 0 or 1.\n0 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/maximize-sum-of-array-after-k-negations/discuss/1120243/WEEB-EXPLAINS-PYTHON-SOLUTION", "python_solutions": "class Solution:\n\tdef largestSumAfterKNegations(self, A: List[int], K: int) -> int:\n\t\tA.sort()\n\t\ti = 0\n\t\twhile i < len(A) and K>0:\n\t\t\tif A[i] < 0: # negative value\n\t\t\t\tA[i] = A[i] * -1 # update the list, change negative to positive\n\t\t\t\tK-=1\n\n\t\t\telif A[i] > 0: # positive value\n\t\t\t\tif K % 2 == 0: # let K==2(must be even value), this means -1*-1==1 so it has no effect on sum\n\t\t\t\t\treturn sum(A)\n\t\t\t\telse: return sum(A) - 2 * min(A) # let A==[1,2,3],K=1, so equation is 6-2(1)==4, same as -1+2+3=4 after taking the minimum in the list to give the largest possible sum required in the question\n\n\t\t\telse: return sum(A) # if A[i]==0,just sum cuz 0 is neutral: 1-0==1 or 1+0==1 thus no change just sum\n\n\t\t\ti+=1\n\n\t\tif K > len(A): # that means we have changed all values to positive\n\t\t\tA.sort() # cuz now its the opposite let A = [-4,-2,-3], K = 8, now flipping all negatives to positives, we have a new minimum which is 2\n\t\t\tif K % 2 == 0: # Here onwards is basically the same thing from before\n\t\t\t\treturn sum(A)\n\t\t\telse: return sum(A) - 2 * min(A)\n\n\t\treturn sum(A)", "slug": "maximize-sum-of-array-after-k-negations", "post_title": "WEEB EXPLAINS PYTHON SOLUTION", "user": "Skywalker5423", "upvotes": 6, "views": 361, "problem_title": "maximize sum of array after k negations", "number": 1005, "acceptance": 0.51, "difficulty": "Easy", "__index_level_0__": 16397, "question": "Given an integer array nums and an integer k, modify the array in the following way:\nchoose an index i and replace nums[i] with -nums[i].\nYou should apply this process exactly k times. You may choose the same index i multiple times.\nReturn the largest possible sum of the array after modifying it in this way.\n Example 1:\nInput: nums = [4,2,3], k = 1\nOutput: 5\nExplanation: Choose index 1 and nums becomes [4,-2,3].\nExample 2:\nInput: nums = [3,-1,0,2], k = 3\nOutput: 6\nExplanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].\nExample 3:\nInput: nums = [2,-3,-1,5,-4], k = 2\nOutput: 13\nExplanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].\n Constraints:\n1 <= nums.length <= 104\n-100 <= nums[i] <= 100\n1 <= k <= 104" }, { "post_href": "https://leetcode.com/problems/clumsy-factorial/discuss/395085/Three-Solutions-in-Python-3-(beats-~99)-(one-line)", "python_solutions": "class Solution:\n def clumsy(self, N: int) -> int:\n \treturn N + ([1,2,2,-1][N % 4] if N > 4 else [0,0,0,3,3][N])", "slug": "clumsy-factorial", "post_title": "Three Solutions in Python 3 (beats ~99%) (one line)", "user": "junaidmansuri", "upvotes": 3, "views": 525, "problem_title": "clumsy factorial", "number": 1006, "acceptance": 0.55, "difficulty": "Medium", "__index_level_0__": 16424, "question": "The factorial of a positive integer n is the product of all positive integers less than or equal to n.\nFor example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.\nWe make a clumsy factorial using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply '*', divide '/', add '+', and subtract '-' in this order.\nFor example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.\nHowever, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.\nAdditionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.\nGiven an integer n, return the clumsy factorial of n.\n Example 1:\nInput: n = 4\nOutput: 7\nExplanation: 7 = 4 * 3 / 2 + 1\nExample 2:\nInput: n = 10\nOutput: 12\nExplanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-domino-rotations-for-equal-row/discuss/1865333/Python3-UNPRECENDENT-NUMBER-OF-COUNTERS-o()o-Explained", "python_solutions": "class Solution:\n def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n total = len(tops)\n top_fr, bot_fr, val_total = [0]*7, [0]*7, [total]*7\n for top, bot in zip(tops, bottoms):\n if top == bot:\n val_total[top] -= 1\n else:\n top_fr[top] += 1\n bot_fr[bot] += 1\n \n for val in range(1, 7):\n if (val_total[val] - top_fr[val]) == bot_fr[val]:\n return min(top_fr[val], bot_fr[val])\n \n return -1", "slug": "minimum-domino-rotations-for-equal-row", "post_title": "\u2714\ufe0f[Python3] UNPRECENDENT NUMBER OF COUNTERS o\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u256e(\uff61\u275b\u1d17\u275b\uff61)\u256do\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361\u0361, Explained", "user": "artod", "upvotes": 23, "views": 1100, "problem_title": "minimum domino rotations for equal row", "number": 1007, "acceptance": 0.524, "difficulty": "Medium", "__index_level_0__": 16432, "question": "In a row of dominoes, tops[i] and bottoms[i] represent the top and bottom halves of the ith domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)\nWe may rotate the ith domino, so that tops[i] and bottoms[i] swap values.\nReturn the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.\nIf it cannot be done, return -1.\n Example 1:\nInput: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\nOutput: 2\nExplanation: \nThe first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\nIf we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.\nExample 2:\nInput: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\nOutput: -1\nExplanation: \nIn this case, it is not possible to rotate the dominoes to make one row of values equal.\n Constraints:\n2 <= tops.length <= 2 * 104\nbottoms.length == tops.length\n1 <= tops[i], bottoms[i] <= 6" }, { "post_href": "https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/649369/Python.-No-recursion.", "python_solutions": "class Solution:\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\n node_stack = []\n node = root = TreeNode(preorder[0])\n for n in preorder[1:]:\n if n <= node.val:\n node.left = TreeNode(n)\n node_stack.append(node)\n node = node.left\n else:\n while node_stack and n > node_stack[-1].val:\n node = node_stack.pop()\n node.right = TreeNode(n)\n node = node.right\n return root", "slug": "construct-binary-search-tree-from-preorder-traversal", "post_title": "Python. No recursion.", "user": "techrabbit58", "upvotes": 4, "views": 464, "problem_title": "construct binary search tree from preorder traversal", "number": 1008, "acceptance": 0.809, "difficulty": "Medium", "__index_level_0__": 16451, "question": "Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.\nIt is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.\nA binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.\nA preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.\n Example 1:\nInput: preorder = [8,5,1,7,10,12]\nOutput: [8,5,10,1,7,null,12]\nExample 2:\nInput: preorder = [1,3]\nOutput: [1,null,3]\n Constraints:\n1 <= preorder.length <= 100\n1 <= preorder[i] <= 1000\nAll the values of preorder are unique." }, { "post_href": "https://leetcode.com/problems/complement-of-base-10-integer/discuss/1666811/Python-Simple-Solution-with-Detail-Explanation-%3A-O(log-n)", "python_solutions": "class Solution:\n def bitwiseComplement(self, n: int) -> int:\n if n == 0:\n return 1\n else:\n result = 0\n factor = 1\n \n while(n > 0):\n result += factor * (1 if n%2 == 0 else 0)\n factor *= 2\n n //= 2\n return result", "slug": "complement-of-base-10-integer", "post_title": "Python Simple Solution with Detail Explanation : O(log n)", "user": "yashitanamdeo", "upvotes": 2, "views": 314, "problem_title": "complement of base 10 integer", "number": 1009, "acceptance": 0.619, "difficulty": "Easy", "__index_level_0__": 16476, "question": "The complement of an integer is the integer you get when you flip all the 0's to 1's and all the 1's to 0's in its binary representation.\nFor example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\nGiven an integer n, return its complement.\n Example 1:\nInput: n = 5\nOutput: 2\nExplanation: 5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.\nExample 2:\nInput: n = 7\nOutput: 0\nExplanation: 7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.\nExample 3:\nInput: n = 10\nOutput: 5\nExplanation: 10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.\n Constraints:\n0 <= n < 109\n Note: This question is the same as 476: https://leetcode.com/problems/number-complement/" }, { "post_href": "https://leetcode.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/discuss/422213/Python-O(n)-6-Lines-beats-86-time", "python_solutions": "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res , count = 0, [0] * 60\n for one in range(len(time)):\n index = time[one] % 60\n res += count[(60 - index)%60] # %60 is for index==0\n count[index] += 1\n return res", "slug": "pairs-of-songs-with-total-durations-divisible-by-60", "post_title": "Python O(n) 6 Lines beats 86% time", "user": "macqueen", "upvotes": 26, "views": 1900, "problem_title": "pairs of songs with total durations divisible by 60", "number": 1010, "acceptance": 0.529, "difficulty": "Medium", "__index_level_0__": 16510, "question": "You are given a list of songs where the ith song has a duration of time[i] seconds.\nReturn the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.\n Example 1:\nInput: time = [30,20,150,100,40]\nOutput: 3\nExplanation: Three pairs have a total duration divisible by 60:\n(time[0] = 30, time[2] = 150): total duration 180\n(time[1] = 20, time[3] = 100): total duration 120\n(time[1] = 20, time[4] = 40): total duration 60\nExample 2:\nInput: time = [60,60,60]\nOutput: 3\nExplanation: All three pairs have a total duration of 120, which is divisible by 60.\n Constraints:\n1 <= time.length <= 6 * 104\n1 <= time[i] <= 500" }, { "post_href": "https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/discuss/1581292/Well-Explained-oror-Thought-process-oror-94-faster", "python_solutions": "class Solution:\ndef shipWithinDays(self, weights: List[int], D: int) -> int:\n \n def feasible(capacity):\n days = 1\n local = 0\n for w in weights:\n local+=w\n if local>capacity:\n local = w\n days+=1\n if days>D:\n return False\n return True\n \n \n left, right = max(weights), sum(weights)\n while left < right:\n mid = left + (right-left)//2\n if feasible(mid):\n right = mid\n else:\n left = mid + 1\n \n return left", "slug": "capacity-to-ship-packages-within-d-days", "post_title": "\ud83d\udccc\ud83d\udccc Well-Explained || Thought process || 94% faster \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 31, "views": 1900, "problem_title": "capacity to ship packages within d days", "number": 1011, "acceptance": 0.6459999999999999, "difficulty": "Medium", "__index_level_0__": 16543, "question": "A conveyor belt has packages that must be shipped from one port to another within days days.\nThe ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.\nReturn the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.\n Example 1:\nInput: weights = [1,2,3,4,5,6,7,8,9,10], days = 5\nOutput: 15\nExplanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n1st day: 1, 2, 3, 4, 5\n2nd day: 6, 7\n3rd day: 8\n4th day: 9\n5th day: 10\n\nNote that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.\nExample 2:\nInput: weights = [3,2,2,4,1,4], days = 3\nOutput: 6\nExplanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n1st day: 3, 2\n2nd day: 2, 4\n3rd day: 1, 4\nExample 3:\nInput: weights = [1,2,3,1,1], days = 4\nOutput: 3\nExplanation:\n1st day: 1\n2nd day: 2\n3rd day: 3\n4th day: 1, 1\n Constraints:\n1 <= days <= weights.length <= 5 * 104\n1 <= weights[i] <= 500" }, { "post_href": "https://leetcode.com/problems/numbers-with-repeated-digits/discuss/332462/Solution-in-Python-3-(beats-~99)", "python_solutions": "class Solution:\n def numDupDigitsAtMostN(self, N: int) -> int:\n \tT = [9,261,4725,67509,831429,9287109,97654149,994388229]\n \tt = [99,999,9999,99999,999999,9999999,99999999,999999999]\n \tif N < 10:\n \t\treturn 0\n \tL = len(str(N))\n \tm, n = [1], []\n \tg = 11-L\n \tfor i in range(L):\n \t\tn.append(int(str(N)[i]))\n \t\tm.append(g)\n \t\tg = g*(12-L+i)\n \tS = 0\n \tfor i in range(L):\n \t\tif len(set(n[:L-i-1])) != len(n)-i-1:\n \t\t\tcontinue\n \t\tk = 0\n \t\tfor j in range(10):\n \t\t\tif j not in n[:L-i-1] and j > n[L-i-1]:\n \t\t\t\tk += 1\n \t\tS += k*m[i]\n \treturn(T[L-2]-(t[L-2]-N-S))\n\t\n- Python 3\n- Junaid Mansuri", "slug": "numbers-with-repeated-digits", "post_title": "Solution in Python 3 (beats ~99%)", "user": "junaidmansuri", "upvotes": 2, "views": 962, "problem_title": "numbers with repeated digits", "number": 1012, "acceptance": 0.406, "difficulty": "Hard", "__index_level_0__": 16569, "question": "Given an integer n, return the number of positive integers in the range [1, n] that have at least one repeated digit.\n Example 1:\nInput: n = 20\nOutput: 1\nExplanation: The only positive number (<= 20) with at least 1 repeated digit is 11.\nExample 2:\nInput: n = 100\nOutput: 10\nExplanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.\nExample 3:\nInput: n = 1000\nOutput: 262\n Constraints:\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/discuss/352417/Solution-in-Python-3-(beats-~99)-(With-Detailed-Explanation)-(-O(n)-time-)-(-O(1)-space-)", "python_solutions": "class Solution:\n def canThreePartsEqualSum(self, A: List[int]) -> bool:\n \tS = sum(A)\n \tif S % 3 != 0: return False\n \tg, C, p = S//3, 0, 0\n \tfor a in A[:-1]:\n \t\tC += a\n \t\tif C == g:\n \t\t\tif p == 1: return True\n \t\t\tC, p = 0, 1\n \treturn False", "slug": "partition-array-into-three-parts-with-equal-sum", "post_title": "Solution in Python 3 (beats ~99%) (With Detailed Explanation) ( O(n) time ) ( O(1) space )", "user": "junaidmansuri", "upvotes": 22, "views": 1600, "problem_title": "partition array into three parts with equal sum", "number": 1013, "acceptance": 0.432, "difficulty": "Easy", "__index_level_0__": 16570, "question": "Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.\nFormally, we can partition the array if we can find indexes i + 1 < j with (arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])\n Example 1:\nInput: arr = [0,2,1,-6,6,-7,9,1,2,0,1]\nOutput: true\nExplanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\nExample 2:\nInput: arr = [0,2,1,-6,6,7,9,-1,2,0,1]\nOutput: false\nExample 3:\nInput: arr = [3,3,6,5,-2,2,5,1,-9,4]\nOutput: true\nExplanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n Constraints:\n3 <= arr.length <= 5 * 104\n-104 <= arr[i] <= 104" }, { "post_href": "https://leetcode.com/problems/best-sightseeing-pair/discuss/1521786/oror-Very-easy-explanation-oror-DP-oror-Complexity-Analysis-oror-Python", "python_solutions": "class Solution:\n def maxScoreSightseeingPair(self, values: List[int]) -> int: \n dp = [0]*(len(values))\n dp[0] = values[0]\n maxVal = 0\n \n for i in range(1, len(values)):\n dp[i] = max(dp[i-1], values[i-1]+i-1)\n maxVal = max(maxVal, dp[i]+values[i]-i)\n \n return maxVal", "slug": "best-sightseeing-pair", "post_title": "\u2705 || Very easy explanation || DP || Complexity Analysis || Python", "user": "siddp6", "upvotes": 34, "views": 1100, "problem_title": "best sightseeing pair", "number": 1014, "acceptance": 0.595, "difficulty": "Medium", "__index_level_0__": 16586, "question": "You are given an integer array values where values[i] represents the value of the ith sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.\nThe score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.\nReturn the maximum score of a pair of sightseeing spots.\n Example 1:\nInput: values = [8,1,5,2,6]\nOutput: 11\nExplanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11\nExample 2:\nInput: values = [1,2]\nOutput: 2\n Constraints:\n2 <= values.length <= 5 * 104\n1 <= values[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/smallest-integer-divisible-by-k/discuss/1655649/Python3-Less-Math-More-Intuition-or-2-Accepted-Solutions-or-Intuitive", "python_solutions": "class Solution:\n def smallestRepunitDivByK(self, k: int) -> int:\n if not k % 2 or not k % 5: return -1\n n = length = 1\n while True:\n if not n % k: return length\n length += 1\n n = 10*n + 1", "slug": "smallest-integer-divisible-by-k", "post_title": "[Python3] \u2714\ufe0f Less Math, More Intuition \u2714\ufe0f | 2 Accepted Solutions | Intuitive", "user": "PatrickOweijane", "upvotes": 26, "views": 1900, "problem_title": "smallest integer divisible by k", "number": 1015, "acceptance": 0.47, "difficulty": "Medium", "__index_level_0__": 16616, "question": "Given a positive integer k, you need to find the length of the smallest positive integer n such that n is divisible by k, and n only contains the digit 1.\nReturn the length of n. If there is no such n, return -1.\nNote: n may not fit in a 64-bit signed integer.\n Example 1:\nInput: k = 1\nOutput: 1\nExplanation: The smallest answer is n = 1, which has length 1.\nExample 2:\nInput: k = 2\nOutput: -1\nExplanation: There is no such positive integer n divisible by 2.\nExample 3:\nInput: k = 3\nOutput: 3\nExplanation: The smallest answer is n = 111, which has length 3.\n Constraints:\n1 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/binary-string-with-substrings-representing-1-to-n/discuss/1106296/Python3-2-approaches", "python_solutions": "class Solution:\n def queryString(self, S: str, N: int) -> bool:\n for x in range(N, 0, -1):\n if bin(x)[2:] not in S: return False \n return True", "slug": "binary-string-with-substrings-representing-1-to-n", "post_title": "[Python3] 2 approaches", "user": "ye15", "upvotes": 6, "views": 387, "problem_title": "binary string with substrings representing 1 to n", "number": 1016, "acceptance": 0.575, "difficulty": "Medium", "__index_level_0__": 16623, "question": "Given a binary string s and a positive integer n, return true if the binary representation of all the integers in the range [1, n] are substrings of s, or false otherwise.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: s = \"0110\", n = 3\nOutput: true\nExample 2:\nInput: s = \"0110\", n = 4\nOutput: false\n Constraints:\n1 <= s.length <= 1000\ns[i] is either '0' or '1'.\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/convert-to-base-2/discuss/2007392/PYTHON-SOL-oror-EASY-oror-BINARY-CONVERSION-oror-WELL-EXPLAINED-oror", "python_solutions": "class Solution:\n def baseNeg2(self, n: int) -> str:\n ans = \"\"\n while n != 0:\n if n%-2 != 0 :\n ans = '1' + ans\n n = (n-1)//-2\n else:\n ans = '0' + ans\n n = n//-2\n return ans if ans !=\"\" else '0'", "slug": "convert-to-base-2", "post_title": "PYTHON SOL || EASY || BINARY CONVERSION || WELL EXPLAINED ||", "user": "reaper_27", "upvotes": 1, "views": 172, "problem_title": "convert to base 2", "number": 1017, "acceptance": 0.61, "difficulty": "Medium", "__index_level_0__": 16630, "question": "Given an integer n, return a binary string representing its representation in base -2.\nNote that the returned string should not have leading zeros unless the string is \"0\".\n Example 1:\nInput: n = 2\nOutput: \"110\"\nExplantion: (-2)2 + (-2)1 = 2\nExample 2:\nInput: n = 3\nOutput: \"111\"\nExplantion: (-2)2 + (-2)1 + (-2)0 = 3\nExample 3:\nInput: n = 4\nOutput: \"100\"\nExplantion: (-2)2 = 4\n Constraints:\n0 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/binary-prefix-divisible-by-5/discuss/356289/Solution-in-Python-3-(beats-~98)-(three-lines)-(-O(1)-space-)", "python_solutions": "class Solution:\n def prefixesDivBy5(self, A: List[int]) -> List[bool]:\n \tn = 0\n \tfor i in range(len(A)): A[i], n = (2*n + A[i]) % 5 == 0, (2*n + A[i]) % 5\n \treturn A\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "binary-prefix-divisible-by-5", "post_title": "Solution in Python 3 (beats ~98%) (three lines) ( O(1) space )", "user": "junaidmansuri", "upvotes": 4, "views": 349, "problem_title": "binary prefix divisible by 5", "number": 1018, "acceptance": 0.473, "difficulty": "Easy", "__index_level_0__": 16634, "question": "You are given a binary array nums (0-indexed).\nWe define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).\nFor example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.\nReturn an array of booleans answer where answer[i] is true if xi is divisible by 5.\n Example 1:\nInput: nums = [0,1,1]\nOutput: [true,false,false]\nExplanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.\nOnly the first number is divisible by 5, so answer[0] is true.\nExample 2:\nInput: nums = [1,1,1]\nOutput: [false,false,false]\n Constraints:\n1 <= nums.length <= 105\nnums[i] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/283607/Clean-Python-Code", "python_solutions": "class Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n result = []\n stack = []\n for i, current in enumerate(self.value_iterator(head)):\n result.append(0)\n while stack and stack[-1][0] < current:\n _, index = stack.pop()\n result[index] = current\n stack.append((current, i))\n return result\n\n def value_iterator(self, head: ListNode):\n while head is not None:\n yield head.val\n head = head.next", "slug": "next-greater-node-in-linked-list", "post_title": "Clean Python Code", "user": "aquafie", "upvotes": 3, "views": 817, "problem_title": "next greater node in linked list", "number": 1019, "acceptance": 0.599, "difficulty": "Medium", "__index_level_0__": 16644, "question": "You are given the head of a linked list with n nodes.\nFor each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.\nReturn an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.\n Example 1:\nInput: head = [2,1,5]\nOutput: [5,5,0]\nExample 2:\nInput: head = [2,7,4,3,5]\nOutput: [7,0,5,5,0]\n Constraints:\nThe number of nodes in the list is n.\n1 <= n <= 104\n1 <= Node.val <= 109" }, { "post_href": "https://leetcode.com/problems/number-of-enclaves/discuss/1040282/Python-BFS-and-DFS-by-yours-truly", "python_solutions": "class Solution:\ndef numEnclaves(self, A: List[List[int]]) -> int:\n row, col = len(A), len(A[0])\n \n if not A or not A[0]:\n return 0\n \n boundary1 = deque([(i,0) for i in range(row) if A[i][0]==1]) + deque([(i,col-1) for i in range(row) if A[i][col-1]==1])\n boundary2 = deque([(0,i) for i in range(1,col-1) if A[0][i]==1]) + deque([(row-1,i) for i in range(1,col-1) if A[row-1][i]==1])\n \n queue = boundary1+boundary2\n \n \n def bfs(queue,A):\n visited = set()\n while queue:\n x,y = queue.popleft()\n A[x][y] = \"T\"\n if (x,y) in visited: continue\n visited.add((x,y))\n for nx,ny in [[x+1,y],[x-1,y],[x,y+1],[x,y-1]]:\n if 0<=nx str:\n \n stack=[]\n counter=0\n for i in S:\n if i=='(':\n counter=counter+1\n if counter==1:\n pass\n else:\n stack.append(i)\n else:\n counter=counter-1\n if counter == 0:\n pass\n else:\n stack.append(i)\n return (''.join(stack))", "slug": "remove-outermost-parentheses", "post_title": "Python Simplest Solution", "user": "aishwaryanathanii", "upvotes": 5, "views": 164, "problem_title": "remove outermost parentheses", "number": 1021, "acceptance": 0.802, "difficulty": "Easy", "__index_level_0__": 16696, "question": "A valid parentheses string is either empty \"\", \"(\" + A + \")\", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.\nFor example, \"\", \"()\", \"(())()\", and \"(()(()))\" are all valid parentheses strings.\nA valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.\nGiven a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.\nReturn s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.\n Example 1:\nInput: s = \"(()())(())\"\nOutput: \"()()()\"\nExplanation: \nThe input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\nExample 2:\nInput: s = \"(()())(())(()(()))\"\nOutput: \"()()()()(())\"\nExplanation: \nThe input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\nAfter removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".\nExample 3:\nInput: s = \"()()\"\nOutput: \"\"\nExplanation: \nThe input string is \"()()\", with primitive decomposition \"()\" + \"()\".\nAfter removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n Constraints:\n1 <= s.length <= 105\ns[i] is either '(' or ')'.\ns is a valid parentheses string." }, { "post_href": "https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/discuss/1681647/Python3-5-LINES-(-)-Explained", "python_solutions": "class Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n def dfs(node, path):\n if not node: return 0\n\n path = (path << 1) + node.val\n\t\t\t\n if not node.left and not node.right:\n return path\n \n return dfs(node.left, path) + dfs(node.right, path)\n \n return dfs(root, 0)", "slug": "sum-of-root-to-leaf-binary-numbers", "post_title": "\u2714\ufe0f [Python3] 5-LINES \u261c\u202f( \u0361\u275b\u202f\ud83d\udc45 \u0361\u275b), Explained", "user": "artod", "upvotes": 19, "views": 876, "problem_title": "sum of root to leaf binary numbers", "number": 1022, "acceptance": 0.737, "difficulty": "Easy", "__index_level_0__": 16731, "question": "You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.\nFor example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.\nFor all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.\nThe test cases are generated so that the answer fits in a 32-bits integer.\n Example 1:\nInput: root = [1,0,1,0,1,0,1]\nOutput: 22\nExplanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22\nExample 2:\nInput: root = [0]\nOutput: 0\n Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\nNode.val is 0 or 1." }, { "post_href": "https://leetcode.com/problems/camelcase-matching/discuss/488216/Python-Two-Pointer-Memory-usage-less-than-100", "python_solutions": "class Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n \n def match(p, q):\n i = 0\n for j, c in enumerate(q):\n if i < len(p) and p[i] == q[j]: i += 1\n elif q[j].isupper(): return False\n return i == len(p)\n \n return [True if match(pattern, s) else False for s in queries]", "slug": "camelcase-matching", "post_title": "Python - Two Pointer - Memory usage less than 100%", "user": "mmbhatk", "upvotes": 8, "views": 638, "problem_title": "camelcase matching", "number": 1023, "acceptance": 0.602, "difficulty": "Medium", "__index_level_0__": 16756, "question": "Given an array of strings queries and a string pattern, return a boolean array answer where answer[i] is true if queries[i] matches pattern, and false otherwise.\nA query word queries[i] matches pattern if you can insert lowercase English letters pattern so that it equals the query. You may insert each character at any position and you may not insert any characters.\n Example 1:\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\nOutput: [true,false,true,true,false]\nExplanation: \"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n\"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n\"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".\nExample 2:\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\nOutput: [true,false,true,false,false]\nExplanation: \"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n\"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".\nExample 3:\nInput: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\nOutput: [false,true,false,false,false]\nExplanation: \"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".\n Constraints:\n1 <= pattern.length, queries.length <= 100\n1 <= queries[i].length <= 100\nqueries[i] and pattern consist of English letters." }, { "post_href": "https://leetcode.com/problems/video-stitching/discuss/2773366/greedy", "python_solutions": "class Solution:\n def videoStitching(self, clips: List[List[int]], T: int) -> int:\n end, end2, res = -1, 0, 0\n for i, j in sorted(clips):\n if end2 >= T or i > end2:\n break\n elif end < i <= end2:\n res, end = res + 1, end2\n end2 = max(end2, j)\n return res if end2 >= T else -1", "slug": "video-stitching", "post_title": "greedy", "user": "yhu415", "upvotes": 0, "views": 1, "problem_title": "video stitching", "number": 1024, "acceptance": 0.505, "difficulty": "Medium", "__index_level_0__": 16767, "question": "You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.\nEach video clip is described by an array clips where clips[i] = [starti, endi] indicates that the ith clip started at starti and ended at endi.\nWe can cut these clips into segments freely.\nFor example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].\nReturn the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.\n Example 1:\nInput: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\nOutput: 3\nExplanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\nThen, we can reconstruct the sporting event as follows:\nWe cut [1,9] into segments [1,2] + [2,8] + [8,9].\nNow we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].\nExample 2:\nInput: clips = [[0,1],[1,2]], time = 5\nOutput: -1\nExplanation: We cannot cover [0,5] with only [0,1] and [1,2].\nExample 3:\nInput: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9\nOutput: 3\nExplanation: We can take clips [0,4], [4,7], and [6,9].\n Constraints:\n1 <= clips.length <= 100\n0 <= starti <= endi <= 100\n1 <= time <= 100" }, { "post_href": "https://leetcode.com/problems/divisor-game/discuss/382233/Solution-in-Python-3-(With-Detailed-Proof)", "python_solutions": "class Solution:\n def divisorGame(self, N: int) -> bool:\n return N % 2 == 0\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "divisor-game", "post_title": "Solution in Python 3 (With Detailed Proof)", "user": "junaidmansuri", "upvotes": 150, "views": 6100, "problem_title": "divisor game", "number": 1025, "acceptance": 0.672, "difficulty": "Easy", "__index_level_0__": 16773, "question": "Alice and Bob take turns playing a game, with Alice starting first.\nInitially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:\nChoosing any x with 0 < x < n and n % x == 0.\nReplacing the number n on the chalkboard with n - x.\nAlso, if a player cannot make a move, they lose the game.\nReturn true if and only if Alice wins the game, assuming both players play optimally.\n Example 1:\nInput: n = 2\nOutput: true\nExplanation: Alice chooses 1, and Bob has no more moves.\nExample 2:\nInput: n = 3\nOutput: false\nExplanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/discuss/1657537/Python3-Simplifying-Tree-to-Arrays-oror-Detailed-Explanation-%2B-Intuition-oror-Preorder-DFS", "python_solutions": "class Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n def dfs(root, mn, mx):\n # Base Case: If we reach None, just return 0 in order not to affect the result\n if not root: return 0\n \n\t\t\t# The best difference we can do using the current node can be found:\n res = max(abs(root.val - mn), abs(root.val - mx))\n\t\t\t\n\t\t\t# Recompute the new minimum and maximum taking into account the current node\n mn, mx = min(mn, root.val), max(mx, root.val)\n\t\t\t\n\t\t\t# Recurse left and right using the newly computated minimum and maximum\n return max(res, dfs(root.left, mn, mx), dfs(root.right, mn, mx))\n \n # Initialize minimum `mn` and maximum `mx` equals value of given root\n return dfs(root, root.val, root.val)", "slug": "maximum-difference-between-node-and-ancestor", "post_title": "\u2705 [Python3] Simplifying Tree to Arrays || Detailed Explanation + Intuition || Preorder DFS", "user": "PatrickOweijane", "upvotes": 10, "views": 509, "problem_title": "maximum difference between node and ancestor", "number": 1026, "acceptance": 0.7340000000000001, "difficulty": "Medium", "__index_level_0__": 16791, "question": "Given the root of a binary tree, find the maximum value v for which there exist different nodes a and b where v = |a.val - b.val| and a is an ancestor of b.\nA node a is an ancestor of b if either: any child of a is equal to b or any child of a is an ancestor of b.\n Example 1:\nInput: root = [8,3,10,1,6,null,14,null,null,4,7,13]\nOutput: 7\nExplanation: We have various ancestor-node differences, some of which are given below :\n|8 - 3| = 5\n|3 - 7| = 4\n|8 - 1| = 7\n|10 - 13| = 3\nAmong all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.\nExample 2:\nInput: root = [1,null,2,null,0,3]\nOutput: 3\n Constraints:\nThe number of nodes in the tree is in the range [2, 5000].\n0 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/longest-arithmetic-subsequence/discuss/415281/Python-DP-solution", "python_solutions": "class Solution:\n def longestArithSeqLength(self, A: List[int]) -> int:\n dp = {}\n for i, a2 in enumerate(A[1:], start=1):\n for j, a1 in enumerate(A[:i]):\n d = a2 - a1\n if (j, d) in dp:\n dp[i, d] = dp[j, d] + 1\n else:\n dp[i, d] = 2\n return max(dp.values())", "slug": "longest-arithmetic-subsequence", "post_title": "Python DP solution", "user": "yasufumy", "upvotes": 53, "views": 5200, "problem_title": "longest arithmetic subsequence", "number": 1027, "acceptance": 0.47, "difficulty": "Medium", "__index_level_0__": 16805, "question": "Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.\nNote that:\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\nA sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).\n Example 1:\nInput: nums = [3,6,9,12]\nOutput: 4\nExplanation: The whole array is an arithmetic sequence with steps of length = 3.\nExample 2:\nInput: nums = [9,4,7,2,10]\nOutput: 3\nExplanation: The longest arithmetic subsequence is [4,7,10].\nExample 3:\nInput: nums = [20,1,15,3,10,5,8]\nOutput: 4\nExplanation: The longest arithmetic subsequence is [20,15,10,5].\n Constraints:\n2 <= nums.length <= 1000\n0 <= nums[i] <= 500" }, { "post_href": "https://leetcode.com/problems/recover-a-tree-from-preorder-traversal/discuss/1179506/Python3-stack", "python_solutions": "class Solution:\n def recoverFromPreorder(self, S: str) -> TreeNode:\n stack = []\n depth, val = 0, \"\"\n for i, x in enumerate(S): \n if x == \"-\": \n depth += 1\n val = \"\"\n else: \n val += S[i]\n if i+1 == len(S) or S[i+1] == \"-\": \n node = TreeNode(int(val))\n while len(stack) > depth: stack.pop()\n if stack:\n if not stack[-1].left: stack[-1].left = node\n else: stack[-1].right = node\n stack.append(node)\n depth = 0\n return stack[0]", "slug": "recover-a-tree-from-preorder-traversal", "post_title": "[Python3] stack", "user": "ye15", "upvotes": 3, "views": 116, "problem_title": "recover a tree from preorder traversal", "number": 1028, "acceptance": 0.73, "difficulty": "Hard", "__index_level_0__": 16816, "question": "We run a preorder depth-first search (DFS) on the root of a binary tree.\nAt each node in this traversal, we output D dashes (where D is the depth of this node), then we output the value of this node. If the depth of a node is D, the depth of its immediate child is D + 1. The depth of the root node is 0.\nIf a node has only one child, that child is guaranteed to be the left child.\nGiven the output traversal of this traversal, recover the tree and return its root.\n Example 1:\nInput: traversal = \"1-2--3--4-5--6--7\"\nOutput: [1,2,5,3,4,6,7]\nExample 2:\nInput: traversal = \"1-2--3---4-5--6---7\"\nOutput: [1,2,5,3,null,6,null,4,null,7]\nExample 3:\nInput: traversal = \"1-401--349---90--88\"\nOutput: [1,401,null,349,88,90]\n Constraints:\nThe number of nodes in the original tree is in the range [1, 1000].\n1 <= Node.val <= 109" }, { "post_href": "https://leetcode.com/problems/two-city-scheduling/discuss/297143/Python-faster-than-93-28-ms", "python_solutions": "class Solution(object):\n def twoCitySchedCost(self, costs):\n \"\"\"\n :type costs: List[List[int]]\n :rtype: int\n \"\"\"\n a = sorted(costs, key=lambda x: x[0]-x[1])\n Sa = 0\n Sb = 0\n for i in range(len(a)//2):\n Sa += a[i][0]\n \n for i in range(len(a)//2, len(a)):\n Sb += a[i][1]\n return Sa + Sb", "slug": "two-city-scheduling", "post_title": "Python - faster than 93%, 28 ms", "user": "il_buono", "upvotes": 17, "views": 1900, "problem_title": "two city scheduling", "number": 1029, "acceptance": 0.648, "difficulty": "Medium", "__index_level_0__": 16819, "question": "A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.\nReturn the minimum cost to fly every person to a city such that exactly n people arrive in each city.\n Example 1:\nInput: costs = [[10,20],[30,200],[400,50],[30,20]]\nOutput: 110\nExplanation: \nThe first person goes to city A for a cost of 10.\nThe second person goes to city A for a cost of 30.\nThe third person goes to city B for a cost of 50.\nThe fourth person goes to city B for a cost of 20.\n\nThe total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\nExample 2:\nInput: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\nOutput: 1859\nExample 3:\nInput: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\nOutput: 3086\n Constraints:\n2 * n == costs.length\n2 <= costs.length <= 100\ncosts.length is even.\n1 <= aCosti, bCosti <= 1000" }, { "post_href": "https://leetcode.com/problems/matrix-cells-in-distance-order/discuss/1202122/Python3-simple-solution-using-dictionary", "python_solutions": "class Solution:\n def allCellsDistOrder(self, R: int, C: int, r0: int, c0: int) -> List[List[int]]:\n d = {}\n for i in range(R):\n for j in range(C):\n d[(i,j)] = d.get((i,j),0) + abs(r0-i) + abs(c0-j)\n return [list(i) for i,j in sorted(d.items(), key = lambda x : x[1])]", "slug": "matrix-cells-in-distance-order", "post_title": "Python3 simple solution using dictionary", "user": "EklavyaJoshi", "upvotes": 3, "views": 95, "problem_title": "matrix cells in distance order", "number": 1030, "acceptance": 0.693, "difficulty": "Easy", "__index_level_0__": 16855, "question": "You are given four integers row, cols, rCenter, and cCenter. There is a rows x cols matrix and you are on the cell with the coordinates (rCenter, cCenter).\nReturn the coordinates of all cells in the matrix, sorted by their distance from (rCenter, cCenter) from the smallest distance to the largest distance. You may return the answer in any order that satisfies this condition.\nThe distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.\n Example 1:\nInput: rows = 1, cols = 2, rCenter = 0, cCenter = 0\nOutput: [[0,0],[0,1]]\nExplanation: The distances from (0, 0) to other cells are: [0,1]\nExample 2:\nInput: rows = 2, cols = 2, rCenter = 0, cCenter = 1\nOutput: [[0,1],[0,0],[1,1],[1,0]]\nExplanation: The distances from (0, 1) to other cells are: [0,1,1,2]\nThe answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.\nExample 3:\nInput: rows = 2, cols = 3, rCenter = 1, cCenter = 2\nOutput: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\nExplanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\nThere are other answers that would also be accepted as correct, such as [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]].\n Constraints:\n1 <= rows, cols <= 100\n0 <= rCenter < rows\n0 <= cCenter < cols" }, { "post_href": "https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/1012572/Python3-dp-(prefix-sum)", "python_solutions": "class Solution:\n def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:\n prefix = [0]\n for x in A: prefix.append(prefix[-1] + x) # prefix sum w/ leading 0\n ans = lmx = mmx = -inf \n for i in range(M+L, len(A)+1): \n lmx = max(lmx, prefix[i-M] - prefix[i-L-M])\n mmx = max(mmx, prefix[i-L] - prefix[i-L-M])\n ans = max(ans, lmx + prefix[i] - prefix[i-M], mmx + prefix[i] - prefix[i-L])\n return ans", "slug": "maximum-sum-of-two-non-overlapping-subarrays", "post_title": "[Python3] dp (prefix sum)", "user": "ye15", "upvotes": 3, "views": 294, "problem_title": "maximum sum of two non overlapping subarrays", "number": 1031, "acceptance": 0.595, "difficulty": "Medium", "__index_level_0__": 16869, "question": "Given an integer array nums and two integers firstLen and secondLen, return the maximum sum of elements in two non-overlapping subarrays with lengths firstLen and secondLen.\nThe array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.\nA subarray is a contiguous part of an array.\n Example 1:\nInput: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\nOutput: 20\nExplanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.\nExample 2:\nInput: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\nOutput: 29\nExplanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.\nExample 3:\nInput: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\nOutput: 31\nExplanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.\n Constraints:\n1 <= firstLen, secondLen <= 1000\n2 <= firstLen + secondLen <= 1000\nfirstLen + secondLen <= nums.length <= 1000\n0 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/moving-stones-until-consecutive/discuss/283466/Clean-Python-beats-100", "python_solutions": "class Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n x, y, z = sorted([a, b, c])\n if x + 1 == y == z - 1:\n min_steps = 0\n elif y - x > 2 and z - y > 2:\n min_steps = 2\n else:\n min_steps = 1\n max_steps = z - x - 2\n return [min_steps, max_steps]", "slug": "moving-stones-until-consecutive", "post_title": "Clean Python, beats 100%", "user": "aquafie", "upvotes": 29, "views": 1100, "problem_title": "moving stones until consecutive", "number": 1033, "acceptance": 0.457, "difficulty": "Medium", "__index_level_0__": 16877, "question": "There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.\nIn one move, you pick up a stone at an endpoint (i.e., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions x, y, and z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.\nThe game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\nReturn an integer array answer of length 2 where:\nanswer[0] is the minimum number of moves you can play, and\nanswer[1] is the maximum number of moves you can play.\n Example 1:\nInput: a = 1, b = 2, c = 5\nOutput: [1,2]\nExplanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.\nExample 2:\nInput: a = 4, b = 3, c = 2\nOutput: [0,0]\nExplanation: We cannot make any moves.\nExample 3:\nInput: a = 3, b = 5, c = 1\nOutput: [1,2]\nExplanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.\n Constraints:\n1 <= a, b, c <= 100\na, b, and c have different values." }, { "post_href": "https://leetcode.com/problems/coloring-a-border/discuss/2329163/Python-DFS-and-Border-Co-ordinates", "python_solutions": "class Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n \n rows, cols = len(grid), len(grid[0])\n border_color = grid[row][col]\n border = []\n \n\t\t# Check if a node is a border node or not\n def is_border(r, c):\n if r == 0 or r == rows - 1 or c == 0 or c == cols - 1:\n return True\n\n for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:\n nr, nc = r + dr, c + dc\n if grid[nr][nc] != border_color:\n return True\n return False \n \n def dfs(r, c):\n if r < 0 or c < 0 or r == rows or c == cols or (r, c) in visited or grid[r][c] != border_color:\n return\n visited.add((r, c))\n \n if is_border(r, c):\n border.append((r, c))\n \n dfs(r + 1, c)\n dfs(r - 1, c)\n dfs(r, c + 1)\n dfs(r, c - 1)\n \n visited = set()\n dfs(row, col)\n for r, c in border:\n grid[r][c] = color\n return grid", "slug": "coloring-a-border", "post_title": "[Python] DFS and Border Co-ordinates", "user": "tejeshreddy111", "upvotes": 0, "views": 47, "problem_title": "coloring a border", "number": 1034, "acceptance": 0.489, "difficulty": "Medium", "__index_level_0__": 16882, "question": "You are given an m x n integer matrix grid, and three integers row, col, and color. Each value in the grid represents the color of the grid square at that location.\nTwo squares are called adjacent if they are next to each other in any of the 4 directions.\nTwo squares belong to the same connected component if they have the same color and they are adjacent.\nThe border of a connected component is all the squares in the connected component that are either adjacent to (at least) a square not in the component, or on the boundary of the grid (the first or last row or column).\nYou should color the border of the connected component that contains the square grid[row][col] with color.\nReturn the final grid.\n Example 1:\nInput: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\nOutput: [[3,3],[3,2]]\nExample 2:\nInput: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\nOutput: [[1,3,3],[2,3,3]]\nExample 3:\nInput: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\nOutput: [[2,2,2],[2,1,2],[2,2,2]]\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 50\n1 <= grid[i][j], color <= 1000\n0 <= row < m\n0 <= col < n" }, { "post_href": "https://leetcode.com/problems/uncrossed-lines/discuss/1502848/Python3-or-Memoization%2BRecursion", "python_solutions": "class Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n e1=len(nums1)\n e2=len(nums2)\n @lru_cache(None,None)\n def dfs(s1,s2):\n best=-float('inf')\n if s1>=e1 or s2>=e2:\n return 0\n temp=[]\n op1=0\n\t\t\t#finding element in array2 which is equal to element in array1 from where we want to draw line\n for idx in range(s2,e2):\n if nums2[idx]==nums1[s1]:\n temp.append(idx)\n\t\t\t#drawing line to all those element and checking which gives maximum value\n for j in temp:\n op1=1+dfs(s1+1,j+1)\n best=max(op1,best)\n\t\t\t#choosing to not draw line from current element of array1\n op2=dfs(s1+1,s2)\n\t\t\t#returning max of both options.\n return max(op2,best)\n return dfs(0,0)", "slug": "uncrossed-lines", "post_title": "[Python3] | Memoization+Recursion", "user": "swapnilsingh421", "upvotes": 1, "views": 59, "problem_title": "uncrossed lines", "number": 1035, "acceptance": 0.5870000000000001, "difficulty": "Medium", "__index_level_0__": 16890, "question": "You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines.\nWe may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:\nnums1[i] == nums2[j], and\nthe line we draw does not intersect any other connecting (non-horizontal) line.\nNote that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).\nReturn the maximum number of connecting lines we can draw in this way.\n Example 1:\nInput: nums1 = [1,4,2], nums2 = [1,2,4]\nOutput: 2\nExplanation: We can draw 2 uncrossed lines as in the diagram.\nWe cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.\nExample 2:\nInput: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\nOutput: 3\nExample 3:\nInput: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\nOutput: 2\n Constraints:\n1 <= nums1.length, nums2.length <= 500\n1 <= nums1[i], nums2[j] <= 2000" }, { "post_href": "https://leetcode.com/problems/escape-a-large-maze/discuss/1292945/Python3-bfs-and-dfs", "python_solutions": "class Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n blocked = set(map(tuple, blocked))\n \n def fn(x, y, tx, ty): \n \"\"\"Return True if (x, y) is not looped from (tx, ty).\"\"\"\n seen = {(x, y)}\n queue = [(x, y)]\n level = 0 \n while queue: \n level += 1\n if level > 200: return True \n newq = []\n for x, y in queue: \n if (x, y) == (tx, ty): return True \n for xx, yy in (x-1, y), (x, y-1), (x, y+1), (x+1, y): \n if 0 <= xx < 1e6 and 0 <= yy < 1e6 and (xx, yy) not in blocked and (xx, yy) not in seen: \n seen.add((xx, yy))\n newq.append((xx, yy))\n queue = newq\n return False \n \n return fn(*source, *target) and fn(*target, *source)", "slug": "escape-a-large-maze", "post_title": "[Python3] bfs & dfs", "user": "ye15", "upvotes": 3, "views": 373, "problem_title": "escape a large maze", "number": 1036, "acceptance": 0.341, "difficulty": "Hard", "__index_level_0__": 16900, "question": "There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y).\nWe start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi).\nEach move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid.\nReturn true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.\n Example 1:\nInput: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\nOutput: false\nExplanation: The target square is inaccessible starting from the source square because we cannot move.\nWe cannot move north or east because those squares are blocked.\nWe cannot move south or west because we cannot go outside of the grid.\nExample 2:\nInput: blocked = [], source = [0,0], target = [999999,999999]\nOutput: true\nExplanation: Because there are no blocked cells, it is possible to reach the target square.\n Constraints:\n0 <= blocked.length <= 200\nblocked[i].length == 2\n0 <= xi, yi < 106\nsource.length == target.length == 2\n0 <= sx, sy, tx, ty < 106\nsource != target\nIt is guaranteed that source and target are not blocked." }, { "post_href": "https://leetcode.com/problems/valid-boomerang/discuss/1985698/Python-3-Triangle-Area", "python_solutions": "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n x1, y1 = points[0]\n x2, y2 = points[1]\n x3, y3 = points[2]\n \n area = abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))/2\n return area != 0", "slug": "valid-boomerang", "post_title": "[Python 3] Triangle Area", "user": "hari19041", "upvotes": 9, "views": 679, "problem_title": "valid boomerang", "number": 1037, "acceptance": 0.374, "difficulty": "Easy", "__index_level_0__": 16902, "question": "Given an array points where points[i] = [xi, yi] represents a point on the X-Y plane, return true if these points are a boomerang.\nA boomerang is a set of three points that are all distinct and not in a straight line.\n Example 1:\nInput: points = [[1,1],[2,3],[3,2]]\nOutput: true\nExample 2:\nInput: points = [[1,1],[2,2],[3,3]]\nOutput: false\n Constraints:\npoints.length == 3\npoints[i].length == 2\n0 <= xi, yi <= 100" }, { "post_href": "https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/discuss/1270148/Recursive-approch-99.88-accuracy-Python", "python_solutions": "class Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n s = 0\n def f(root):\n if root is None: return\n nonlocal s\n f(root.right)\n #print(s,root.val)\n s = s + root.val\n root.val = s\n f(root.left)\n f(root)\n return root", "slug": "binary-search-tree-to-greater-sum-tree", "post_title": "Recursive approch 99.88% accuracy[ Python ]", "user": "rstudy211", "upvotes": 5, "views": 238, "problem_title": "binary search tree to greater sum tree", "number": 1038, "acceptance": 0.8540000000000001, "difficulty": "Medium", "__index_level_0__": 16918, "question": "Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.\nAs a reminder, a binary search tree is a tree that satisfies these constraints:\nThe left subtree of a node contains only nodes with keys less than the node's key.\nThe right subtree of a node contains only nodes with keys greater than the node's key.\nBoth the left and right subtrees must also be binary search trees.\n Example 1:\nInput: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\nOutput: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\nExample 2:\nInput: root = [0,null,1]\nOutput: [1,null,1]\n Constraints:\nThe number of nodes in the tree is in the range [1, 100].\n0 <= Node.val <= 100\nAll the values in the tree are unique.\n Note: This question is the same as 538: https://leetcode.com/problems/convert-bst-to-greater-tree/" }, { "post_href": "https://leetcode.com/problems/minimum-score-triangulation-of-polygon/discuss/391440/Two-Solutions-in-Python-3-(DP)-(Top-Down-and-Bottom-Up)", "python_solutions": "class Solution:\n def minScoreTriangulation(self, A: List[int]) -> int:\n \tSP, LA = [[0]*50 for i in range(50)], len(A)\n \tdef MinPoly(a,b):\n \t\tL, m = b - a + 1, math.inf; \n \t\tif SP[a][b] != 0 or L < 3: return SP[a][b]\n \t\tfor i in range(a+1,b): m = min(m, A[a]*A[i]*A[b] + MinPoly(a,i) + MinPoly(i,b))\n \t\tSP[a][b] = m; return SP[a][b]\n \treturn MinPoly(0,LA-1)", "slug": "minimum-score-triangulation-of-polygon", "post_title": "Two Solutions in Python 3 (DP) (Top Down and Bottom Up)", "user": "junaidmansuri", "upvotes": 2, "views": 791, "problem_title": "minimum score triangulation of polygon", "number": 1039, "acceptance": 0.547, "difficulty": "Medium", "__index_level_0__": 16930, "question": "You have a convex n-sided polygon where each vertex has an integer value. You are given an integer array values where values[i] is the value of the ith vertex (i.e., clockwise order).\nYou will triangulate the polygon into n - 2 triangles. For each triangle, the value of that triangle is the product of the values of its vertices, and the total score of the triangulation is the sum of these values over all n - 2 triangles in the triangulation.\nReturn the smallest possible total score that you can achieve with some triangulation of the polygon.\n Example 1:\nInput: values = [1,2,3]\nOutput: 6\nExplanation: The polygon is already triangulated, and the score of the only triangle is 6.\nExample 2:\nInput: values = [3,7,4,5]\nOutput: 144\nExplanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.\nThe minimum score is 144.\nExample 3:\nInput: values = [1,3,1,4,1,5]\nOutput: 13\nExplanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.\n Constraints:\nn == values.length\n3 <= n <= 50\n1 <= values[i] <= 100" }, { "post_href": "https://leetcode.com/problems/moving-stones-until-consecutive-ii/discuss/1488487/Python-Sliding-window-with-detailed-expalanation", "python_solutions": "class Solution:\n def numMovesStonesII(self, stones: list[int]) -> list[int]:\n \"\"\"\n 1. For the higher bound, it is determined by either moving the leftmost\n to the right side, or by moving the rightmost to the left side:\n 1.1 If moving leftmost to the right side, the available moving\n positions are A[n - 1] - A[1] + 1 - (n - 1) = \n A[n - 1] - A[1] - n + 2\n 1.2 If moving rightmost to the left side, the available moving\n positions are A[n - 2] - A[0] + 1 - (n - 1) = \n A[n - 2] - A[0] - n + 2.\n 2. For the lower bound, we could use sliding window to find a window\n that contains the most consecutive stones (A[i] - A[i - 1] = 1):\n 2.1 Generally the moves we need are the same as the number of\n missing stones in the current window.\n 2.3 When the window is already consecutive and contains all the\n n - 1 stones, we need at least 2 steps to move the last stone\n into the current window. For example, 1,2,3,4,10:\n 2.3.1 We need to move 1 to 6 first as we are not allowed to\n move 10 to 5 as it will still be an endpoint stone.\n 2.3.2 Then we need to move 10 to 5 and now the window becomes\n 2,3,4,5,6.\n \"\"\"\n A, N = sorted(stones), len(stones)\n maxMoves = max(A[N - 1] - A[1] - N + 2, A[N - 2] - A[0] - N + 2)\n minMoves = N\n\n # Calculate minimum moves through sliding window.\n start = 0\n for end in range(N):\n while A[end] - A[start] + 1 > N:\n start += 1\n\n if end - start + 1 == N - 1 and A[end] - A[start] + 1 == N - 1:\n # Case: N - 1 stones with N - 1 positions.\n minMoves = min(minMoves, 2)\n else:\n minMoves = min(minMoves, N - (end - start + 1))\n\n return [minMoves, maxMoves]", "slug": "moving-stones-until-consecutive-ii", "post_title": "[Python] Sliding window with detailed expalanation", "user": "eroneko", "upvotes": 4, "views": 390, "problem_title": "moving stones until consecutive ii", "number": 1040, "acceptance": 0.557, "difficulty": "Medium", "__index_level_0__": 16936, "question": "There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones.\nCall a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.\nIn particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone.\nThe game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\nReturn an integer array answer of length 2 where:\nanswer[0] is the minimum number of moves you can play, and\nanswer[1] is the maximum number of moves you can play.\n Example 1:\nInput: stones = [7,4,9]\nOutput: [1,2]\nExplanation: We can move 4 -> 8 for one move to finish the game.\nOr, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.\nExample 2:\nInput: stones = [6,5,4,3,10]\nOutput: [2,3]\nExplanation: We can move 3 -> 8 then 10 -> 7 to finish the game.\nOr, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\nNotice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.\n Constraints:\n3 <= stones.length <= 104\n1 <= stones[i] <= 109\nAll the values of stones are unique." }, { "post_href": "https://leetcode.com/problems/robot-bounded-in-circle/discuss/1676693/Python3-Simple-4-Loops-or-O(n)-Time-or-O(1)-Space", "python_solutions": "class Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n x = y = 0\n directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]\n i = 0\n while True:\n for do in instructions:\n if do == 'G':\n x += directions[i][0]\n y += directions[i][1]\n elif do == 'R':\n i = (i + 1) % 4\n else:\n i = (i - 1) % 4\n \n if i == 0:\n return x == 0 and y == 0", "slug": "robot-bounded-in-circle", "post_title": "\u2705 [Python3] Simple 4 Loops | O(n) Time | O(1) Space", "user": "PatrickOweijane", "upvotes": 5, "views": 623, "problem_title": "robot bounded in circle", "number": 1041, "acceptance": 0.5529999999999999, "difficulty": "Medium", "__index_level_0__": 16938, "question": "On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:\nThe north direction is the positive direction of the y-axis.\nThe south direction is the negative direction of the y-axis.\nThe east direction is the positive direction of the x-axis.\nThe west direction is the negative direction of the x-axis.\nThe robot can receive one of three instructions:\n\"G\": go straight 1 unit.\n\"L\": turn 90 degrees to the left (i.e., anti-clockwise direction).\n\"R\": turn 90 degrees to the right (i.e., clockwise direction).\nThe robot performs the instructions given in order, and repeats them forever.\nReturn true if and only if there exists a circle in the plane such that the robot never leaves the circle.\n Example 1:\nInput: instructions = \"GGLLGG\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South.\n\"G\": move one step. Position: (0, 1). Direction: South.\n\"G\": move one step. Position: (0, 0). Direction: South.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\nBased on that, we return true.\nExample 2:\nInput: instructions = \"GG\"\nOutput: false\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"G\": move one step. Position: (0, 2). Direction: North.\nRepeating the instructions, keeps advancing in the north direction and does not go into cycles.\nBased on that, we return false.\nExample 3:\nInput: instructions = \"GL\"\nOutput: true\nExplanation: The robot is initially at (0, 0) facing the north direction.\n\"G\": move one step. Position: (0, 1). Direction: North.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West.\n\"G\": move one step. Position: (-1, 1). Direction: West.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South.\n\"G\": move one step. Position: (-1, 0). Direction: South.\n\"L\": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East.\n\"G\": move one step. Position: (0, 0). Direction: East.\n\"L\": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North.\nRepeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\nBased on that, we return true.\n Constraints:\n1 <= instructions.length <= 100\ninstructions[i] is 'G', 'L' or, 'R'." }, { "post_href": "https://leetcode.com/problems/flower-planting-with-no-adjacent/discuss/557619/**Python-Simple-DFS-solution-70-80-**", "python_solutions": "class Solution:\n def gardenNoAdj(self, N: int, paths: List[List[int]]) -> List[int]:\n G = defaultdict(list)\n for path in paths:\n G[path[0]].append(path[1])\n G[path[1]].append((path[0]))\n colored = defaultdict()\n\n def dfs(G, V, colored):\n colors = [1, 2, 3, 4]\n for neighbour in G[V]:\n if neighbour in colored:\n if colored[neighbour] in colors:\n colors.remove(colored[neighbour])\n colored[V] = colors[0]\n\n for V in range(1, N + 1):\n dfs(G, V, colored)\n\n ans = []\n for V in range(len(colored)):\n ans.append(colored[V + 1])\n\n return ans", "slug": "flower-planting-with-no-adjacent", "post_title": "**Python Simple DFS solution 70 - 80 %**", "user": "art35part2", "upvotes": 6, "views": 846, "problem_title": "flower planting with no adjacent", "number": 1042, "acceptance": 0.504, "difficulty": "Medium", "__index_level_0__": 16965, "question": "You have n gardens, labeled from 1 to n, and an array paths where paths[i] = [xi, yi] describes a bidirectional path between garden xi to garden yi. In each garden, you want to plant one of 4 types of flowers.\nAll gardens have at most 3 paths coming into or leaving it.\nYour task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers.\nReturn any such a choice as an array answer, where answer[i] is the type of flower planted in the (i+1)th garden. The flower types are denoted 1, 2, 3, or 4. It is guaranteed an answer exists.\n Example 1:\nInput: n = 3, paths = [[1,2],[2,3],[3,1]]\nOutput: [1,2,3]\nExplanation:\nGardens 1 and 2 have different types.\nGardens 2 and 3 have different types.\nGardens 3 and 1 have different types.\nHence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].\nExample 2:\nInput: n = 4, paths = [[1,2],[3,4]]\nOutput: [1,2,1,2]\nExample 3:\nInput: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]\nOutput: [1,2,3,4]\n Constraints:\n1 <= n <= 104\n0 <= paths.length <= 2 * 104\npaths[i].length == 2\n1 <= xi, yi <= n\nxi != yi\nEvery garden has at most 3 paths coming into or leaving it." }, { "post_href": "https://leetcode.com/problems/partition-array-for-maximum-sum/discuss/1621079/Python-Easy-DP-with-Visualization-and-examples", "python_solutions": "class Solution:\n def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:\n n = len(arr)\n dp = [0]*n\n \n # handle the first k indexes differently\n for j in range(k): dp[j]=max(arr[:j+1])*(j+1)\n \n # we can get rid of index i by running i times\n for j in range(k,n):\n curr = []\n for m in range(k):\n curr.append(dp[j-m-1] + max(arr[(j-m):(j+1)]) * (m+1))\n dp[j] = max(curr)\n\n return dp[-1]", "slug": "partition-array-for-maximum-sum", "post_title": "[Python] Easy DP with Visualization and examples", "user": "sashaxx", "upvotes": 56, "views": 1300, "problem_title": "partition array for maximum sum", "number": 1043, "acceptance": 0.7120000000000001, "difficulty": "Medium", "__index_level_0__": 16972, "question": "Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.\nReturn the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\nInput: arr = [1,15,7,9,2,5,10], k = 3\nOutput: 84\nExplanation: arr becomes [15,15,15,9,10,10,10]\nExample 2:\nInput: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\nOutput: 83\nExample 3:\nInput: arr = [1], k = 1\nOutput: 1\n Constraints:\n1 <= arr.length <= 500\n0 <= arr[i] <= 109\n1 <= k <= arr.length" }, { "post_href": "https://leetcode.com/problems/longest-duplicate-substring/discuss/2806471/Python-Easy-or-Simple-or-Binary-Solution", "python_solutions": "class Solution:\n def longestDupSubstring(self, s: str) -> str:\n length = len(s)\n l,r = 0, length-1 \n result = []\n while l int:\n stones.sort()\n while stones:\n s1 = stones.pop() # the heaviest stone\n if not stones: # s1 is the remaining stone\n return s1\n s2 = stones.pop() # the second-heaviest stone; s2 <= s1\n if s1 > s2:\n # we need to insert the remaining stone (s1-s2) into the list\n pass\n # else s1 == s2; both stones are destroyed\n return 0 # if no more stones remain", "slug": "last-stone-weight", "post_title": "[Python] Beginner-friendly Optimisation Process with Explanation", "user": "zayne-siew", "upvotes": 91, "views": 5800, "problem_title": "last stone weight", "number": 1046, "acceptance": 0.647, "difficulty": "Easy", "__index_level_0__": 16988, "question": "You are given an array of integers stones where stones[i] is the weight of the ith stone.\nWe are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:\nIf x == y, both stones are destroyed, and\nIf x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.\nAt the end of the game, there is at most one stone left.\nReturn the weight of the last remaining stone. If there are no stones left, return 0.\n Example 1:\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation: \nWe combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\nwe combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\nwe combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\nwe combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.\nExample 2:\nInput: stones = [1]\nOutput: 1\n Constraints:\n1 <= stones.length <= 30\n1 <= stones[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/1291694/Easy-Python-Solution(89.05)", "python_solutions": "class Solution:\n def removeDuplicates(self, s: str) -> str:\n stack=[s[0]]\n for i in range(1,len(s)):\n if(stack and stack[-1]==s[i]):\n stack.pop()\n else:\n stack.append(s[i])\n return \"\".join(stack)", "slug": "remove-all-adjacent-duplicates-in-string", "post_title": "Easy Python Solution(89.05%)", "user": "Sneh17029", "upvotes": 11, "views": 807, "problem_title": "remove all adjacent duplicates in string", "number": 1047, "acceptance": 0.703, "difficulty": "Easy", "__index_level_0__": 17023, "question": "You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.\nWe repeatedly make duplicate removals on s until we no longer can.\nReturn the final string after all such duplicate removals have been made. It can be proven that the answer is unique.\n Example 1:\nInput: s = \"abbaca\"\nOutput: \"ca\"\nExplanation: \nFor example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".\nExample 2:\nInput: s = \"azxxzy\"\nOutput: \"ay\"\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/longest-string-chain/discuss/2152864/PYTHON-oror-EXPLAINED-oror", "python_solutions": "class Solution:\n def longestStrChain(self, words: List[str]) -> int:\n \n words.sort(key=len)\n dic = {}\n \n for i in words:\n dic[ i ] = 1\n \n for j in range(len(i)):\n \n # creating words by deleting a letter\n successor = i[:j] + i[j+1:]\n if successor in dic:\n dic[ i ] = max (dic[i], 1 + dic[successor])\n \n res = max(dic.values())\n return res", "slug": "longest-string-chain", "post_title": "\u2714\ufe0f PYTHON || EXPLAINED || ;]", "user": "karan_8082", "upvotes": 27, "views": 1500, "problem_title": "longest string chain", "number": 1048, "acceptance": 0.591, "difficulty": "Medium", "__index_level_0__": 17083, "question": "You are given an array of words where each word consists of lowercase English letters.\nwordA is a predecessor of wordB if and only if we can insert exactly one letter anywhere in wordA without changing the order of the other characters to make it equal to wordB.\nFor example, \"abc\" is a predecessor of \"abac\", while \"cba\" is not a predecessor of \"bcad\".\nA word chain is a sequence of words [word1, word2, ..., wordk] with k >= 1, where word1 is a predecessor of word2, word2 is a predecessor of word3, and so on. A single word is trivially a word chain with k == 1.\nReturn the length of the longest possible word chain with words chosen from the given list of words.\n Example 1:\nInput: words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\nOutput: 4\nExplanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].\nExample 2:\nInput: words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\nOutput: 5\nExplanation: All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].\nExample 3:\nInput: words = [\"abcd\",\"dbqca\"]\nOutput: 1\nExplanation: The trivial word chain [\"abcd\"] is one of the longest word chains.\n[\"abcd\",\"dbqca\"] is not a valid word chain because the ordering of the letters is changed.\n Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length <= 16\nwords[i] only consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/last-stone-weight-ii/discuss/1013873/Python3-top-down-dp", "python_solutions": "class Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n \n @lru_cache(None)\n def fn(i, v): \n \"\"\"Return minimum weight of stones[i:] given existing weight.\"\"\"\n if i == len(stones): return abs(v)\n return min(fn(i+1, v - stones[i]), fn(i+1, v + stones[i]))\n \n return fn(0, 0)", "slug": "last-stone-weight-ii", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 153, "problem_title": "last stone weight ii", "number": 1049, "acceptance": 0.526, "difficulty": "Medium", "__index_level_0__": 17126, "question": "You are given an array of integers stones where stones[i] is the weight of the ith stone.\nWe are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:\nIf x == y, both stones are destroyed, and\nIf x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.\nAt the end of the game, there is at most one stone left.\nReturn the smallest possible weight of the left stone. If there are no stones left, return 0.\n Example 1:\nInput: stones = [2,7,4,1,8,1]\nOutput: 1\nExplanation:\nWe can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,\nwe can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,\nwe can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,\nwe can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.\nExample 2:\nInput: stones = [31,26,33,21,40]\nOutput: 5\n Constraints:\n1 <= stones.length <= 30\n1 <= stones[i] <= 100" }, { "post_href": "https://leetcode.com/problems/height-checker/discuss/429670/Python-3-O(n)-Faster-than-100-Memory-usage-less-than-100", "python_solutions": "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n \n max_val = max(heights)\n \n # Create frequency table\n freq = [0] * (max_val + 1)\n for num in heights: freq[num] += 1\n for num in range(1, len(freq)): freq[num] += freq[num-1]\n\n # Create places table\n places = [0] * len(heights)\n for num in heights:\n places[freq[num]-1] = num\n freq[num] -= 1\n\n return sum([a!=b for a, b in zip(heights, places)])", "slug": "height-checker", "post_title": "Python 3 - O(n) - Faster than 100%, Memory usage less than 100%", "user": "mmbhatk", "upvotes": 24, "views": 4800, "problem_title": "height checker", "number": 1051, "acceptance": 0.7509999999999999, "difficulty": "Easy", "__index_level_0__": 17132, "question": "A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line.\nYou are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed).\nReturn the number of indices where heights[i] != expected[i].\n Example 1:\nInput: heights = [1,1,4,2,1,3]\nOutput: 3\nExplanation: \nheights: [1,1,4,2,1,3]\nexpected: [1,1,1,2,3,4]\nIndices 2, 4, and 5 do not match.\nExample 2:\nInput: heights = [5,1,2,3,4]\nOutput: 5\nExplanation:\nheights: [5,1,2,3,4]\nexpected: [1,2,3,4,5]\nAll indices do not match.\nExample 3:\nInput: heights = [1,2,3,4,5]\nOutput: 0\nExplanation:\nheights: [1,2,3,4,5]\nexpected: [1,2,3,4,5]\nAll indices match.\n Constraints:\n1 <= heights.length <= 100\n1 <= heights[i] <= 100" }, { "post_href": "https://leetcode.com/problems/grumpy-bookstore-owner/discuss/441491/Python-(97)-Easy-to-understand-Sliding-Window-with-comments", "python_solutions": "class Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:\n # a sliding window approach\n currsum = 0\n # first store the sum as if the owner has no super power\n for i in range(len(grumpy)):\n if not grumpy[i]:\n currsum += customers[i]\n \n # now assuming he has the power, take the first window \n # and add to the previous sum\n for i in range(X):\n if grumpy[i]:\n currsum += customers[i]\n \n maxsum = currsum\n \n # Now the sliding window starts\n # i and j are the two opposite ends of the window\n i = 0\n j = X\n while j < len(customers):\n if grumpy[j]:\n currsum += customers[j]\n if grumpy[i]:\n currsum -= customers[i]\n\t\t\t# we subtract above as the window has already passed over that customer\n if currsum > maxsum:\n maxsum = currsum\n i += 1\n j += 1\n return maxsum", "slug": "grumpy-bookstore-owner", "post_title": "Python (97%) - Easy to understand Sliding Window with comments", "user": "vdhyani96", "upvotes": 3, "views": 315, "problem_title": "grumpy bookstore owner", "number": 1052, "acceptance": 0.5710000000000001, "difficulty": "Medium", "__index_level_0__": 17167, "question": "There is a bookstore owner that has a store open for n minutes. Every minute, some number of customers enter the store. You are given an integer array customers of length n where customers[i] is the number of the customer that enters the store at the start of the ith minute and all those customers leave after the end of that minute.\nOn some minutes, the bookstore owner is grumpy. You are given a binary array grumpy where grumpy[i] is 1 if the bookstore owner is grumpy during the ith minute, and is 0 otherwise.\nWhen the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.\nThe bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.\nReturn the maximum number of customers that can be satisfied throughout the day.\n Example 1:\nInput: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\nOutput: 16\nExplanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. \nThe maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.\nExample 2:\nInput: customers = [1], grumpy = [0], minutes = 1\nOutput: 1\n Constraints:\nn == customers.length == grumpy.length\n1 <= minutes <= n <= 2 * 104\n0 <= customers[i] <= 1000\ngrumpy[i] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/previous-permutation-with-one-swap/discuss/1646525/python-O(n)-time-O(1)-space-with-explanation", "python_solutions": "class Solution:\n\t def prevPermOpt1(self, nums: List[int]) -> List[int]:\n\t\tn = len(nums)-1\n\t\tleft = n\n\n // find first non-decreasing number\n while left >= 0 and nums[left] >= nums[left-1]:\n left -= 1\n \n\t// if this hits, it means we have the smallest possible perm \n if left <= 0:\n return nums\n\t\n\t// the while loop above lands us at +1, so k is the actual value\n k = left - 1\n \n // find the largest number that's smaller than k \n // while skipping duplicates\n right = n\n while right >= left:\n if nums[right] < nums[k] and nums[right] != nums[right-1]:\n nums[k], nums[right] = nums[right], nums[k]\n return nums\n \n right -= 1\n \n return nums", "slug": "previous-permutation-with-one-swap", "post_title": "python O(n) time, O(1) space with explanation", "user": "uzumaki01", "upvotes": 3, "views": 322, "problem_title": "previous permutation with one swap", "number": 1053, "acceptance": 0.508, "difficulty": "Medium", "__index_level_0__": 17182, "question": "Given an array of positive integers arr (not necessarily distinct), return the\nlexicographically\nlargest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array.\nNote that a swap exchanges the positions of two numbers arr[i] and arr[j]\n Example 1:\nInput: arr = [3,2,1]\nOutput: [3,1,2]\nExplanation: Swapping 2 and 1.\nExample 2:\nInput: arr = [1,1,5]\nOutput: [1,1,5]\nExplanation: This is already the smallest permutation.\nExample 3:\nInput: arr = [1,9,4,6,7]\nOutput: [1,7,4,6,9]\nExplanation: Swapping 9 and 7.\n Constraints:\n1 <= arr.length <= 104\n1 <= arr[i] <= 104" }, { "post_href": "https://leetcode.com/problems/distant-barcodes/discuss/411386/Two-Solutions-in-Python-3-(six-lines)-(beats-~95)", "python_solutions": "class Solution:\n def rearrangeBarcodes(self, B: List[int]) -> List[int]:\n L, A, i = len(B), [0]*len(B), 0\n for k,v in collections.Counter(B).most_common():\n for _ in range(v):\n A[i], i = k, i + 2\n if i >= L: i = 1\n return A\n\n\n\nclass Solution:\n def rearrangeBarcodes(self, B: List[int]) -> List[int]:\n L, C = len(B), collections.Counter(B)\n B.sort(key = lambda x: (C[x],x))\n B[1::2], B[::2] = B[:L//2], B[L//2:]\n return B\n\t\t\n\t\t\n- Junaid Mansuri", "slug": "distant-barcodes", "post_title": "Two Solutions in Python 3 (six lines) (beats ~95%)", "user": "junaidmansuri", "upvotes": 5, "views": 755, "problem_title": "distant barcodes", "number": 1054, "acceptance": 0.457, "difficulty": "Medium", "__index_level_0__": 17186, "question": "In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].\nRearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.\n Example 1:\nInput: barcodes = [1,1,1,2,2,2]\nOutput: [2,1,2,1,2,1]\nExample 2:\nInput: barcodes = [1,1,1,1,2,2,3,3]\nOutput: [1,3,1,3,1,2,1,2]\n Constraints:\n1 <= barcodes.length <= 10000\n1 <= barcodes[i] <= 10000" }, { "post_href": "https://leetcode.com/problems/greatest-common-divisor-of-strings/discuss/860984/Python-3-or-GCD-1-liner-or-Explanation", "python_solutions": "class Solution:\n def gcdOfStrings(self, s1: str, s2: str) -> str:\n return s1[:math.gcd(len(s1), len(s2))] if s1 + s2 == s2 + s1 else ''", "slug": "greatest-common-divisor-of-strings", "post_title": "Python 3 | GCD 1-liner | Explanation", "user": "idontknoooo", "upvotes": 61, "views": 3500, "problem_title": "greatest common divisor of strings", "number": 1071, "acceptance": 0.511, "difficulty": "Easy", "__index_level_0__": 17191, "question": "For two strings s and t, we say \"t divides s\" if and only if s = t + t + t + ... + t + t (i.e., t is concatenated with itself one or more times).\nGiven two strings str1 and str2, return the largest string x such that x divides both str1 and str2.\n Example 1:\nInput: str1 = \"ABCABC\", str2 = \"ABC\"\nOutput: \"ABC\"\nExample 2:\nInput: str1 = \"ABABAB\", str2 = \"ABAB\"\nOutput: \"AB\"\nExample 3:\nInput: str1 = \"LEET\", str2 = \"CODE\"\nOutput: \"\"\n Constraints:\n1 <= str1.length, str2.length <= 1000\nstr1 and str2 consist of English uppercase letters." }, { "post_href": "https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/discuss/1440662/97-faster-oror-Well-Explained-with-example-oror-Easy-Approach", "python_solutions": "class Solution:\ndef maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n \n dic = defaultdict(int)\n for row in matrix:\n local=[]\n for c in row:\n local.append(c^row[0])\n dic[tuple(local)]+=1\n \n return max(dic.values())", "slug": "flip-columns-for-maximum-number-of-equal-rows", "post_title": "\ud83d\udc0d 97% faster || Well-Explained with example || Easy-Approach \ud83d\udccc\ud83d\udccc", "user": "abhi9Rai", "upvotes": 1, "views": 199, "problem_title": "flip columns for maximum number of equal rows", "number": 1072, "acceptance": 0.63, "difficulty": "Medium", "__index_level_0__": 17204, "question": "You are given an m x n binary matrix matrix.\nYou can choose any number of columns in the matrix and flip every cell in that column (i.e., Change the value of the cell from 0 to 1 or vice versa).\nReturn the maximum number of rows that have all values equal after some number of flips.\n Example 1:\nInput: matrix = [[0,1],[1,1]]\nOutput: 1\nExplanation: After flipping no values, 1 row has all values equal.\nExample 2:\nInput: matrix = [[0,1],[1,0]]\nOutput: 2\nExplanation: After flipping values in the first column, both rows have equal values.\nExample 3:\nInput: matrix = [[0,0,0],[0,0,1],[1,1,0]]\nOutput: 2\nExplanation: After flipping values in the first two columns, the last two rows have equal values.\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 300\nmatrix[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/adding-two-negabinary-numbers/discuss/1384126/Python-3-or-Math-Two-Pointers-or-Explanation", "python_solutions": "class Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n ans = list()\n m, n = len(arr1), len(arr2)\n i, j = m-1, n-1\n def add(a, b): # A helper function to add -2 based numbers\n if a == 1 and b == 1:\n cur, carry = 0, -1\n elif (a == -1 and b == 0) or (a == 0 and b == -1): \n cur = carry = 1\n else: \n cur, carry = a+b, 0\n return cur, carry # Return current value and carry\n carry = 0\n while i >= 0 or j >= 0: # Two pointers from right side\n cur, carry_1, carry_2 = carry, 0, 0\n if i >= 0:\n cur, carry_1 = add(cur, arr1[i])\n if j >= 0: \n cur, carry_2 = add(cur, arr2[j])\n carry = carry_1 + carry_2\n ans.append(cur)\n i, j = i-1, j-1\n ans = [1,1] + ans[::-1] if carry == -1 else ans[::-1] # Add [1, 1] if there is a carry -1 leftover\n for i, v in enumerate(ans): # Remove leading zero and return\n if v == 1:\n return ans[i:]\n else:\n return [0]", "slug": "adding-two-negabinary-numbers", "post_title": "Python 3 | Math, Two Pointers | Explanation", "user": "idontknoooo", "upvotes": 2, "views": 558, "problem_title": "adding two negabinary numbers", "number": 1073, "acceptance": 0.364, "difficulty": "Medium", "__index_level_0__": 17210, "question": "Given two numbers arr1 and arr2 in base -2, return the result of adding them together.\nEach number is given in array format: as an array of 0s and 1s, from most significant bit to least significant bit. For example, arr = [1,1,0,1] represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3. A number arr in array, format is also guaranteed to have no leading zeros: either arr == [0] or arr[0] == 1.\nReturn the result of adding arr1 and arr2 in the same format: as an array of 0s and 1s with no leading zeros.\n Example 1:\nInput: arr1 = [1,1,1,1,1], arr2 = [1,0,1]\nOutput: [1,0,0,0,0]\nExplanation: arr1 represents 11, arr2 represents 5, the output represents 16.\nExample 2:\nInput: arr1 = [0], arr2 = [0]\nOutput: [0]\nExample 3:\nInput: arr1 = [0], arr2 = [1]\nOutput: [1]\n Constraints:\n1 <= arr1.length, arr2.length <= 1000\narr1[i] and arr2[i] are 0 or 1\narr1 and arr2 have no leading zeros" }, { "post_href": "https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/discuss/2118388/or-PYTHON-SOL-or-EASY-or-EXPLAINED-or-VERY-SIMPLE-or-COMMENTED-or", "python_solutions": "class Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n # find the rows and columns of the matrix\n n,m = len(matrix) , len(matrix[0])\n # find the prefix sum for each row\n for i in range(n):\n for j in range(1,m):\n matrix[i][j] += matrix[i][j-1]\n ans = 0\n # fix the left boundary of the column\n for start in range(m):\n # fix the right boundary of the column\n for end in range(start,m):\n # a dictionary to map data\n d = defaultdict(lambda:0)\n d[0] = 1\n summ = 0\n # now we do check at each row\n for i in range(n):\n curr = matrix[i][end]\n if start > 0: curr -= matrix[i][start-1]\n summ += curr\n ans += d[summ - target]\n d[summ] += 1\n return ans", "slug": "number-of-submatrices-that-sum-to-target", "post_title": "| PYTHON SOL | EASY | EXPLAINED | VERY SIMPLE | COMMENTED |", "user": "reaper_27", "upvotes": 1, "views": 203, "problem_title": "number of submatrices that sum to target", "number": 1074, "acceptance": 0.698, "difficulty": "Hard", "__index_level_0__": 17215, "question": "Given a matrix and a target, return the number of non-empty submatrices that sum to target.\nA submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.\nTwo submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.\n Example 1:\nInput: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\nOutput: 4\nExplanation: The four 1x1 submatrices that only contain 0.\nExample 2:\nInput: matrix = [[1,-1],[-1,1]], target = 0\nOutput: 5\nExplanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\nExample 3:\nInput: matrix = [[904]], target = 0\nOutput: 0\n Constraints:\n1 <= matrix.length <= 100\n1 <= matrix[0].length <= 100\n-1000 <= matrix[i][j] <= 1000\n-10^8 <= target <= 10^8" }, { "post_href": "https://leetcode.com/problems/occurrences-after-bigram/discuss/1443810/Using-stack-for-words-93-speed", "python_solutions": "class Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n ans, stack = [], []\n for w in text.split():\n if len(stack) > 1 and stack[-2] == first and stack[-1] == second:\n ans.append(w)\n stack.append(w)\n return ans", "slug": "occurrences-after-bigram", "post_title": "Using stack for words, 93% speed", "user": "EvgenySH", "upvotes": 2, "views": 99, "problem_title": "occurrences after bigram", "number": 1078, "acceptance": 0.638, "difficulty": "Easy", "__index_level_0__": 17223, "question": "Given two strings first and second, consider occurrences in some text of the form \"first second third\", where second comes immediately after first, and third comes immediately after second.\nReturn an array of all the words third for each occurrence of \"first second third\".\n Example 1:\nInput: text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"\nOutput: [\"girl\",\"student\"]\nExample 2:\nInput: text = \"we will we will rock you\", first = \"we\", second = \"will\"\nOutput: [\"we\",\"rock\"]\n Constraints:\n1 <= text.length <= 1000\ntext consists of lowercase English letters and spaces.\nAll the words in text a separated by a single space.\n1 <= first.length, second.length <= 10\nfirst and second consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/letter-tile-possibilities/discuss/774815/Python-3-Backtracking-(no-set-no-itertools-simple-DFS-count)-with-explanation", "python_solutions": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n record = [0] * 26\n for tile in tiles: record[ord(tile)-ord('A')] += 1\n def dfs(record):\n s = 0\n for i in range(26):\n if not record[i]: continue\n record[i] -= 1\n s += dfs(record) + 1 \n record[i] += 1\n return s \n return dfs(record)", "slug": "letter-tile-possibilities", "post_title": "Python 3 Backtracking (no set, no itertools, simple DFS count) with explanation", "user": "idontknoooo", "upvotes": 21, "views": 1500, "problem_title": "letter tile possibilities", "number": 1079, "acceptance": 0.7609999999999999, "difficulty": "Medium", "__index_level_0__": 17240, "question": "You have n tiles, where each tile has one letter tiles[i] printed on it.\nReturn the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n Example 1:\nInput: tiles = \"AAB\"\nOutput: 8\nExplanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\nExample 2:\nInput: tiles = \"AAABBC\"\nOutput: 188\nExample 3:\nInput: tiles = \"V\"\nOutput: 1\n Constraints:\n1 <= tiles.length <= 7\ntiles consists of uppercase English letters." }, { "post_href": "https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/discuss/1350913/Simple-Python-Solution-or-O(N)-or-DFS", "python_solutions": "class Solution:\n def sufficientSubset(self, root: TreeNode, limit: int, pathSum = 0) -> TreeNode:\n if not root: return None\n if not root.left and not root.right:\n if pathSum + root.val < limit:\n return None\n return root\n root.left = self.sufficientSubset(root.left, limit, pathSum + root.val)\n root.right = self.sufficientSubset(root.right, limit, pathSum + root.val)\n if not root.left and not root.right:\n return None\n return root", "slug": "insufficient-nodes-in-root-to-leaf-paths", "post_title": "Simple Python Solution | O(N) | DFS", "user": "Astomak", "upvotes": 2, "views": 192, "problem_title": "insufficient nodes in root to leaf paths", "number": 1080, "acceptance": 0.53, "difficulty": "Medium", "__index_level_0__": 17256, "question": "Given the root of a binary tree and an integer limit, delete all insufficient nodes in the tree simultaneously, and return the root of the resulting binary tree.\nA node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.\nA leaf is a node with no children.\n Example 1:\nInput: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\nOutput: [1,2,3,4,null,null,7,8,9,null,14]\nExample 2:\nInput: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\nOutput: [5,4,8,11,null,17,4,7,null,null,null,5]\nExample 3:\nInput: root = [1,2,-3,-5,null,4,null], limit = -1\nOutput: [1,null,-3,4]\n Constraints:\nThe number of nodes in the tree is in the range [1, 5000].\n-105 <= Node.val <= 105\n-109 <= limit <= 109" }, { "post_href": "https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/894588/Python3-stack-O(N)", "python_solutions": "class Solution:\n def smallestSubsequence(self, s: str) -> str:\n loc = {x: i for i, x in enumerate(s)}\n stack = []\n for i, x in enumerate(s): \n if x not in stack: \n while stack and x < stack[-1] and i < loc[stack[-1]]: stack.pop()\n stack.append(x)\n return \"\".join(stack)", "slug": "smallest-subsequence-of-distinct-characters", "post_title": "[Python3] stack O(N)", "user": "ye15", "upvotes": 2, "views": 246, "problem_title": "smallest subsequence of distinct characters", "number": 1081, "acceptance": 0.575, "difficulty": "Medium", "__index_level_0__": 17262, "question": "Given a string s, return the\nlexicographically smallest\nsubsequence\nof s that contains all the distinct characters of s exactly once.\n Example 1:\nInput: s = \"bcabc\"\nOutput: \"abc\"\nExample 2:\nInput: s = \"cbacdcbc\"\nOutput: \"acdb\"\n Constraints:\n1 <= s.length <= 1000\ns consists of lowercase English letters.\n Note: This question is the same as 316: https://leetcode.com/problems/remove-duplicate-letters/" }, { "post_href": "https://leetcode.com/problems/duplicate-zeros/discuss/408059/Python-Simple-Solution", "python_solutions": "class Solution:\n\tdef duplicateZeros(self, arr: List[int]) -> None:\n\t\ti = 0\n\t\tn = len(arr)\n\t\twhile(i int:\n ans = 0\n freq = {}\n for value, label in sorted(zip(values, labels), reverse=True):\n if freq.get(label, 0) < use_limit: \n ans += value\n num_wanted -= 1\n if not num_wanted: break \n freq[label] = 1 + freq.get(label, 0)\n return ans", "slug": "largest-values-from-labels", "post_title": "[Python3] greedy O(NlogN)", "user": "ye15", "upvotes": 2, "views": 161, "problem_title": "largest values from labels", "number": 1090, "acceptance": 0.609, "difficulty": "Medium", "__index_level_0__": 17321, "question": "There is a set of n items. You are given two integer arrays values and labels where the value and the label of the ith element are values[i] and labels[i] respectively. You are also given two integers numWanted and useLimit.\nChoose a subset s of the n elements such that:\nThe size of the subset s is less than or equal to numWanted.\nThere are at most useLimit items with the same label in s.\nThe score of a subset is the sum of the values in the subset.\nReturn the maximum score of a subset s.\n Example 1:\nInput: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\nOutput: 9\nExplanation: The subset chosen is the first, third, and fifth items.\nExample 2:\nInput: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\nOutput: 12\nExplanation: The subset chosen is the first, second, and third items.\nExample 3:\nInput: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\nOutput: 16\nExplanation: The subset chosen is the first and fourth items.\n Constraints:\nn == values.length == labels.length\n1 <= n <= 2 * 104\n0 <= values[i], labels[i] <= 2 * 104\n1 <= numWanted, useLimit <= n" }, { "post_href": "https://leetcode.com/problems/shortest-path-in-binary-matrix/discuss/2043228/Python-Simple-BFS-with-Explanation", "python_solutions": "class Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n # check if source and target are not clear cells\n if grid[0][0] != 0 or grid[-1][-1] != 0:\n return -1\n \n N = len(grid) \n # offsets required for all 8 directions\n offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n \n q = deque()\n q.append((0,0)) # starting point\n visited = {(0, 0)}\n \n \n # finds unvisited clear cells using 8 offsets\n def get_neighbours(x,y):\n for x_offset, y_offset in offsets:\n new_row = x + x_offset\n new_col = y + y_offset\n \n if 0 <= new_row < N and 0 <= new_col < N and not grid[new_row][new_col] and (new_row, new_col) not in visited:\n yield (new_row, new_col) \n \n \n current_distance = 1 # start with one clear cell\n # standard iterative BFS traversal\n while q:\n length = len(q)\n \n # loop through all the cells at the same distance\n for _ in range(length):\n row, col = q.popleft()\n \n if row == N-1 and col==N-1: # reached target\n return current_distance\n \n # loop though all valid neignbours\n for p in get_neighbours(row, col):\n visited.add(p)\n q.append(p)\n \n current_distance+=1 # update the level or distance from source\n \n return -1", "slug": "shortest-path-in-binary-matrix", "post_title": "\u2705 Python Simple BFS with Explanation", "user": "constantine786", "upvotes": 15, "views": 1800, "problem_title": "shortest path in binary matrix", "number": 1091, "acceptance": 0.445, "difficulty": "Medium", "__index_level_0__": 17329, "question": "Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.\nA clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:\nAll the visited cells of the path are 0.\nAll the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).\nThe length of a clear path is the number of visited cells of this path.\n Example 1:\nInput: grid = [[0,1],[1,0]]\nOutput: 2\nExample 2:\nInput: grid = [[0,0,0],[1,1,0],[1,1,0]]\nOutput: 4\nExample 3:\nInput: grid = [[1,0,0],[1,1,0],[1,1,0]]\nOutput: -1\n Constraints:\nn == grid.length\nn == grid[i].length\n1 <= n <= 100\ngrid[i][j] is 0 or 1" }, { "post_href": "https://leetcode.com/problems/shortest-common-supersequence/discuss/786544/Simple-Python-Accepted-Solution-using-LCS-implementation-faster-than-83-python-users", "python_solutions": "class Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n n,m = len(str1),len(str2)\n dp = [[0 for j in range(m+1)]for i in range(n+1)]\n for i in range(1,n+1):\n for j in range(1,m+1):\n if str1[i-1] == str2[j-1]:\n dp[i][j] = 1+dp[i-1][j-1]\n else:\n dp[i][j] = max(dp[i-1][j],dp[i][j-1])\n i,j = n,m\n ans = \"\"\n while(i>0 and j>0):\n if str1[i-1] == str2[j-1]:\n ans += str1[i-1]\n i -= 1\n j -= 1\n else:\n if(dp[i-1][j] > dp[i][j-1]):\n ans += str1[i-1]\n i -= 1\n else:\n ans += str2[j-1]\n j -= 1\n while(i>0):\n ans += str1[i-1]\n i -= 1\n while(j>0):\n ans += str2[j-1]\n j -= 1\n return ans[::-1]", "slug": "shortest-common-supersequence", "post_title": "Simple Python Accepted Solution using LCS implementation faster than 83% python users", "user": "theflash007", "upvotes": 7, "views": 323, "problem_title": "shortest common supersequence", "number": 1092, "acceptance": 0.578, "difficulty": "Hard", "__index_level_0__": 17363, "question": "Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.\nA string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.\n Example 1:\nInput: str1 = \"abac\", str2 = \"cab\"\nOutput: \"cabac\"\nExplanation: \nstr1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\nstr2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\nThe answer provided is the shortest such string that satisfies these properties.\nExample 2:\nInput: str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\nOutput: \"aaaaaaaa\"\n Constraints:\n1 <= str1.length, str2.length <= 1000\nstr1 and str2 consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/statistics-from-a-large-sample/discuss/1653119/Python3-one-liner", "python_solutions": "class Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n return [\n #Minimum\n min(i for i,c in enumerate(count) if c != 0),\n #Maximum\n max(i for i,c in enumerate(count) if c != 0),\n #Mean\n sum(i*c for i,c in enumerate(count)) / sum(c for c in count if c != 0),\n #Media\n (lambda total:\n (\n next(i for i,s in enumerate(itertools.accumulate(count)) if s >= total//2+1)+\n next(i for i,s in enumerate(itertools.accumulate(count)) if s >= total//2+total%2)\n )/2\n )(sum(c for c in count if c != 0)),\n #Mode\n max(((i,c) for i,c in enumerate(count) if c != 0),key=(lambda x: x[1]))[0]\n ]", "slug": "statistics-from-a-large-sample", "post_title": "Python3 one-liner", "user": "pknoe3lh", "upvotes": 0, "views": 179, "problem_title": "statistics from a large sample", "number": 1093, "acceptance": 0.444, "difficulty": "Medium", "__index_level_0__": 17381, "question": "You are given a large sample of integers in the range [0, 255]. Since the sample is so large, it is represented by an array count where count[k] is the number of times that k appears in the sample.\nCalculate the following statistics:\nminimum: The minimum element in the sample.\nmaximum: The maximum element in the sample.\nmean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.\nmedian:\nIf the sample has an odd number of elements, then the median is the middle element once the sample is sorted.\nIf the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.\nmode: The number that appears the most in the sample. It is guaranteed to be unique.\nReturn the statistics of the sample as an array of floating-point numbers [minimum, maximum, mean, median, mode]. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,3.00000,2.37500,2.50000,3.00000]\nExplanation: The sample represented by count is [1,2,2,2,3,3,3,3].\nThe minimum and maximum are 1 and 3 respectively.\nThe mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\nSince the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\nThe mode is 3 as it appears the most in the sample.\nExample 2:\nInput: count = [0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: [1.00000,4.00000,2.18182,2.00000,1.00000]\nExplanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\nThe minimum and maximum are 1 and 4 respectively.\nThe mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182).\nSince the size of the sample is odd, the median is the middle element 2.\nThe mode is 1 as it appears the most in the sample.\n Constraints:\ncount.length == 256\n0 <= count[i] <= 109\n1 <= sum(count) <= 109\nThe mode of the sample that count represents is unique." }, { "post_href": "https://leetcode.com/problems/car-pooling/discuss/1669593/Python3-STRAIGHTFORWARD-()-Explained", "python_solutions": "class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n path = [0]*1000\n \n for num, a, b in trips:\n for loc in range (a, b):\n path[loc] += num\n if path[loc] > capacity: return False\n \n return True", "slug": "car-pooling", "post_title": "\u2764 [Python3] STRAIGHTFORWARD (\u273f\u25e0\u203f\u25e0), Explained", "user": "artod", "upvotes": 11, "views": 826, "problem_title": "car pooling", "number": 1094, "acceptance": 0.573, "difficulty": "Medium", "__index_level_0__": 17384, "question": "There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).\nYou are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi] indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop them off are fromi and toi respectively. The locations are given as the number of kilometers due east from the car's initial location.\nReturn true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.\n Example 1:\nInput: trips = [[2,1,5],[3,3,7]], capacity = 4\nOutput: false\nExample 2:\nInput: trips = [[2,1,5],[3,3,7]], capacity = 5\nOutput: true\n Constraints:\n1 <= trips.length <= 1000\ntrips[i].length == 3\n1 <= numPassengersi <= 100\n0 <= fromi < toi <= 1000\n1 <= capacity <= 105" }, { "post_href": "https://leetcode.com/problems/find-in-mountain-array/discuss/1290875/Python3-binary-search", "python_solutions": "class Solution:\n def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:\n \n def fn(lo, hi, mult): \n \"\"\"Return index of target between lo (inclusive) and hi (exlusive).\"\"\"\n while lo < hi: \n mid = lo + hi >> 1\n if mountain_arr.get(mid) == target: return mid \n elif mountain_arr.get(mid)*mult < target*mult: lo = mid + 1\n else: hi = mid \n return -1 \n \n lo, hi = 0, mountain_arr.length()\n while lo < hi: \n mid = lo + hi >> 1\n if mid and mountain_arr.get(mid-1) < mountain_arr.get(mid): lo = mid + 1\n else: hi = mid \n if (x := fn(0, lo, 1)) != -1: return x \n if (x := fn(lo, mountain_arr.length(), -1)) != -1: return x \n return -1", "slug": "find-in-mountain-array", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 1, "views": 48, "problem_title": "find in mountain array", "number": 1095, "acceptance": 0.357, "difficulty": "Hard", "__index_level_0__": 17421, "question": "(This problem is an interactive problem.)\nYou may recall that an array arr is a mountain array if and only if:\narr.length >= 3\nThere exists some i with 0 < i < arr.length - 1 such that:\narr[0] < arr[1] < ... < arr[i - 1] < arr[i]\narr[i] > arr[i + 1] > ... > arr[arr.length - 1]\nGiven a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.\nYou cannot access the mountain array directly. You may only access the array using a MountainArray interface:\nMountainArray.get(k) returns the element of the array at index k (0-indexed).\nMountainArray.length() returns the length of the array.\nSubmissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.\n Example 1:\nInput: array = [1,2,3,4,5,3,1], target = 3\nOutput: 2\nExplanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.\nExample 2:\nInput: array = [0,1,2,4,2,1], target = 3\nOutput: -1\nExplanation: 3 does not exist in the array, so we return -1.\n Constraints:\n3 <= mountain_arr.length() <= 104\n0 <= target <= 109\n0 <= mountain_arr.get(index) <= 109" }, { "post_href": "https://leetcode.com/problems/brace-expansion-ii/discuss/322002/Python3-Concise-iterative-solution-using-stack", "python_solutions": "class Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n stack,res,cur=[],[],[]\n for i in range(len(expression)):\n v=expression[i]\n if v.isalpha():\n cur=[c+v for c in cur or ['']]\n elif v=='{':\n stack.append(res)\n stack.append(cur)\n res,cur=[],[]\n elif v=='}':\n pre=stack.pop()\n preRes=stack.pop()\n cur=[p+c for c in res+cur for p in pre or ['']]\n res=preRes\n elif v==',':\n res+=cur\n cur=[]\n return sorted(set(res+cur))", "slug": "brace-expansion-ii", "post_title": "[Python3] Concise iterative solution using stack", "user": "yuanzhi247012", "upvotes": 102, "views": 4800, "problem_title": "brace expansion ii", "number": 1096, "acceptance": 0.635, "difficulty": "Hard", "__index_level_0__": 17427, "question": "Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.\nThe grammar can best be understood through simple examples:\nSingle letters represent a singleton set containing that word.\nR(\"a\") = {\"a\"}\nR(\"w\") = {\"w\"}\nWhen we take a comma-delimited list of two or more expressions, we take the union of possibilities.\nR(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}\nR(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)\nWhen 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.\nR(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}\nR(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}\nFormally, the three rules for our grammar:\nFor every lowercase letter x, we have R(x) = {x}.\nFor expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) \u222a R(e2) \u222a ...\nFor expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) \u00d7 R(e2)}, where + denotes concatenation, and \u00d7 denotes the cartesian product.\nGiven an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.\n Example 1:\nInput: expression = \"{a,b}{c,{d,e}}\"\nOutput: [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\nExample 2:\nInput: expression = \"{{a,z},a{b,c},{ab,z}}\"\nOutput: [\"a\",\"ab\",\"ac\",\"z\"]\nExplanation: Each distinct word is written only once in the final answer.\n Constraints:\n1 <= expression.length <= 60\nexpression[i] consists of '{', '}', ','or lowercase English letters.\nThe given expression represents a set of words based on the grammar given in the description." }, { "post_href": "https://leetcode.com/problems/distribute-candies-to-people/discuss/797848/Solution-or-Python", "python_solutions": "class Solution:\n def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n # create an array of size num_people and initialize it with 0\n list_people = [0] * num_people\n \n # starting value\n index = 1\n \n # iterate until the number of candies are more than 0\n while candies > 0:\n \n # if candies are more than index value, add the index value to the location \n if candies > index:\n # we are using mod operation by the num_people to locate the index of the array\n # we are subtracting by 1 because the array index starts at 0\n list_people[(index - 1) % num_people] += index\n else:\n # if candies are less than index value, add all remaining candies to location\n list_people[(index - 1) % num_people] += candies\n \n # subtract the candies with index values\n candies -= index\n \n # increment the index values\n index += 1\n \n # return the resultant array\n return(list_people)", "slug": "distribute-candies-to-people", "post_title": "Solution | Python", "user": "rushirg", "upvotes": 11, "views": 439, "problem_title": "distribute candies to people", "number": 1103, "acceptance": 0.639, "difficulty": "Easy", "__index_level_0__": 17430, "question": "We distribute some number of candies, to a row of n = num_people people in the following way:\nWe then give 1 candy to the first person, 2 candies to the second person, and so on until we give n candies to the last person.\nThen, we go back to the start of the row, giving n + 1 candies to the first person, n + 2 candies to the second person, and so on until we give 2 * n candies to the last person.\nThis process repeats (with us giving one more candy each time, and moving to the start of the row after we reach the end) until we run out of candies. The last person will receive all of our remaining candies (not necessarily one more than the previous gift).\nReturn an array (of length num_people and sum candies) that represents the final distribution of candies.\n Example 1:\nInput: candies = 7, num_people = 4\nOutput: [1,2,3,1]\nExplanation:\nOn the first turn, ans[0] += 1, and the array is [1,0,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3,0].\nOn the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].\nExample 2:\nInput: candies = 10, num_people = 3\nOutput: [5,2,3]\nExplanation: \nOn the first turn, ans[0] += 1, and the array is [1,0,0].\nOn the second turn, ans[1] += 2, and the array is [1,2,0].\nOn the third turn, ans[2] += 3, and the array is [1,2,3].\nOn the fourth turn, ans[0] += 4, and the final array is [5,2,3].\n Constraints:\n1 <= candies <= 10^9\n1 <= num_people <= 1000" }, { "post_href": "https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/323382/Python-3-easy-explained", "python_solutions": "class Solution:\n \n def pathInZigZagTree(self, label: int) -> List[int]:\n rows = [(1, 0)] #row represented by tuple (min_element_in_row, is_neg_order)\n while rows[-1][0]*2 <= label:\n rows.append((rows[-1][0]*2, 1 - rows[-1][1]))\n \n power, negOrder = rows.pop()\n \n res = []\n while label > 1:\n res.append(label)\n \n if negOrder:\n # adjust label position and find parent with division by 2\n # a, b - range of current row \n a, b = power, power*2 -1\n label = (a + (b - label))//2\n else:\n # divide label by 2 and adjust parent position\n # a, b - range of previous row\n a, b = power//2, power - 1\n label = b - (label//2 - a)\n \n power, negOrder = rows.pop()\n \n \n res.append(1)\n \n return res[::-1]", "slug": "path-in-zigzag-labelled-binary-tree", "post_title": "Python 3 easy explained", "user": "vilchinsky", "upvotes": 3, "views": 207, "problem_title": "path in zigzag labelled binary tree", "number": 1104, "acceptance": 0.75, "difficulty": "Medium", "__index_level_0__": 17448, "question": "In an infinite binary tree where every node has two children, the nodes are labelled in row order.\nIn the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.\nGiven the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.\n Example 1:\nInput: label = 14\nOutput: [1,3,4,14]\nExample 2:\nInput: label = 26\nOutput: [1,2,6,10,26]\n Constraints:\n1 <= label <= 10^6" }, { "post_href": "https://leetcode.com/problems/filling-bookcase-shelves/discuss/1517001/Python-3-or-DP-or-Explanation", "python_solutions": "class Solution:\n def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:\n n = len(books)\n dp = [sys.maxsize] * n\n dp[0] = books[0][1] # first book will always on it's own row\n for i in range(1, n): # for each book\n cur_w, height_max = books[i][0], books[i][1]\n dp[i] = dp[i-1] + height_max # initialize result for current book `dp[i]`\n for j in range(i-1, -1, -1): # for each previou `book[j]`, verify if it can be placed in the same row as `book[i]`\n if cur_w + books[j][0] > shelfWidth: break\n cur_w += books[j][0]\n height_max = max(height_max, books[j][1]) # update current max height\n dp[i] = min(dp[i], (dp[j-1] + height_max) if j-1 >= 0 else height_max) # always take the maximum heigh on current row\n return dp[n-1]", "slug": "filling-bookcase-shelves", "post_title": "Python 3 | DP | Explanation", "user": "idontknoooo", "upvotes": 5, "views": 518, "problem_title": "filling bookcase shelves", "number": 1105, "acceptance": 0.5920000000000001, "difficulty": "Medium", "__index_level_0__": 17456, "question": "You are given an array books where books[i] = [thicknessi, heighti] indicates the thickness and height of the ith book. You are also given an integer shelfWidth.\nWe want to place these books in order onto bookcase shelves that have a total width shelfWidth.\nWe choose some of the books to place on this shelf such that the sum of their thickness is less than or equal to shelfWidth, then build another level of the shelf of the bookcase so that the total height of the bookcase has increased by the maximum height of the books we just put down. We repeat this process until there are no more books to place.\nNote that at each step of the above process, the order of the books we place is the same order as the given sequence of books.\nFor example, if we have an ordered list of 5 books, we might place the first and second book onto the first shelf, the third book on the second shelf, and the fourth and fifth book on the last shelf.\nReturn the minimum possible height that the total bookshelf can be after placing shelves in this manner.\n Example 1:\nInput: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4\nOutput: 6\nExplanation:\nThe sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\nNotice that book number 2 does not have to be on the first shelf.\nExample 2:\nInput: books = [[1,3],[2,4],[3,2]], shelfWidth = 6\nOutput: 4\n Constraints:\n1 <= books.length <= 1000\n1 <= thicknessi <= shelfWidth <= 1000\n1 <= heighti <= 1000" }, { "post_href": "https://leetcode.com/problems/parsing-a-boolean-expression/discuss/1582694/One-pass-with-stack-97-speed", "python_solutions": "class Solution:\n operands = {\"!\", \"&\", \"|\", \"t\", \"f\"}\n values = {\"t\", \"f\"}\n\n def parseBoolExpr(self, expression: str) -> bool:\n stack = []\n for c in expression:\n if c == \")\":\n val = stack.pop()\n args = set()\n while val in Solution.values:\n args.add(val)\n val = stack.pop()\n if val == \"!\":\n stack.append(\"f\" if \"t\" in args else \"t\")\n elif val == \"&\":\n stack.append(\"f\" if \"f\" in args else \"t\")\n elif val == \"|\":\n stack.append(\"t\" if \"t\" in args else \"f\")\n elif c in Solution.operands:\n stack.append(c)\n return stack[0] == \"t\"", "slug": "parsing-a-boolean-expression", "post_title": "One pass with stack, 97% speed", "user": "EvgenySH", "upvotes": 2, "views": 142, "problem_title": "parsing a boolean expression", "number": 1106, "acceptance": 0.585, "difficulty": "Hard", "__index_level_0__": 17465, "question": "A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:\n't' that evaluates to true.\n'f' that evaluates to false.\n'!(subExpr)' that evaluates to the logical NOT of the inner expression subExpr.\n'&(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical AND of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1.\n'|(subExpr1, subExpr2, ..., subExprn)' that evaluates to the logical OR of the inner expressions subExpr1, subExpr2, ..., subExprn where n >= 1.\nGiven a string expression that represents a boolean expression, return the evaluation of that expression.\nIt is guaranteed that the given expression is valid and follows the given rules.\n Example 1:\nInput: expression = \"&(|(f))\"\nOutput: false\nExplanation: \nFirst, evaluate |(f) --> f. The expression is now \"&(f)\".\nThen, evaluate &(f) --> f. The expression is now \"f\".\nFinally, return false.\nExample 2:\nInput: expression = \"|(f,f,f,t)\"\nOutput: true\nExplanation: The evaluation of (false OR false OR false OR true) is true.\nExample 3:\nInput: expression = \"!(&(f,t))\"\nOutput: true\nExplanation: \nFirst, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now \"!(f)\".\nThen, evaluate !(f) --> NOT false --> true. We return true.\n Constraints:\n1 <= expression.length <= 2 * 104\nexpression[i] is one following characters: '(', ')', '&', '|', '!', 't', 'f', and ','." }, { "post_href": "https://leetcode.com/problems/defanging-an-ip-address/discuss/1697285/Python-code%3A-Defanging-an-IP-Address", "python_solutions": "class Solution:\n def defangIPaddr(self, address: str) -> str:\n address=address.replace(\".\",\"[.]\")\n return address", "slug": "defanging-an-ip-address", "post_title": "Python code: Defanging an IP Address", "user": "Anilchouhan181", "upvotes": 3, "views": 78, "problem_title": "defanging an ip address", "number": 1108, "acceptance": 0.893, "difficulty": "Easy", "__index_level_0__": 17472, "question": "Given a valid (IPv4) IP address, return a defanged version of that IP address.\nA defanged IP address replaces every period \".\" with \"[.]\".\n Example 1:\nInput: address = \"1.1.1.1\"\nOutput: \"1[.]1[.]1[.]1\"\nExample 2:\nInput: address = \"255.100.50.0\"\nOutput: \"255[.]100[.]50[.]0\"\n Constraints:\nThe given address is a valid IPv4 address." }, { "post_href": "https://leetcode.com/problems/corporate-flight-bookings/discuss/2309125/Easy-Python-O(n)-using-accumulate", "python_solutions": "class Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n res = [0]*n\n for first, last, seat in bookings:\n res[first - 1] += seat\n if last < n:\n res[last] -= seat\n return accumulate(res)", "slug": "corporate-flight-bookings", "post_title": "Easy Python O(n) using accumulate", "user": "rinaba501", "upvotes": 3, "views": 140, "problem_title": "corporate flight bookings", "number": 1109, "acceptance": 0.604, "difficulty": "Medium", "__index_level_0__": 17526, "question": "There are n flights that are labeled from 1 to n.\nYou are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.\nReturn an array answer of length n, where answer[i] is the total number of seats reserved for flight i.\n Example 1:\nInput: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\nOutput: [10,55,45,25,25]\nExplanation:\nFlight labels: 1 2 3 4 5\nBooking 1 reserved: 10 10\nBooking 2 reserved: 20 20\nBooking 3 reserved: 25 25 25 25\nTotal seats: 10 55 45 25 25\nHence, answer = [10,55,45,25,25]\nExample 2:\nInput: bookings = [[1,2,10],[2,2,15]], n = 2\nOutput: [10,25]\nExplanation:\nFlight labels: 1 2\nBooking 1 reserved: 10 10\nBooking 2 reserved: 15\nTotal seats: 10 25\nHence, answer = [10,25]\n Constraints:\n1 <= n <= 2 * 104\n1 <= bookings.length <= 2 * 104\nbookings[i].length == 3\n1 <= firsti <= lasti <= n\n1 <= seatsi <= 104" }, { "post_href": "https://leetcode.com/problems/delete-nodes-and-return-forest/discuss/1025341/Python3-dfs-O(N)", "python_solutions": "class Solution:\n def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:\n to_delete = set(to_delete) # O(1) lookup \n \n def fn(node, pval):\n \"\"\"Return node upon deletion of required values.\"\"\"\n if not node: return \n if node.val in to_delete: \n node.left = fn(node.left, None)\n node.right = fn(node.right, None)\n return \n else: \n if not pval: ans.append(node)\n node.left = fn(node.left, node.val)\n node.right = fn(node.right, node.val)\n return node \n \n ans = []\n fn(root, None)\n return ans", "slug": "delete-nodes-and-return-forest", "post_title": "[Python3] dfs O(N)", "user": "ye15", "upvotes": 5, "views": 233, "problem_title": "delete nodes and return forest", "number": 1110, "acceptance": 0.693, "difficulty": "Medium", "__index_level_0__": 17545, "question": "Given the root of a binary tree, each node in the tree has a distinct value.\nAfter deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\nReturn the roots of the trees in the remaining forest. You may return the result in any order.\n Example 1:\nInput: root = [1,2,3,4,5,6,7], to_delete = [3,5]\nOutput: [[1,2,null,4],[6],[7]]\nExample 2:\nInput: root = [1,2,4,null,3], to_delete = [3]\nOutput: [[1,2,4]]\n Constraints:\nThe number of nodes in the given tree is at most 1000.\nEach node has a distinct value between 1 and 1000.\nto_delete.length <= 1000\nto_delete contains distinct values between 1 and 1000." }, { "post_href": "https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/2825324/Python-oror-98.06-Faster-oror-Greedy-Approach-oror-O(N)-Solution", "python_solutions": "class Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n ans=[]\n prev=1\n for i in seq:\n if i=='(':\n if prev==0:\n ans.append(1)\n else:\n ans.append(0)\n else:\n ans.append(prev)\n if prev==0:\n prev=1\n else:\n prev=0\n return ans", "slug": "maximum-nesting-depth-of-two-valid-parentheses-strings", "post_title": "Python || 98.06% Faster || Greedy Approach || O(N) Solution", "user": "DareDevil_007", "upvotes": 1, "views": 10, "problem_title": "maximum nesting depth of two valid parentheses strings", "number": 1111, "acceptance": 0.732, "difficulty": "Medium", "__index_level_0__": 17555, "question": "A string is a valid parentheses string (denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and:\nIt is the empty string, or\nIt can be written as AB (A concatenated with B), where A and B are VPS's, or\nIt can be written as (A), where A is a VPS.\nWe can similarly define the nesting depth depth(S) of any VPS S as follows:\ndepth(\"\") = 0\ndepth(A + B) = max(depth(A), depth(B)), where A and B are VPS's\ndepth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\nFor example, \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\n Given a VPS seq, split it into two disjoint subsequences A and B, such that A and B are VPS's (and A.length + B.length = seq.length).\nNow choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.\nReturn an answer array (of length seq.length) that encodes such a choice of A and B: answer[i] = 0 if seq[i] is part of A, else answer[i] = 1. Note that even though multiple answers may exist, you may return any of them.\n Example 1:\nInput: seq = \"(()())\"\nOutput: [0,1,1,1,1,0]\nExample 2:\nInput: seq = \"()(())()\"\nOutput: [0,0,0,1,1,0,1,1]\n Constraints:\n1 <= seq.size <= 10000" }, { "post_href": "https://leetcode.com/problems/relative-sort-array/discuss/343445/Python3.-Actually-easy-to-understand.-Beats-75-on-speed-and-100-on-memory", "python_solutions": "class Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n\t\t# initialise a dictionary since we're going to want to count the occurences of each element in arr1\n dic = {}\n\t\t# this loop populates the dictionary with the number of occurences for each element\n for elem in arr1:\n if dic.get(elem) is None:\n dic[elem] = 1\n else:\n dic[elem] = dic[elem] + 1\n\t\t# initialise a new list to store the values which exist in both arr2 and arr1\n output = []\n\t\t# populate output with the elements multiplied by their occurences (e.g. [1]*2 = [1, 1])\n for elem in arr2:\n output += [elem]*dic[elem]\n\t\t# initialise a new list to store the elements which are in arr1 but not arr2\n extra_output = []\n\t\t# populate extra_output with these elements multiplied by their occurences. \n\t\t# Note: set(arr1)-set(arr2) provides us with the set of numbers which exist in arr1 but not in arr2\n for elem in set(arr1)-set(arr2):\n extra_output += [elem]*dic[elem]\n\t\t# return the first list and the sorted second list\n return output + sorted(extra_output)", "slug": "relative-sort-array", "post_title": "Python3. Actually easy to understand. Beats 75% on speed and 100% on memory", "user": "softbabywipes", "upvotes": 12, "views": 1800, "problem_title": "relative sort array", "number": 1122, "acceptance": 0.684, "difficulty": "Easy", "__index_level_0__": 17564, "question": "Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.\nSort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that do not appear in arr2 should be placed at the end of arr1 in ascending order.\n Example 1:\nInput: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\nOutput: [2,2,2,1,4,3,3,9,6,7,19]\nExample 2:\nInput: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]\nOutput: [22,28,8,6,17,44]\n Constraints:\n1 <= arr1.length, arr2.length <= 1000\n0 <= arr1[i], arr2[i] <= 1000\nAll the elements of arr2 are distinct.\nEach arr2[i] is in arr1." }, { "post_href": "https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/discuss/1760394/Python-easy-to-understand-and-read-or-DFS", "python_solutions": "class Solution:\n def ht(self, node):\n if not node:\n return 0\n return max(self.ht(node.left), self.ht(node.right)) + 1\n \n def dfs(self, node):\n if not node:\n return None\n left, right = self.ht(node.left), self.ht(node.right)\n if left == right:\n return node\n if left > right:\n return self.dfs(node.left)\n if left < right:\n return self.dfs(node.right)\n\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n return self.dfs(root)", "slug": "lowest-common-ancestor-of-deepest-leaves", "post_title": "Python easy to understand and read | DFS", "user": "sanial2001", "upvotes": 4, "views": 184, "problem_title": "lowest common ancestor of deepest leaves", "number": 1123, "acceptance": 0.706, "difficulty": "Medium", "__index_level_0__": 17612, "question": "Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.\nRecall that:\nThe node of a binary tree is a leaf if and only if it has no children\nThe depth of the root of the tree is 0. if the depth of a node is d, the depth of each of its children is d + 1.\nThe lowest common ancestor of a set S of nodes, is the node A with the largest depth such that every node in S is in the subtree with root A.\n Example 1:\nInput: root = [3,5,1,6,2,0,8,null,null,7,4]\nOutput: [2,7,4]\nExplanation: We return the node with value 2, colored in yellow in the diagram.\nThe nodes coloured in blue are the deepest leaf-nodes of the tree.\nNote that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.\nExample 2:\nInput: root = [1]\nOutput: [1]\nExplanation: The root is the deepest node in the tree, and it's the lca of itself.\nExample 3:\nInput: root = [0,1,3,null,2]\nOutput: [2]\nExplanation: The deepest leaf node in the tree is 2, the lca of one node is itself.\n Constraints:\nThe number of nodes in the tree will be in the range [1, 1000].\n0 <= Node.val <= 1000\nThe values of the nodes in the tree are unique.\n Note: This question is the same as 865: https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/" }, { "post_href": "https://leetcode.com/problems/longest-well-performing-interval/discuss/1495771/For-Beginners-oror-Well-Explained-oror-97-faster-oror-Easy-to-understand", "python_solutions": "class Solution:\ndef longestWPI(self, hours: List[int]) -> int:\n \n dic = defaultdict(int)\n dummy = [1 if hours[0]>8 else -1]\n for h in hours[1:]:\n c = 1 if h>8 else -1\n dummy.append(dummy[-1]+c)\n \n res = 0\n for i in range(len(dummy)):\n if dummy[i]>0:\n res = max(res,i+1)\n else:\n if dummy[i]-1 in dic:\n res = max(res,i-dic[dummy[i]-1])\n if dummy[i] not in dic:\n dic[dummy[i]] = i\n \n return res", "slug": "longest-well-performing-interval", "post_title": "\ud83d\udccc\ud83d\udccc For-Beginners || Well-Explained || 97% faster || Easy-to-understand \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 4, "views": 471, "problem_title": "longest well performing interval", "number": 1124, "acceptance": 0.346, "difficulty": "Medium", "__index_level_0__": 17623, "question": "We are given hours, a list of the number of hours worked per day for a given employee.\nA day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.\nA well-performing interval is an interval of days for which the number of tiring days is strictly larger than the number of non-tiring days.\nReturn the length of the longest well-performing interval.\n Example 1:\nInput: hours = [9,9,6,0,6,6,9]\nOutput: 3\nExplanation: The longest well-performing interval is [9,9,6].\nExample 2:\nInput: hours = [6,6,6]\nOutput: 0\n Constraints:\n1 <= hours.length <= 104\n0 <= hours[i] <= 16" }, { "post_href": "https://leetcode.com/problems/smallest-sufficient-team/discuss/334630/Python-Optimized-backtracking-with-explanation-and-code-comments-88-ms", "python_solutions": "class Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n \n # Firstly, convert all the sublists in people into sets for easier processing.\n for i, skills in enumerate(people):\n people[i] = set(skills)\n \n # Remove all skill sets that are subset of another skillset, by replacing the subset with an\n # empty set. We do this rather than completely removing, so that indexes aren't \n # disrupted (which is a pain to have to sort out later).\n for i, i_skills in enumerate(people):\n for j, j_skills in enumerate(people):\n if i != j and i_skills.issubset(j_skills):\n people[i] = set()\n \n # Now build up a dictionary of skills to the people who can perform them. The backtracking algorithm\n # will use this.\n skills_to_people = collections.defaultdict(set)\n for i, skills in enumerate(people):\n for skill in skills:\n skills_to_people[skill].add(i)\n people[i] = set(skills)\n \n # Keep track of some data used by the backtracking algorithm.\n self.unmet_skills = set(req_skills) # Backtracking will remove and readd skills here as needed.\n self.smallest_length = math.inf # Smallest team length so far.\n self.current_team = [] # Current team members.\n self.best_team = [] # Best team we've found, i,e, shortest team that covers skills/\n \n\t\t# Here is the backtracking algorithm.\n def meet_skill(skill=0):\n\t\t\t# Base case: All skills are met.\n if not self.unmet_skills:\n\t\t\t\t# If the current team is smaller than the previous we found, update it.\n if self.smallest_length > len(self.current_team):\n self.smallest_length = len(self.current_team)\n self.best_team = self.current_team[::] # In Python, this makes a copy of a list.\n return # So that we don't carry out the rest of the algorithm.\n \n # If this skill is already met, move onto the next one.\n if req_skills[skill] not in self.unmet_skills:\n return meet_skill(skill + 1)\n\t\t\t\t# Note return is just to stop rest of code here running. Return values\n\t\t\t\t# are not caught and used.\n \n # Otherwise, consider all who could meet the current skill.\n for i in skills_to_people[req_skills[skill]]:\n \n\t\t\t\t# Add this person onto the team by updating the backtrading data.\n skills_added_by_person = people[i].intersection(self.unmet_skills)\n self.unmet_skills = self.unmet_skills - skills_added_by_person\n self.current_team.append(i)\n \n\t\t\t\t# Do the recursive call to further build the team.\n meet_skill(skill + 1)\n \n # Backtrack by removing the person from the team again.\n self.current_team.pop()\n self.unmet_skills = self.unmet_skills.union(skills_added_by_person)\n \n\t\t# Kick off the algorithm.\n meet_skill() \n return self.best_team", "slug": "smallest-sufficient-team", "post_title": "Python - Optimized backtracking with explanation and code comments [88 ms]", "user": "Hai_dee", "upvotes": 44, "views": 3100, "problem_title": "smallest sufficient team", "number": 1125, "acceptance": 0.47, "difficulty": "Hard", "__index_level_0__": 17628, "question": "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.\nConsider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\nFor example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].\nReturn any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\nIt is guaranteed an answer exists.\n Example 1:\nInput: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\nOutput: [0,2]\nExample 2:\nInput: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\nOutput: [1,2]\n Constraints:\n1 <= req_skills.length <= 16\n1 <= req_skills[i].length <= 16\nreq_skills[i] consists of lowercase English letters.\nAll the strings of req_skills are unique.\n1 <= people.length <= 60\n0 <= people[i].length <= 16\n1 <= people[i][j].length <= 16\npeople[i][j] consists of lowercase English letters.\nAll the strings of people[i] are unique.\nEvery skill in people[i] is a skill in req_skills.\nIt is guaranteed a sufficient team exists." }, { "post_href": "https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/405437/Python3-Concise-and-Efficient", "python_solutions": "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n m = collections.defaultdict(int)\n ans = 0\n for a, b in dominoes:\n if a > b: a, b = b, a\n v = 10*a + b\n if v in m:\n ans += m[v]\n m[v] += 1\n return ans", "slug": "number-of-equivalent-domino-pairs", "post_title": "Python3 - Concise and Efficient", "user": "luojl", "upvotes": 6, "views": 310, "problem_title": "number of equivalent domino pairs", "number": 1128, "acceptance": 0.469, "difficulty": "Easy", "__index_level_0__": 17631, "question": "Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a == c and b == d), or (a == d and b == c) - that is, one domino can be rotated to be equal to another domino.\nReturn the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].\n Example 1:\nInput: dominoes = [[1,2],[2,1],[3,4],[5,6]]\nOutput: 1\nExample 2:\nInput: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]\nOutput: 3\n Constraints:\n1 <= dominoes.length <= 4 * 104\ndominoes[i].length == 2\n1 <= dominoes[i][j] <= 9" }, { "post_href": "https://leetcode.com/problems/shortest-path-with-alternating-colors/discuss/712063/Python-DFS", "python_solutions": "class Solution:\n def shortestAlternatingPaths(self, n, red_edges, blue_edges):\n neighbors = [[[], []] for _ in range(n)]\n ans = [[0, 0]]+[[2*n, 2*n] for _ in range(n-1)]\n for u, v in red_edges: neighbors[u][0].append(v)\n for u, v in blue_edges: neighbors[u][1].append(v)\n \n def dfs(u, c, dist):\n for v in neighbors[u][c]:\n if dist+1 int:\n \n arr = [float('inf')] + arr + [float('inf')]\n n, res = len(arr), 0\n \n while n>3:\n mi = min(arr)\n ind = arr.index(mi)\n \n if arr[ind-1] int:\n minA = minB = minC = minD = math.inf\n maxA = maxB = maxC = maxD = -math.inf\n\n for i, (num1, num2) in enumerate(zip(arr1, arr2)):\n minA = min(minA, i + num1 + num2)\n maxA = max(maxA, i + num1 + num2)\n minB = min(minB, i + num1 - num2)\n maxB = max(maxB, i + num1 - num2)\n minC = min(minC, i - num1 + num2)\n maxC = max(maxC, i - num1 + num2)\n minD = min(minD, i - num1 - num2)\n maxD = max(maxD, i - num1 - num2)\n \n return max(maxA - minA, maxB - minB,\n maxC - minC, maxD - minD)", "slug": "maximum-of-absolute-value-expression", "post_title": "Python 3 | O(n)/O(1)", "user": "dereky4", "upvotes": 2, "views": 322, "problem_title": "maximum of absolute value expression", "number": 1131, "acceptance": 0.494, "difficulty": "Medium", "__index_level_0__": 17665, "question": "Given two arrays of integers with equal lengths, return the maximum value of:\n|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\nwhere the maximum is taken over all 0 <= i, j < arr1.length.\n Example 1:\nInput: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\nOutput: 13\nExample 2:\nInput: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\nOutput: 20\n Constraints:\n2 <= arr1.length == arr2.length <= 40000\n-10^6 <= arr1[i], arr2[i] <= 10^6" }, { "post_href": "https://leetcode.com/problems/n-th-tribonacci-number/discuss/350547/Solution-in-Python-3-(beats-~100)", "python_solutions": "class Solution:\n def tribonacci(self, n: int) -> int:\n \ta, b, c = 0, 1, 1\n \tfor i in range(n): a, b, c = b, c, a + b + c\n \treturn a\n\t\t\n\t\t\n- Junaid Mansuri", "slug": "n-th-tribonacci-number", "post_title": "Solution in Python 3 (beats ~100%)", "user": "junaidmansuri", "upvotes": 14, "views": 1600, "problem_title": "n th tribonacci number", "number": 1137, "acceptance": 0.633, "difficulty": "Easy", "__index_level_0__": 17670, "question": "The Tribonacci sequence Tn is defined as follows: \nT0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\nGiven n, return the value of Tn.\n Example 1:\nInput: n = 4\nOutput: 4\nExplanation:\nT_3 = 0 + 1 + 1 = 2\nT_4 = 1 + 1 + 2 = 4\nExample 2:\nInput: n = 25\nOutput: 1389537\n Constraints:\n0 <= n <= 37\nThe answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1." }, { "post_href": "https://leetcode.com/problems/alphabet-board-path/discuss/837601/Python-3-or-Straight-forward-solution-or-Explanations", "python_solutions": "class Solution:\n def __init__(self):\n board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"]\n self.d = {c:(i, j) for i, row in enumerate(board) for j, c in enumerate(row)}\n \n def alphabetBoardPath(self, target: str) -> str:\n ans, prev = '', (0, 0)\n for c in target:\n cur = self.d[c]\n delta_x, delta_y = cur[0]-prev[0], cur[1]-prev[1]\n h = 'R'*delta_y if delta_y > 0 else 'L'*(-delta_y) \n v = 'D'*delta_x if delta_x > 0 else 'U'*(-delta_x) \n ans += (h+v if cur == (5,0) else v+h) + '!'\n prev = cur\n return ans", "slug": "alphabet-board-path", "post_title": "Python 3 | Straight forward solution | Explanations", "user": "idontknoooo", "upvotes": 2, "views": 184, "problem_title": "alphabet board path", "number": 1138, "acceptance": 0.523, "difficulty": "Medium", "__index_level_0__": 17731, "question": "On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].\nHere, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"], as shown in the diagram below.\nWe may make the following moves:\n'U' moves our position up one row, if the position exists on the board;\n'D' moves our position down one row, if the position exists on the board;\n'L' moves our position left one column, if the position exists on the board;\n'R' moves our position right one column, if the position exists on the board;\n'!' adds the character board[r][c] at our current position (r, c) to the answer.\n(Here, the only positions that exist on the board are positions with letters on them.)\nReturn a sequence of moves that makes our answer equal to target in the minimum number of moves. You may return any path that does so.\n Example 1:\nInput: target = \"leet\"\nOutput: \"DDR!UURRR!!DDD!\"\nExample 2:\nInput: target = \"code\"\nOutput: \"RR!DDRR!UUL!R!\"\n Constraints:\n1 <= target.length <= 100\ntarget consists only of English lowercase letters." }, { "post_href": "https://leetcode.com/problems/largest-1-bordered-square/discuss/1435087/Python-3-or-Prefix-sum-DP-O(N3)-or-Explanation", "python_solutions": "class Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n dp = [[(0, 0)] * (n) for _ in range((m))] \n for i in range(m): # calculate prefix-sum as `hint` section suggested\n for j in range(n):\n if not grid[i][j]:\n continue\n dp[i][j] = (dp[i][j][0] + dp[i-1][j][0] + 1, dp[i][j][1] + dp[i][j-1][1] + 1)\n for win in range(min(m, n)-1, -1, -1): # for each window size\n for i in range(m-win): # for each x-axis\n for j in range(n-win): # for each y-axis\n if not grid[i][j]: continue # determine whether square of (i, j), (i+win, j+win) is 1-boarded\n x1, y1 = dp[i+win][j+win] # bottom-right corner\n x2, y2 = dp[i][j+win] # upper-right corner\n x3, y3 = dp[i+win][j] # bottom-left corner\n x4, y4 = dp[i][j] # upper-left corner\n if y1 - y3 == x1 - x2 == y2 - y4 == x3 - x4 == win:\n return (win+1) * (win+1)\n return 0", "slug": "largest-1-bordered-square", "post_title": "Python 3 | Prefix-sum, DP, O(N^3) | Explanation", "user": "idontknoooo", "upvotes": 2, "views": 347, "problem_title": "largest 1 bordered square", "number": 1139, "acceptance": 0.501, "difficulty": "Medium", "__index_level_0__": 17739, "question": "Given a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.\n Example 1:\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 9\nExample 2:\nInput: grid = [[1,1,0,0]]\nOutput: 1\n Constraints:\n1 <= grid.length <= 100\n1 <= grid[0].length <= 100\ngrid[i][j] is 0 or 1" }, { "post_href": "https://leetcode.com/problems/stone-game-ii/discuss/793881/python-DP-Thought-process-explained", "python_solutions": "class Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n suffix_sum = self._suffix_sum(piles)\n\n @lru_cache(None)\n def dfs(pile: int, M: int, turn: bool) -> Tuple[int, int]:\n # turn: true - alex, false - lee\n sum_alex, sum_lee = suffix_sum[pile], suffix_sum[pile]\n\n for next_pile in range(pile + 1, min(pile + 2 * M + 1, len(piles) + 1)):\n sum_alex_next, sum_lee_next = dfs(\n next_pile, max(M, next_pile - pile), not turn\n )\n range_sum = suffix_sum[pile] - suffix_sum[next_pile]\n\n if turn:\n if sum_lee_next < sum_lee:\n sum_alex = sum_alex_next + range_sum\n sum_lee = sum_lee_next\n else:\n if sum_alex_next < sum_alex:\n sum_alex = sum_alex_next\n sum_lee = sum_lee_next + range_sum\n\n return sum_alex, sum_lee\n\n return dfs(0, 1, True)[0]", "slug": "stone-game-ii", "post_title": "[python] DP Thought process explained", "user": "omgitspavel", "upvotes": 36, "views": 1900, "problem_title": "stone game ii", "number": 1140, "acceptance": 0.649, "difficulty": "Medium", "__index_level_0__": 17743, "question": "Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. \nAlice and Bob take turns, with Alice starting first. Initially, M = 1.\nOn each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).\nThe game continues until all the stones have been taken.\nAssuming Alice and Bob play optimally, return the maximum number of stones Alice can get.\n Example 1:\nInput: piles = [2,7,9,4,4]\nOutput: 10\nExplanation: If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 piles in total. So we return 10 since it's larger. \nExample 2:\nInput: piles = [1,2,3,4,5,100]\nOutput: 104\n Constraints:\n1 <= piles.length <= 100\n1 <= piles[i] <= 104" }, { "post_href": "https://leetcode.com/problems/longest-common-subsequence/discuss/2331817/Python3-or-Java-or-C%2B%2B-or-DP-or-O(nm)-or-BottomUp-(Tabulation)", "python_solutions": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n \n dp = []\n \n # Fill the matrix\n for _ in range(len(text1)+1):\n row = []\n for _ in range(len(text2)+1):\n row.append(0)\n \n dp.append(row)\n \n \n longest_length = 0\n \n # Start looping throught the text1 and text2\n for i in range(1, len(text1)+1):\n for j in range(1, len(text2)+1):\n \n # If characters match\n\t\t\t\t# fill the current cell by adding one to the diagonal value\n if text1[i-1] == text2[j-1]:\n dp[i][j] = dp[i-1][j-1] + 1\n else:\n # If characters do not match\n\t\t\t\t\t# Fill the cell with max value of previous row and column\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n \n # Keep track of the MAXIMUM value in the matrix\n longest_length = max(longest_length, dp[i][j])\n \n return longest_length", "slug": "longest-common-subsequence", "post_title": "Python3 | Java | C++ | DP | O(nm) | BottomUp (Tabulation)", "user": "khaydaraliev99", "upvotes": 10, "views": 488, "problem_title": "longest common subsequence", "number": 1143, "acceptance": 0.588, "difficulty": "Medium", "__index_level_0__": 17752, "question": "Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\nFor example, \"ace\" is a subsequence of \"abcde\".\nA common subsequence of two strings is a subsequence that is common to both strings.\n Example 1:\nInput: text1 = \"abcde\", text2 = \"ace\" \nOutput: 3 \nExplanation: The longest common subsequence is \"ace\" and its length is 3.\nExample 2:\nInput: text1 = \"abc\", text2 = \"abc\"\nOutput: 3\nExplanation: The longest common subsequence is \"abc\" and its length is 3.\nExample 3:\nInput: text1 = \"abc\", text2 = \"def\"\nOutput: 0\nExplanation: There is no such common subsequence, so the result is 0.\n Constraints:\n1 <= text1.length, text2.length <= 1000\ntext1 and text2 consist of only lowercase English characters." }, { "post_href": "https://leetcode.com/problems/decrease-elements-to-make-array-zigzag/discuss/891850/Python-3-or-Greedy-Two-pass-or-Explanation", "python_solutions": "class Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n def greedy(nums, small_first=True):\n if n <= 1: return 0\n ans = 0\n for i in range(n-1):\n if small_first and nums[i] >= nums[i+1]:\n ans += nums[i] - (nums[i+1]-1)\n nums[i] = nums[i+1] - 1\n elif not small_first and nums[i] <= nums[i+1]:\n ans += nums[i+1] - (nums[i]-1)\n nums[i+1] = nums[i] - 1\n small_first = not small_first\n return ans \n n = len(nums)\n return min(greedy(nums[:], True), greedy(nums[:], False))", "slug": "decrease-elements-to-make-array-zigzag", "post_title": "Python 3 | Greedy Two pass | Explanation", "user": "idontknoooo", "upvotes": 1, "views": 312, "problem_title": "decrease elements to make array zigzag", "number": 1144, "acceptance": 0.47, "difficulty": "Medium", "__index_level_0__": 17813, "question": "Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.\nAn array A is a zigzag array if either:\nEvery even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...\nOR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...\nReturn the minimum number of moves to transform the given array nums into a zigzag array.\n Example 1:\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: We can decrease 2 to 0 or 3 to 1.\nExample 2:\nInput: nums = [9,6,1,6,2]\nOutput: 4\n Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/binary-tree-coloring-game/discuss/797574/Python-3-or-DFS-or-One-pass-and-Three-pass-or-Explanation", "python_solutions": "class Solution:\n def btreeGameWinningMove(self, root: TreeNode, n: int, x: int) -> bool:\n first = None\n def count(node):\n nonlocal first\n total = 0\n if node: \n if node.val == x: first = node\n total += count(node.left) + count(node.right) + 1\n return total\n \n s = count(root) # Get total number of nodes, and x node (first player's choice)\n l = count(first.left) # Number of nodes on left branch \n r = count(first.right) # Number of nodes on right branch \n p = s-l-r-1 # Number of nodes on parent branch (anything else other than node, left subtree of node or right subtree of node)\n return l+r < p or l+p < r or r+p < l", "slug": "binary-tree-coloring-game", "post_title": "Python 3 | DFS | One pass & Three pass | Explanation", "user": "idontknoooo", "upvotes": 13, "views": 501, "problem_title": "binary tree coloring game", "number": 1145, "acceptance": 0.515, "difficulty": "Medium", "__index_level_0__": 17819, "question": "Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.\nInitially, the first player names a value x with 1 <= x <= n, and the second player names a value y with 1 <= y <= n and y != x. The first player colors the node with value x red, and the second player colors the node with value y blue.\nThen, the players take turns starting with the first player. In each turn, that player chooses a node of their color (red if player 1, blue if player 2) and colors an uncolored neighbor of the chosen node (either the left child, right child, or parent of the chosen node.)\nIf (and only if) a player cannot choose such a node in this way, they must pass their turn. If both players pass their turn, the game ends, and the winner is the player that colored more nodes.\nYou are the second player. If it is possible to choose such a y to ensure you win the game, return true. If it is not possible, return false.\n Example 1:\nInput: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\nOutput: true\nExplanation: The second player can choose the node with value 2.\nExample 2:\nInput: root = [1,2,3], n = 3, x = 1\nOutput: false\n Constraints:\nThe number of nodes in the tree is n.\n1 <= x <= n <= 100\nn is odd.\n1 <= Node.val <= n\nAll the values of the tree are unique." }, { "post_href": "https://leetcode.com/problems/longest-chunked-palindrome-decomposition/discuss/350711/Close-to-O(n)-Python-Rabin-Karp-Algorithm-with-two-pointer-technique-with-explanation-(~40ms)", "python_solutions": "class Solution:\n def longestDecomposition(self, text: str) -> int:\n \n\t\t# Used a prime number generator on the internet to grab a prime number to use.\n magic_prime = 32416189573\n \n\t\t# Standard 2 pointer technique variables.\n low = 0\n high = len(text) - 1\n \n\t\t# These are the hash tracking variables.\n\t\tcur_low_hash = 0\n cur_high_hash = 0\n cur_hash_length = 0\n \n\t\t# This is the number of parts we've found, i.e. the k value we need to return.\n\t\tk = 0\n \n while low < high:\n \n\t\t\t# To put the current letter onto our low hash (i.e. the one that goes forward from\n\t\t\t# the start of the string, we shift up the existing hash by multiplying by the base\n\t\t\t# of 26, and then adding on the new character by converting it to a number from 0 - 25.\n cur_low_hash *= 26 # Shift up by the base of 26.\n cur_low_hash += ord(text[low]) - 97 # Take away 97 so that it's between 0 and 25.\n \n\t\t\t\n\t\t\t# The high one, i.e. the one backwards from the end is a little more complex, as we want the \n\t\t\t# hash to represent the characters in forward order, not backwards. If we did the exact same\n\t\t\t# thing we did for low, the string abc would be represented as cba, which is not right.\t\n\t\t\t\n\t\t\t# Start by getting the character's 0 - 25 number.\n\t\t\thigh_char = ord(text[high]) - 97\n\t\t\t\n\t\t\t# The third argument to pow is modular arithmetic. It says to give the answer modulo the\n\t\t\t# magic prime (more on that below). Just pretend it isn't doing that for now if it confuses you. \n # What we're doing is making an int that puts the high character at the top, and then the \n\t\t\t# existing hash at the bottom.\n\t\t\tcur_high_hash = (high_char * pow(26, cur_hash_length, magic_prime)) + cur_high_hash \n \n\t\t\t# Mathematically, we can safely do this. Impressive, huh? I'm not going to go into here, but\n\t\t\t# I recommend studying up on modular arithmetic if you're confused.\n\t\t\t# The algorithm would be correct without doing this, BUT it'd be very slow as the numbers could\n\t\t\t# become tens of thousands of bits long. The problem with that of course is that comparing the\n\t\t\t# numbers would no longer be O(1) constant. So we need to keep them small.\n\t\t\tcur_low_hash %= magic_prime \n cur_high_hash %= magic_prime\n \n\t\t\t# And now some standard 2 pointer technique stuff.\n low += 1\n high -= 1\n cur_hash_length += 1\n \n\t\t\t# This piece of code checks if we currently have a match.\n # This is actually probabilistic, i.e. it is possible to get false positives.\n # For correctness, we should be verifying that this is actually correct.\n # We would do this by ensuring the characters in each hash (using\n\t\t\t# the low, high, and length variables we've been tracking) are\n\t\t\t# actually the same. But here I didn't bother as I figured Leetcode\n\t\t\t# would not have a test case that broke my specific prime.\n\t\t\tif cur_low_hash == cur_high_hash:\n k += 2 # We have just added 2 new strings to k.\n # And reset our hashing variables.\n\t\t\t\tcur_low_hash = 0\n cur_high_hash = 0\n cur_hash_length = 0\n \n\t\t# At the end, there are a couple of edge cases we need to address....\n\t\t# The first is if there is a middle character left.\n\t\t# The second is a non-paired off string in the middle.\n if (cur_hash_length == 0 and low == high) or cur_hash_length > 0:\n k += 1\n \n return k", "slug": "longest-chunked-palindrome-decomposition", "post_title": "Close to O(n) Python, Rabin Karp Algorithm with two pointer technique with explanation (~40ms)", "user": "Hai_dee", "upvotes": 33, "views": 2400, "problem_title": "longest chunked palindrome decomposition", "number": 1147, "acceptance": 0.597, "difficulty": "Hard", "__index_level_0__": 17823, "question": "You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:\nsubtexti is a non-empty string.\nThe concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).\nsubtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).\nReturn the largest possible value of k.\n Example 1:\nInput: text = \"ghiabcdefhelloadamhelloabcdefghi\"\nOutput: 7\nExplanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\nExample 2:\nInput: text = \"merchant\"\nOutput: 1\nExplanation: We can split the string on \"(merchant)\".\nExample 3:\nInput: text = \"antaprezatepzapreanta\"\nOutput: 11\nExplanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".\n Constraints:\n1 <= text.length <= 1000\ntext consists only of lowercase English characters." }, { "post_href": "https://leetcode.com/problems/day-of-the-year/discuss/449866/Python-3-Four-liner-Simple-Solution", "python_solutions": "class Solution:\n def dayOfYear(self, date: str) -> int:\n y, m, d = map(int, date.split('-'))\n days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n if (y % 400) == 0 or ((y % 4 == 0) and (y % 100 != 0)): days[1] = 29\n return d + sum(days[:m-1])", "slug": "day-of-the-year", "post_title": "Python 3 - Four liner - Simple Solution", "user": "mmbhatk", "upvotes": 30, "views": 1700, "problem_title": "day of the year", "number": 1154, "acceptance": 0.501, "difficulty": "Easy", "__index_level_0__": 17830, "question": "Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.\n Example 1:\nInput: date = \"2019-01-09\"\nOutput: 9\nExplanation: Given date is the 9th day of the year in 2019.\nExample 2:\nInput: date = \"2019-02-10\"\nOutput: 41\n Constraints:\ndate.length == 10\ndate[4] == date[7] == '-', and all other date[i]'s are digits\ndate represents a calendar date between Jan 1st, 1900 and Dec 31th, 2019." }, { "post_href": "https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/discuss/822515/Python-3-or-DP-or-Explanation", "python_solutions": "class Solution:\n def numRollsToTarget(self, d: int, f: int, target: int) -> int:\n if d*f < target: return 0 # Handle special case, it speed things up, but not necessary\n elif d*f == target: return 1 # Handle special case, it speed things up, but not necessary\n mod = int(10**9 + 7)\n dp = [[0] * (target+1) for _ in range(d+1)] \n for j in range(1, min(f+1, target+1)): dp[1][j] = 1\n for i in range(2, d+1):\n for j in range(1, target+1):\n for k in range(1, f+1):\n if j - k >= 0: dp[i][j] += dp[i-1][j-k]\n dp[i][j] %= mod \n return dp[-1][-1]", "slug": "number-of-dice-rolls-with-target-sum", "post_title": "Python 3 | DP | Explanation", "user": "idontknoooo", "upvotes": 12, "views": 1400, "problem_title": "number of dice rolls with target sum", "number": 1155, "acceptance": 0.536, "difficulty": "Medium", "__index_level_0__": 17853, "question": "You have n dice, and each dice has k faces numbered from 1 to k.\nGiven three integers n, k, and target, return the number of possible ways (out of the kn total ways) to roll the dice, so the sum of the face-up numbers equals target. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: n = 1, k = 6, target = 3\nOutput: 1\nExplanation: You throw one die with 6 faces.\nThere is only one way to get a sum of 3.\nExample 2:\nInput: n = 2, k = 6, target = 7\nOutput: 6\nExplanation: You throw two dice, each with 6 faces.\nThere are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.\nExample 3:\nInput: n = 30, k = 30, target = 500\nOutput: 222616187\nExplanation: The answer must be returned modulo 109 + 7.\n Constraints:\n1 <= n, k <= 30\n1 <= target <= 1000" }, { "post_href": "https://leetcode.com/problems/swap-for-longest-repeated-character-substring/discuss/2255000/PYTHON-or-AS-INTERVIEWER-WANTS-or-WITHOUT-ITERTOOLS-or-WELL-EXPLAINED-or", "python_solutions": "class Solution:\n def maxRepOpt1(self, text: str) -> int:\n first_occurence,last_occurence = {},{}\n ans,prev,count = 1,0,0\n n = len(text)\n \n for i in range(n):\n if text[i] not in first_occurence: first_occurence[text[i]] = i\n last_occurence[text[i]] = i\n \n for i in range(n+1):\n if i < n and text[i] == text[prev]:\n count += 1\n else:\n if first_occurence[text[prev]] < prev or last_occurence[text[prev]] > i : count += 1\n ans = max(ans,count)\n count = 1\n prev = i\n \n def someWork(item,before,after):\n count = 0\n while before >= 0 and text[before] == item: \n count += 1\n before -= 1\n while after < n and text[after] == item:\n count += 1\n after += 1\n if first_occurence[item] <= before or last_occurence[item] >= after:count+=1\n return count\n \n for i in range(1,n-1):\n ans = max(ans,someWork(text[i+1],i-1,i+1))\n return ans", "slug": "swap-for-longest-repeated-character-substring", "post_title": "PYTHON | AS INTERVIEWER WANTS | WITHOUT ITERTOOLS | WELL EXPLAINED |", "user": "reaper_27", "upvotes": 1, "views": 178, "problem_title": "swap for longest repeated character substring", "number": 1156, "acceptance": 0.4539999999999999, "difficulty": "Medium", "__index_level_0__": 17915, "question": "You are given a string text. You can swap two of the characters in the text.\nReturn the length of the longest substring with repeated characters.\n Example 1:\nInput: text = \"ababa\"\nOutput: 3\nExplanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.\nExample 2:\nInput: text = \"aaabaaa\"\nOutput: 6\nExplanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.\nExample 3:\nInput: text = \"aaaaa\"\nOutput: 5\nExplanation: No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.\n Constraints:\n1 <= text.length <= 2 * 104\ntext consist of lowercase English characters only." }, { "post_href": "https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/2177578/Python3-O(n2)-oror-O(1)-Runtime%3A-96ms-97.20-Memory%3A-14.5mb-84.92", "python_solutions": "class Solution:\n# O(n^2) || O(1)\n# Runtime: 96ms 97.20% Memory: 14.5mb 84.92%\n def countCharacters(self, words: List[str], chars: str) -> int:\n ans=0\n for word in words:\n for ch in word:\n if word.count(ch)>chars.count(ch):\n break\n else:\n ans+=len(word)\n \n return ans", "slug": "find-words-that-can-be-formed-by-characters", "post_title": "Python3 O(n^2) || O(1) Runtime: 96ms 97.20% Memory: 14.5mb 84.92%", "user": "arshergon", "upvotes": 5, "views": 350, "problem_title": "find words that can be formed by characters", "number": 1160, "acceptance": 0.677, "difficulty": "Easy", "__index_level_0__": 17920, "question": "You are given an array of strings words and a string chars.\nA string is good if it can be formed by characters from chars (each character can only be used once).\nReturn the sum of lengths of all good strings in words.\n Example 1:\nInput: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\nOutput: 6\nExplanation: The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\nExample 2:\nInput: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\nOutput: 10\nExplanation: The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length, chars.length <= 100\nwords[i] and chars consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/discuss/848959/BFS-Python-solution-with-comments!", "python_solutions": "class Solution:\n def maxLevelSum(self, root: TreeNode) -> int:\n \n queue = deque() #init a queue for storing nodes as we traverse the tree\n queue.append(root) #first node (level = 1) inserted\n \n #bfs = [] #just for understanding- this will be a bfs list to store nodes as we conduct the search, but we don't need it here.\n \n level_sum = 0 # for sum of each level\n level_nodes = 1 # for knowing when a particular level has ended\n \n sum_of_levels = [] #list to store all levels sum of nodes\n \n while queue: #begin BFS\n node = queue.popleft() \n #bfs.append(node)\n level_sum += node.val #add node \n \n if node.left:\n queue.append(node.left)\n \n if node.right:\n queue.append(node.right)\n \n level_nodes -= 1 #reduce level number by 1, as we popped out a node\n if level_nodes == 0: # if 0, then a level has ended, so calculate the sum\n sum_of_levels.append(level_sum)\n level_sum = 0\n level_nodes = len(queue)\n \n return sum_of_levels.index(max(sum_of_levels)) + 1 #return index of max level sum", "slug": "maximum-level-sum-of-a-binary-tree", "post_title": "BFS Python solution - with comments!", "user": "tintsTy", "upvotes": 1, "views": 58, "problem_title": "maximum level sum of a binary tree", "number": 1161, "acceptance": 0.6609999999999999, "difficulty": "Medium", "__index_level_0__": 17951, "question": "Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.\nReturn the smallest level x such that the sum of all the values of nodes at level x is maximal.\n Example 1:\nInput: root = [1,7,0,7,-8,null,null]\nOutput: 2\nExplanation: \nLevel 1 sum = 1.\nLevel 2 sum = 7 + 0 = 7.\nLevel 3 sum = 7 + -8 = -1.\nSo we return the level with the maximum sum which is level 2.\nExample 2:\nInput: root = [989,null,10250,98693,-89388,null,null,null,-32127]\nOutput: 2\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n-105 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/as-far-from-land-as-possible/discuss/1158339/A-general-Explanation-w-Animation", "python_solutions": "class Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n \n\t\t# The # of rows and # of cols\n M, N, result = len(grid), len(grid[0]), -1\n \n\t\t# A list of valid points\n valid_points = {(i, j) for i in range(M) for j in range(N)}\n \n\t\t# A double-ended queue of \"land\" cells\n queue = collections.deque([(i, j) for i in range(M) for j in range(N) if grid[i][j] == 1])\n \n # Check if all land, or all water, an edge case\n if len(queue) == M*N or len(queue) == 0:\n return -1\n \n\t\t# BFS\n while queue:\n\t\t\t\n\t\t\t# One iteration here\n for _ in range(len(queue)):\n i, j = queue.popleft()\n for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if (x, y) not in valid_points: continue\n if grid[x][y] == 1: continue \n queue.append((x, y))\n grid[x][y] = 1 # We mark water cells as land to avoid visiting them again\n \n\t\t\t# Increase the iteration/result count\n result += 1\n \n return result", "slug": "as-far-from-land-as-possible", "post_title": "A general Explanation w/ Animation", "user": "dev-josh", "upvotes": 8, "views": 367, "problem_title": "as far from land as possible", "number": 1162, "acceptance": 0.486, "difficulty": "Medium", "__index_level_0__": 17962, "question": "Given an n x n grid containing only values 0 and 1, where 0 represents water and 1 represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return -1.\nThe distance used in this problem is the Manhattan distance: the distance between two cells (x0, y0) and (x1, y1) is |x0 - x1| + |y0 - y1|.\n Example 1:\nInput: grid = [[1,0,1],[0,0,0],[1,0,1]]\nOutput: 2\nExplanation: The cell (1, 1) is as far as possible from all the land with distance 2.\nExample 2:\nInput: grid = [[1,0,0],[0,0,0],[0,0,0]]\nOutput: 4\nExplanation: The cell (2, 2) is as far as possible from all the land with distance 4.\n Constraints:\nn == grid.length\nn == grid[i].length\n1 <= n <= 100\ngrid[i][j] is 0 or 1" }, { "post_href": "https://leetcode.com/problems/last-substring-in-lexicographical-order/discuss/361321/Solution-in-Python-3-(beats-100)", "python_solutions": "class Solution:\n def lastSubstring(self, s: str) -> str:\n \tS, L, a = [ord(i) for i in s] + [0], len(s), 1\n \tM = max(S)\n \tI = [i for i in range(L) if S[i] == M]\n \tif len(I) == L: return s\n \twhile len(I) != 1:\n \t\tb = [S[i + a] for i in I]\n \t\tM, a = max(b), a + 1\n \t\tI = [I[i] for i, j in enumerate(b) if j == M]\n \treturn s[I[0]:]\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "last-substring-in-lexicographical-order", "post_title": "Solution in Python 3 (beats 100%)", "user": "junaidmansuri", "upvotes": 3, "views": 742, "problem_title": "last substring in lexicographical order", "number": 1163, "acceptance": 0.35, "difficulty": "Hard", "__index_level_0__": 17973, "question": "Given a string s, return the last substring of s in lexicographical order.\n Example 1:\nInput: s = \"abab\"\nOutput: \"bab\"\nExplanation: The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".\nExample 2:\nInput: s = \"leetcode\"\nOutput: \"tcode\"\n Constraints:\n1 <= s.length <= 4 * 105\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/invalid-transactions/discuss/670649/Simple-clean-python-only-10-lines", "python_solutions": "class Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n invalid = []\n \n for i, t1 in enumerate(transactions):\n name1, time1, amount1, city1 = t1.split(',')\n if int(amount1) > 1000:\n invalid.append(t1)\n continue\n for j, t2 in enumerate(transactions):\n if i != j: \n name2, time2, amount2, city2 = t2.split(',')\n if name1 == name2 and city1 != city2 and abs(int(time1) - int(time2)) <= 60:\n invalid.append(t1)\n break\n \n return invalid", "slug": "invalid-transactions", "post_title": "Simple clean python - only 10 lines", "user": "auwdish", "upvotes": 7, "views": 1600, "problem_title": "invalid transactions", "number": 1169, "acceptance": 0.312, "difficulty": "Medium", "__index_level_0__": 17979, "question": "A transaction is possibly invalid if:\nthe amount exceeds $1000, or;\nif it occurs within (and including) 60 minutes of another transaction with the same name in a different city.\nYou are given an array of strings transaction where transactions[i] consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.\nReturn a list of transactions that are possibly invalid. You may return the answer in any order.\n Example 1:\nInput: transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nOutput: [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\nExplanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.\nExample 2:\nInput: transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]\nOutput: [\"alice,50,1200,mtv\"]\nExample 3:\nInput: transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]\nOutput: [\"bob,50,1200,mtv\"]\n Constraints:\ntransactions.length <= 1000\nEach transactions[i] takes the form \"{name},{time},{amount},{city}\"\nEach {name} and {city} consist of lowercase English letters, and have lengths between 1 and 10.\nEach {time} consist of digits, and represent an integer between 0 and 1000.\nEach {amount} consist of digits, and represent an integer between 0 and 2000." }, { "post_href": "https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character/discuss/401039/Python-Simple-Code-Memory-efficient", "python_solutions": "class Solution:\n\tdef numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n\t\tdef f(s):\n\t\t\tt = sorted(list(s))[0]\n\t\t\treturn s.count(t)\n\t\tquery = [f(x) for x in queries]\n\t\tword = [f(x) for x in words]\n\t\tm = []\n\t\tfor x in query:\n\t\t\tcount = 0\n\t\t\tfor y in word:\n\t\t\t\tif y>x:\n\t\t\t\t\tcount+=1\n\t\t\tm.append(count)\n\t\treturn m", "slug": "compare-strings-by-frequency-of-the-smallest-character", "post_title": "Python Simple Code Memory efficient", "user": "saffi", "upvotes": 14, "views": 1700, "problem_title": "compare strings by frequency of the smallest character", "number": 1170, "acceptance": 0.614, "difficulty": "Medium", "__index_level_0__": 17991, "question": "Let the function f(s) be the frequency of the lexicographically smallest character in a non-empty string s. For example, if s = \"dcce\" then f(s) = 2 because the lexicographically smallest character is 'c', which has a frequency of 2.\nYou are given an array of strings words and another array of query strings queries. For each query queries[i], count the number of words in words such that f(queries[i]) < f(W) for each W in words.\nReturn an integer array answer, where each answer[i] is the answer to the ith query.\n Example 1:\nInput: queries = [\"cbd\"], words = [\"zaaaz\"]\nOutput: [1]\nExplanation: On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").\nExample 2:\nInput: queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\nOutput: [1,2]\nExplanation: On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").\n Constraints:\n1 <= queries.length <= 2000\n1 <= words.length <= 2000\n1 <= queries[i].length, words[i].length <= 10\nqueries[i][j], words[i][j] consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/discuss/1701518/Easiest-Approach-oror-Clean-and-Concise-oror-Well-Explained", "python_solutions": "class Solution:\n\tdef removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\n\t\tdummy = ListNode(0,head)\n\t\tpre = 0\n\t\tdic = {0: dummy}\n\n\t\twhile head:\n\t\t\tpre+=head.val\n\t\t\tdic[pre] = head\n\t\t\thead = head.next\n\n\t\thead = dummy\n\t\tpre = 0\n\t\twhile head:\n\t\t\tpre+=head.val\n\t\t\thead.next = dic[pre].next\n\t\t\thead = head.next\n\n\t\treturn dummy.next", "slug": "remove-zero-sum-consecutive-nodes-from-linked-list", "post_title": "\ud83d\udccc\ud83d\udccc Easiest Approach || Clean & Concise || Well-Explained \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 7, "views": 282, "problem_title": "remove zero sum consecutive nodes from linked list", "number": 1171, "acceptance": 0.43, "difficulty": "Medium", "__index_level_0__": 18010, "question": "Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.\nAfter doing so, return the head of the final linked list. You may return any such answer.\n (Note that in the examples below, all sequences are serializations of ListNode objects.)\nExample 1:\nInput: head = [1,2,-3,3,1]\nOutput: [3,1]\nNote: The answer [1,2,1] would also be accepted.\nExample 2:\nInput: head = [1,2,3,-3,4]\nOutput: [1,2,4]\nExample 3:\nInput: head = [1,2,3,-3,-2]\nOutput: [1]\n Constraints:\nThe given linked list will contain between 1 and 1000 nodes.\nEach node in the linked list has -1000 <= node.val <= 1000." }, { "post_href": "https://leetcode.com/problems/prime-arrangements/discuss/2794041/Find-product-between-factorial-of-primes-and-non-primes", "python_solutions": "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n # find number of prime indices\n # ways to arrange prime indices\n # is prime indices factorial\n # amount of non-prime indices is\n # n - prime indices \n # the factorial of non - prime indices\n # times the factorial of prime indices\n # is the amount of ways to arrange the \n # prime numbers and i be valid \n # use helper to find factorial of a number\n # use helper to see if a number is prime\n # time O(n ^ 2) space O(1)\n\n def isPrime(num):\n if num <= 1:\n return False\n for i in range(2, num // 2 + 1):\n if num % i == 0:\n return False\n return True\n\n def factorial(num):\n res = 1\n for i in range(1, num + 1):\n res *= i\n return res\n \n primes = 0\n for num in range(1, n + 1):\n if isPrime(num):\n primes += 1\n return int(factorial(primes) * factorial(n - primes) % (10**9 + 7))", "slug": "prime-arrangements", "post_title": "Find product between factorial of primes & non-primes", "user": "andrewnerdimo", "upvotes": 0, "views": 4, "problem_title": "prime arrangements", "number": 1175, "acceptance": 0.537, "difficulty": "Easy", "__index_level_0__": 18014, "question": "Return the number of permutations of 1 to n so that prime numbers are at prime indices (1-indexed.)\n(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)\nSince the answer may be large, return the answer modulo 10^9 + 7.\n Example 1:\nInput: n = 5\nOutput: 12\nExplanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\nExample 2:\nInput: n = 100\nOutput: 682289015\n Constraints:\n1 <= n <= 100" }, { "post_href": "https://leetcode.com/problems/can-make-palindrome-from-substring/discuss/1201798/Python3-prefix-freq", "python_solutions": "class Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n prefix = [[0]*26]\n for c in s: \n elem = prefix[-1].copy()\n elem[ord(c)-97] += 1\n prefix.append(elem)\n \n ans = []\n for left, right, k in queries: \n cnt = sum(1&(prefix[right+1][i] - prefix[left][i]) for i in range(26))\n ans.append(cnt <= 2*k+1)\n return ans", "slug": "can-make-palindrome-from-substring", "post_title": "[Python3] prefix freq", "user": "ye15", "upvotes": 2, "views": 222, "problem_title": "can make palindrome from substring", "number": 1177, "acceptance": 0.38, "difficulty": "Medium", "__index_level_0__": 18020, "question": "You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.\nIf the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.\nReturn a boolean array answer where answer[i] is the result of the ith query queries[i].\nNote that each letter is counted individually for replacement, so if, for example s[lefti...righti] = \"aaa\", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.\n Example :\nInput: s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\nOutput: [true,false,false,true,true]\nExplanation:\nqueries[0]: substring = \"d\", is palidrome.\nqueries[1]: substring = \"bc\", is not palidrome.\nqueries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\nqueries[3]: substring = \"abcd\", could be changed to \"abba\" which is palidrome. Also this can be changed to \"baab\" first rearrange it \"bacd\" then replace \"cd\" with \"ab\".\nqueries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.\nExample 2:\nInput: s = \"lyb\", queries = [[0,1,0],[2,2,1]]\nOutput: [false,true]\n Constraints:\n1 <= s.length, queries.length <= 105\n0 <= lefti <= righti < s.length\n0 <= ki <= s.length\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/number-of-valid-words-for-each-puzzle/discuss/1567415/Python-TrieBitmasking-Solutions-with-Explanation", "python_solutions": "class Solution:\n def mask(self, word: str) -> int:\n result = 0\n for ch in word:\n result |= 1 << (ord(ch)-ord('a'))\n return result\n\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n word_count = Counter(self.mask(word) for word in words)\n result = []\n for puzzle in puzzles:\n original_mask, first = self.mask(puzzle[1:]), self.mask(puzzle[0])\n curr_mask, count = original_mask, word_count[first]\n while curr_mask:\n count += word_count[curr_mask|first]\n curr_mask = (curr_mask-1)&original_mask\n result.append(count)\n return result", "slug": "number-of-valid-words-for-each-puzzle", "post_title": "[Python] Trie/Bitmasking Solutions with Explanation", "user": "zayne-siew", "upvotes": 16, "views": 596, "problem_title": "number of valid words for each puzzle", "number": 1178, "acceptance": 0.465, "difficulty": "Hard", "__index_level_0__": 18025, "question": "With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:\nword contains the first letter of puzzle.\nFor each letter in word, that letter is in puzzle.\nFor example, if the puzzle is \"abcdefg\", then valid words are \"faced\", \"cabbage\", and \"baggage\", while\ninvalid words are \"beefed\" (does not include 'a') and \"based\" (includes 's' which is not in the puzzle).\nReturn an array answer, where answer[i] is the number of words in the given word list words that is valid with respect to the puzzle puzzles[i].\n Example 1:\nInput: words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\nOutput: [1,1,3,2,4,0]\nExplanation: \n1 valid word for \"aboveyz\" : \"aaaa\" \n1 valid word for \"abrodyz\" : \"aaaa\"\n3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\nThere are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.\nExample 2:\nInput: words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]\nOutput: [0,1,3,2,0]\n Constraints:\n1 <= words.length <= 105\n4 <= words[i].length <= 50\n1 <= puzzles.length <= 104\npuzzles[i].length == 7\nwords[i] and puzzles[i] consist of lowercase English letters.\nEach puzzles[i] does not contain repeated characters." }, { "post_href": "https://leetcode.com/problems/distance-between-bus-stops/discuss/377844/Python-Explanation", "python_solutions": "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n a, b = min(start, destination), max(start, destination)\n return min(sum(distance[a:b]), sum(distance) - sum(distance[a:b]))", "slug": "distance-between-bus-stops", "post_title": "Python - Explanation", "user": "nuclearoreo", "upvotes": 8, "views": 400, "problem_title": "distance between bus stops", "number": 1184, "acceptance": 0.541, "difficulty": "Easy", "__index_level_0__": 18028, "question": "A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.\nThe bus goes along both directions i.e. clockwise and counterclockwise.\nReturn the shortest distance between the given start and destination stops.\n Example 1:\nInput: distance = [1,2,3,4], start = 0, destination = 1\nOutput: 1\nExplanation: Distance between 0 and 1 is 1 or 9, minimum is 1.\n Example 2:\nInput: distance = [1,2,3,4], start = 0, destination = 2\nOutput: 3\nExplanation: Distance between 0 and 2 is 3 or 7, minimum is 3.\n Example 3:\nInput: distance = [1,2,3,4], start = 0, destination = 3\nOutput: 4\nExplanation: Distance between 0 and 3 is 6 or 4, minimum is 4.\n Constraints:\n1 <= n <= 10^4\ndistance.length == n\n0 <= start, destination < n\n0 <= distance[i] <= 10^4" }, { "post_href": "https://leetcode.com/problems/day-of-the-week/discuss/1084728/Python3-simple-solution", "python_solutions": "class Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n prev_year = year - 1\n days = prev_year * 365 + prev_year // 4 - prev_year // 100 + prev_year // 400\n days += sum([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][:month - 1])\n days += day\n\n if month > 2 and ((year % 4 == 0 and year % 100 != 0) or year % 400 == 0):\n days += 1\n\n return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][days % 7]", "slug": "day-of-the-week", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 7, "views": 333, "problem_title": "day of the week", "number": 1185, "acceptance": 0.5760000000000001, "difficulty": "Easy", "__index_level_0__": 18049, "question": "Given a date, return the corresponding day of the week for that date.\nThe input is given as three integers representing the day, month and year respectively.\nReturn the answer as one of the following values {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}.\n Example 1:\nInput: day = 31, month = 8, year = 2019\nOutput: \"Saturday\"\nExample 2:\nInput: day = 18, month = 7, year = 1999\nOutput: \"Sunday\"\nExample 3:\nInput: day = 15, month = 8, year = 1993\nOutput: \"Sunday\"\n Constraints:\nThe given dates are valid dates between the years 1971 and 2100." }, { "post_href": "https://leetcode.com/problems/maximum-subarray-sum-with-one-deletion/discuss/1104253/Python-Kadane's-Algorithm-easy-solution", "python_solutions": "class Solution:\n def maximumSum(self, arr: List[int]) -> int:\n n = len(arr)\n #maximum subarray starting from the last element i.e. backwards \n prefix_sum_ending = [float('-inf')]*n\n #maximum subarray starting from the first element i.e forwards\n prefix_sum_starting = [float('-inf')]*n\n prefix_sum_ending[n-1] = arr[n-1]\n prefix_sum_starting[0] = arr[0]\n \n for i in range(1,n):\n prefix_sum_starting[i] = max(prefix_sum_starting[i-1]+arr[i], arr[i])\n for i in range(n-2,-1,-1):\n prefix_sum_ending[i] = max(prefix_sum_ending[i+1]+arr[i], arr[i])\n \n max_without_deletion = max(prefix_sum_starting)\n max_with_deletion = float('-inf')\n for i in range(1,n-1):\n max_with_deletion = max(max_with_deletion, prefix_sum_starting[i-1]+prefix_sum_ending[i+1])\n \n return max(max_without_deletion, max_with_deletion)", "slug": "maximum-subarray-sum-with-one-deletion", "post_title": "[Python] Kadane's Algorithm easy solution", "user": "msd1311", "upvotes": 8, "views": 522, "problem_title": "maximum subarray sum with one deletion", "number": 1186, "acceptance": 0.413, "difficulty": "Medium", "__index_level_0__": 18058, "question": "Given an array of integers, return the maximum sum for a non-empty subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.\nNote that the subarray needs to be non-empty after deleting one element.\n Example 1:\nInput: arr = [1,-2,0,3]\nOutput: 4\nExplanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.\nExample 2:\nInput: arr = [1,-2,-2,3]\nOutput: 3\nExplanation: We just choose [3] and it's the maximum sum.\nExample 3:\nInput: arr = [-1,-1,-1,-1]\nOutput: -1\nExplanation: The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.\n Constraints:\n1 <= arr.length <= 105\n-104 <= arr[i] <= 104" }, { "post_href": "https://leetcode.com/problems/make-array-strictly-increasing/discuss/1155655/Python3-top-down-dp", "python_solutions": "class Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n arr2.sort()\n \n @cache\n def fn(i, prev): \n \"\"\"Return min ops to make arr1[i:] increasing w/ given previous element.\"\"\"\n if i == len(arr1): return 0 \n ans = inf \n if (prev < arr1[i]): ans = fn(i+1, arr1[i])\n k = bisect_right(arr2, prev)\n if k < len(arr2): ans = min(ans, 1 + fn(i+1, arr2[k]))\n return ans \n \n ans = fn(0, -inf)\n return ans if ans < inf else -1", "slug": "make-array-strictly-increasing", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 196, "problem_title": "make array strictly increasing", "number": 1187, "acceptance": 0.452, "difficulty": "Hard", "__index_level_0__": 18066, "question": "Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.\nIn one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].\nIf there is no way to make arr1 strictly increasing, return -1.\n Example 1:\nInput: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\nOutput: 1\nExplanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].\nExample 2:\nInput: arr1 = [1,5,3,6,7], arr2 = [4,3,1]\nOutput: 2\nExplanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].\nExample 3:\nInput: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\nOutput: -1\nExplanation: You can't make arr1 strictly increasing.\n Constraints:\n1 <= arr1.length, arr2.length <= 2000\n0 <= arr1[i], arr2[i] <= 10^9\n " }, { "post_href": "https://leetcode.com/problems/maximum-number-of-balloons/discuss/1013213/2-Line-Python-using-Counter", "python_solutions": "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n c = collections.Counter(text)\n return min(c['b'],c['a'],c['l']//2,c['o']//2,c['n'])", "slug": "maximum-number-of-balloons", "post_title": "2 Line Python using Counter", "user": "majinlion", "upvotes": 8, "views": 385, "problem_title": "maximum number of balloons", "number": 1189, "acceptance": 0.618, "difficulty": "Easy", "__index_level_0__": 18068, "question": "Given a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible.\nYou can use each character in text at most once. Return the maximum number of instances that can be formed.\n Example 1:\nInput: text = \"nlaebolko\"\nOutput: 1\nExample 2:\nInput: text = \"loonbalxballpoon\"\nOutput: 2\nExample 3:\nInput: text = \"leetcode\"\nOutput: 0\n Constraints:\n1 <= text.length <= 104\ntext consists of lower case English letters only." }, { "post_href": "https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/discuss/2290806/PYTHON-SOL-or-RECURSION-AND-STACK-SOL-or-DETAILED-EXPLANATION-WITH-PICTRUE-or", "python_solutions": "class Solution:\n def reverseParentheses(self, s: str) -> str:\n def solve(string):\n n = len(string)\n word = \"\"\n i = 0\n while i 0:\n nums[i] += nums[i-1]\n return max(max(nums), 0)\n \n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n sums = sum(arr)\n mod = 10**9 + 7\n if k == 1:\n return self.kadane(arr) % (mod)\n if sums > 0:\n return (self.kadane(arr+arr) + (k-2)*sums) % (mod)\n else:\n return self.kadane(arr+arr) % (mod)", "slug": "k-concatenation-maximum-sum", "post_title": "Python easy to read and understand | kadane", "user": "sanial2001", "upvotes": 2, "views": 147, "problem_title": "k concatenation maximum sum", "number": 1191, "acceptance": 0.239, "difficulty": "Medium", "__index_level_0__": 18122, "question": "Given an integer array arr and an integer k, modify the array by repeating it k times.\nFor example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].\nReturn the maximum sub-array sum in the modified array. Note that the length of the sub-array can be 0 and its sum in that case is 0.\nAs the answer can be very large, return the answer modulo 109 + 7.\n Example 1:\nInput: arr = [1,2], k = 3\nOutput: 9\nExample 2:\nInput: arr = [1,-2,1], k = 5\nOutput: 2\nExample 3:\nInput: arr = [-1,-2], k = 7\nOutput: 0\n Constraints:\n1 <= arr.length <= 105\n1 <= k <= 105\n-104 <= arr[i] <= 104" }, { "post_href": "https://leetcode.com/problems/critical-connections-in-a-network/discuss/382440/Python-DFS-Tree-Solution-(O(V%2BE)-complexity)", "python_solutions": "class Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n \n dic = collections.defaultdict(list)\n for c in connections:\n u, v = c\n dic[u].append(v)\n dic[v].append(u)\n \n \n timer = 0\n \n depth, lowest, parent, visited = [float(\"inf\")]*n, [float(\"inf\")]*n, [float(\"inf\")]*n, [False]*n\n res = []\n \n def find(u):\n \n nonlocal timer\n \n visited[u] = True\n depth[u], lowest[u] = timer, timer\n timer += 1\n \n for v in dic[u]: \n \n if not visited[v]:\n parent[v] = u\n find(v)\n if lowest[v]>depth[u]:\n res.append([u,v])\n \n if parent[u]!=v:\n lowest[u] = min(lowest[u], lowest[v])\n \n find(0)\n return res", "slug": "critical-connections-in-a-network", "post_title": "Python DFS-Tree Solution (O(V+E) complexity)", "user": "ywen1995", "upvotes": 16, "views": 5500, "problem_title": "critical connections in a network", "number": 1192, "acceptance": 0.545, "difficulty": "Hard", "__index_level_0__": 18130, "question": "There are n servers numbered from 0 to n - 1 connected by undirected server-to-server connections forming a network where connections[i] = [ai, bi] represents a connection between servers ai and bi. Any server can reach other servers directly or indirectly through the network.\nA critical connection is a connection that, if removed, will make some servers unable to reach some other server.\nReturn all critical connections in the network in any order.\n Example 1:\nInput: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\nOutput: [[1,3]]\nExplanation: [[3,1]] is also accepted.\nExample 2:\nInput: n = 2, connections = [[0,1]]\nOutput: [[0,1]]\n Constraints:\n2 <= n <= 105\nn - 1 <= connections.length <= 105\n0 <= ai, bi <= n - 1\nai != bi\nThere are no repeated connections." }, { "post_href": "https://leetcode.com/problems/minimum-absolute-difference/discuss/569795/Easy-to-Understand-or-Faster-or-Simple-or-Python-Solution", "python_solutions": "class Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n arr.sort()\n m = float('inf')\n out = []\n for i in range(1, len(arr)):\n prev = arr[i - 1]\n curr = abs(prev - arr[i])\n if curr < m:\n out = [[prev, arr[i]]]\n m = curr\n elif curr == m: out.append([prev, arr[i]])\n return out", "slug": "minimum-absolute-difference", "post_title": "Easy to Understand | Faster | Simple | Python Solution", "user": "Mrmagician", "upvotes": 16, "views": 1300, "problem_title": "minimum absolute difference", "number": 1200, "acceptance": 0.6970000000000001, "difficulty": "Easy", "__index_level_0__": 18141, "question": "Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.\nReturn a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows\na, b are from arr\na < b\nb - a equals to the minimum absolute difference of any two elements in arr\n Example 1:\nInput: arr = [4,2,1,3]\nOutput: [[1,2],[2,3],[3,4]]\nExplanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.\nExample 2:\nInput: arr = [1,3,6,10,15]\nOutput: [[1,3]]\nExample 3:\nInput: arr = [3,8,-10,23,19,-4,-14,27]\nOutput: [[-14,-10],[19,23],[23,27]]\n Constraints:\n2 <= arr.length <= 105\n-106 <= arr[i] <= 106" }, { "post_href": "https://leetcode.com/problems/ugly-number-iii/discuss/723589/Python3-inconsistent-definition-of-%22ugly-numbers%22", "python_solutions": "class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n # inclusion-exclusion principle\n ab = a*b//gcd(a, b)\n bc = b*c//gcd(b, c)\n ca = c*a//gcd(c, a)\n abc = ab*c//gcd(ab, c)\n \n lo, hi = 1, n*min(a, b, c)\n while lo < hi: \n mid = lo + hi >> 1\n if mid//a + mid//b + mid//c - mid//ab - mid//bc - mid//ca + mid//abc < n: lo = mid + 1\n else: hi = mid \n return lo", "slug": "ugly-number-iii", "post_title": "[Python3] inconsistent definition of \"ugly numbers\"", "user": "ye15", "upvotes": 33, "views": 1000, "problem_title": "ugly number iii", "number": 1201, "acceptance": 0.285, "difficulty": "Medium", "__index_level_0__": 18183, "question": "An ugly number is a positive integer that is divisible by a, b, or c.\nGiven four integers n, a, b, and c, return the nth ugly number.\n Example 1:\nInput: n = 3, a = 2, b = 3, c = 5\nOutput: 4\nExplanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.\nExample 2:\nInput: n = 4, a = 2, b = 3, c = 4\nOutput: 6\nExplanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.\nExample 3:\nInput: n = 5, a = 2, b = 11, c = 13\nOutput: 10\nExplanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.\n Constraints:\n1 <= n, a, b, c <= 109\n1 <= a * b * c <= 1018\nIt is guaranteed that the result will be in range [1, 2 * 109]." }, { "post_href": "https://leetcode.com/problems/smallest-string-with-swaps/discuss/1985185/Python3-UNION-FIND-()**-Explained", "python_solutions": "class Solution:\n def union(self, a, b):\n self.parent[self.find(a)] = self.find(b)\n\t\t\n def find(self, a):\n if self.parent[a] != a:\n self.parent[a] = self.find(self.parent[a])\n\n return self.parent[a]\n \n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n\t\t# 1. Union-Find\n self.parent = list(range(len(s)))\n for a, b in pairs:\n self.union(a, b)\n\n\t\t# 2. Grouping\n group = defaultdict(lambda: ([], [])) \n for i, ch in enumerate(s):\n parent = self.find(i)\n group[parent][0].append(i)\n group[parent][1].append(ch)\n\n\t\t# 3. Sorting\n res = [''] * len(s)\n for ids, chars in group.values():\n ids.sort()\n chars.sort()\n for ch, i in zip(chars, ids):\n res[i] = ch\n \n return ''.join(res)", "slug": "smallest-string-with-swaps", "post_title": "\u2714\ufe0f [Python3] UNION-FIND (\u2741\u00b4\u25bd`\u2741)*\u2732\uff9f*, Explained", "user": "artod", "upvotes": 55, "views": 2700, "problem_title": "smallest string with swaps", "number": 1202, "acceptance": 0.5760000000000001, "difficulty": "Medium", "__index_level_0__": 18188, "question": "You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string.\nYou can swap the characters at any pair of indices in the given pairs any number of times.\nReturn the lexicographically smallest string that s can be changed to after using the swaps.\n Example 1:\nInput: s = \"dcab\", pairs = [[0,3],[1,2]]\nOutput: \"bacd\"\nExplaination: \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[1] and s[2], s = \"bacd\"\nExample 2:\nInput: s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]\nOutput: \"abcd\"\nExplaination: \nSwap s[0] and s[3], s = \"bcad\"\nSwap s[0] and s[2], s = \"acbd\"\nSwap s[1] and s[2], s = \"abcd\"\nExample 3:\nInput: s = \"cba\", pairs = [[0,1],[1,2]]\nOutput: \"abc\"\nExplaination: \nSwap s[0] and s[1], s = \"bca\"\nSwap s[1] and s[2], s = \"bac\"\nSwap s[0] and s[1], s = \"abc\"\n Constraints:\n1 <= s.length <= 10^5\n0 <= pairs.length <= 10^5\n0 <= pairs[i][0], pairs[i][1] < s.length\ns only contains lower case English letters." }, { "post_href": "https://leetcode.com/problems/sort-items-by-groups-respecting-dependencies/discuss/1149266/Python3-topological-sort", "python_solutions": "class Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n for i in range(n): \n if group[i] == -1: group[i] = i + m # re-group \n \n graph0 = {} # digraph of groups \n indeg0 = [0]*(m+n) # indegree of groups \n \n graph1 = {} # digrpah of items \n indeg1 = [0]*n # indegree of items\n \n for i, x in enumerate(beforeItems): \n for xx in x: \n if group[xx] != group[i]: \n graph0.setdefault(group[xx], []).append(group[i])\n indeg0[group[i]] += 1\n graph1.setdefault(xx, []).append(i)\n indeg1[i] += 1\n \n def fn(graph, indeg): \n \"\"\"Return topological sort of graph using Kahn's algo.\"\"\"\n ans = []\n stack = [k for k in range(len(indeg)) if indeg[k] == 0]\n while stack: \n n = stack.pop()\n ans.append(n)\n for nn in graph.get(n, []):\n indeg[nn] -= 1\n if indeg[nn] == 0: stack.append(nn)\n return ans \n \n tp0 = fn(graph0, indeg0) \n if len(tp0) != len(indeg0): return [] \n \n tp1 = fn(graph1, indeg1)\n if len(tp1) != len(indeg1): return []\n \n mp0 = {x: i for i, x in enumerate(tp0)}\n mp1 = {x: i for i, x in enumerate(tp1)}\n \n return sorted(range(n), key=lambda x: (mp0[group[x]], mp1[x]))", "slug": "sort-items-by-groups-respecting-dependencies", "post_title": "[Python3] topological sort", "user": "ye15", "upvotes": 2, "views": 123, "problem_title": "sort items by groups respecting dependencies", "number": 1203, "acceptance": 0.506, "difficulty": "Hard", "__index_level_0__": 18203, "question": "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.\nReturn a sorted list of the items such that:\nThe items that belong to the same group are next to each other in the sorted list.\nThere 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).\nReturn any solution if there is more than one solution and return an empty list if there is no solution.\n Example 1:\nInput: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\nOutput: [6,3,4,1,5,2,0,7]\nExample 2:\nInput: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\nOutput: []\nExplanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.\n Constraints:\n1 <= m <= n <= 3 * 104\ngroup.length == beforeItems.length == n\n-1 <= group[i] <= m - 1\n0 <= beforeItems[i].length <= n - 1\n0 <= beforeItems[i][j] <= n - 1\ni != beforeItems[i][j]\nbeforeItems[i] does not contain duplicates elements." }, { "post_href": "https://leetcode.com/problems/unique-number-of-occurrences/discuss/393086/Solution-in-Python-3-(one-line)-(beats-100.00-)", "python_solutions": "class Solution:\n def uniqueOccurrences(self, A: List[int]) -> bool:\n \treturn (lambda x: len(x) == len(set(x)))(collections.Counter(A).values())\n\t\t\n\t\t\n- Junaid Mansuri\n(LeetCode ID)@hotmail.com", "slug": "unique-number-of-occurrences", "post_title": "Solution in Python 3 (one line) (beats 100.00 %)", "user": "junaidmansuri", "upvotes": 13, "views": 2600, "problem_title": "unique number of occurrences", "number": 1207, "acceptance": 0.7090000000000001, "difficulty": "Easy", "__index_level_0__": 18204, "question": "Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.\n Example 1:\nInput: arr = [1,2,2,1,1,3]\nOutput: true\nExplanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\nExample 2:\nInput: arr = [1,2]\nOutput: false\nExample 3:\nInput: arr = [-3,0,1,-3,1,1,1,-3,10,0]\nOutput: true\n Constraints:\n1 <= arr.length <= 1000\n-1000 <= arr[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/get-equal-substrings-within-budget/discuss/2312556/PYTHON-or-SLIDING-WINDOW-or-O(n)-or-WELL-EXPLAINED-or-EASY-or", "python_solutions": "class Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n n = len(s)\n cost,start,ans = 0,0,0\n for i in range(n):\n diff = abs(ord(s[i]) - ord(t[i]))\n if cost + diff <= maxCost:\n # we can increase our sliding window\n cost += diff\n else:\n # we are unable to increase our sliding window\n ans = max(ans,i - start)\n while True:\n cost -= abs(ord(s[start]) - ord(t[start]))\n start += 1\n if cost + diff <= maxCost: break\n if cost + diff > maxCost: start = i + 1\n else: cost += diff\n \n ans = max(ans,n - start)\n return ans", "slug": "get-equal-substrings-within-budget", "post_title": "PYTHON | SLIDING WINDOW | O(n) | WELL EXPLAINED | EASY |", "user": "reaper_27", "upvotes": 1, "views": 36, "problem_title": "get equal substrings within budget", "number": 1208, "acceptance": 0.478, "difficulty": "Medium", "__index_level_0__": 18248, "question": "You are given two strings s and t of the same length and an integer maxCost.\nYou want to change s to t. Changing the ith character of s to ith character of t costs |s[i] - t[i]| (i.e., the absolute difference between the ASCII values of the characters).\nReturn the maximum length of a substring of s that can be changed to be the same as the corresponding substring of t with a cost less than or equal to maxCost. If there is no substring from s that can be changed to its corresponding substring from t, return 0.\n Example 1:\nInput: s = \"abcd\", t = \"bcdf\", maxCost = 3\nOutput: 3\nExplanation: \"abc\" of s can change to \"bcd\".\nThat costs 3, so the maximum length is 3.\nExample 2:\nInput: s = \"abcd\", t = \"cdef\", maxCost = 3\nOutput: 1\nExplanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.\nExample 3:\nInput: s = \"abcd\", t = \"acde\", maxCost = 0\nOutput: 1\nExplanation: You cannot make any change, so the maximum length is 1.\n Constraints:\n1 <= s.length <= 105\nt.length == s.length\n0 <= maxCost <= 106\ns and t consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/discuss/2012318/Python-Simple-One-Pass-Solution", "python_solutions": "class Solution:\n def removeDuplicates(self, s: str, k: int) -> str: \n stck = [['$', 0]] # a placeholder to mark stack is empty. This eliminates the need to do an empty check later\n \n for c in s:\n if stck[-1][0] == c:\n stck[-1][1]+=1 # update occurences count of top element if it matches current character\n if stck[-1][1] == k:\n stck.pop()\n else:\n stck.append([c, 1]) \n \n return ''.join(c * cnt for c, cnt in stck)", "slug": "remove-all-adjacent-duplicates-in-string-ii", "post_title": "\u2705 Python Simple One Pass Solution", "user": "constantine786", "upvotes": 81, "views": 4300, "problem_title": "remove all adjacent duplicates in string ii", "number": 1209, "acceptance": 0.56, "difficulty": "Medium", "__index_level_0__": 18254, "question": "You are given a string s and an integer k, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them, causing the left and the right side of the deleted substring to concatenate together.\nWe repeatedly make k duplicate removals on s until we no longer can.\nReturn the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.\n Example 1:\nInput: s = \"abcd\", k = 2\nOutput: \"abcd\"\nExplanation: There's nothing to delete.\nExample 2:\nInput: s = \"deeedbbcccbdaa\", k = 3\nOutput: \"aa\"\nExplanation: \nFirst delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\nThen delete \"bbb\", get \"dddaa\"\nFinally delete \"ddd\", get \"aa\"\nExample 3:\nInput: s = \"pbbcggttciiippooaais\", k = 2\nOutput: \"ps\"\n Constraints:\n1 <= s.length <= 105\n2 <= k <= 104\ns only contains lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-moves-to-reach-target-with-rotations/discuss/393042/Python-3-(BFS-DFS-and-DP)-(With-Explanation)-(beats-100.00)", "python_solutions": "class Solution:\n def minimumMoves(self, G: List[List[int]]) -> int:\n \tN, S, T, V, c = len(G), [(0, 0, 'h')], [], set(), 0\n \twhile S:\n \t\tfor i in S:\n \t\t\tif i in V: continue\n \t\t\tif i == (N-1, N-2, 'h'): return c\n \t\t\t(a, b, o), _ = i, V.add(i)\n\t \t\tif o == 'h':\n \t\t\t\tif b + 2 != N and G[a][b+2] == 0: T.append((a, b+1, o))\n \t\t\t\tif a + 1 != N and G[a+1][b] == 0 and G[a+1][b+1] == 0: T.append((a+1, b, o)), T.append((a, b, 'v'))\n \t\t\telif o == 'v':\n \t\t\t\tif a + 2 != N and G[a+2][b] == 0: T.append((a+1, b, o))\n \t\t\t\tif b + 1 != N and G[a][b+1] == 0 and G[a+1][b+1] == 0: T.append((a, b+1, o)), T.append((a, b, 'h'))\n \t\tS, T, c = T, [], c + 1\n \treturn -1", "slug": "minimum-moves-to-reach-target-with-rotations", "post_title": "Python 3 (BFS, DFS, and DP) (With Explanation) (beats 100.00%)", "user": "junaidmansuri", "upvotes": 8, "views": 896, "problem_title": "minimum moves to reach target with rotations", "number": 1210, "acceptance": 0.491, "difficulty": "Hard", "__index_level_0__": 18311, "question": "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).\nIn one move the snake can:\nMove 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.\nMove down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\nRotate 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).\nRotate 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).\nReturn the minimum number of moves to reach the target.\nIf there is no way to reach the target, return -1.\n Example 1:\nInput: grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n [0,0,0,0,1,1],\n [0,0,1,0,1,0],\n [0,1,1,0,0,0],\n [0,1,1,0,0,0]]\nOutput: 11\nExplanation:\nOne possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\nExample 2:\nInput: grid = [[0,0,1,1,1,1],\n [0,0,0,0,1,1],\n [1,1,0,0,0,1],\n [1,1,1,0,0,1],\n [1,1,1,0,0,1],\n [1,1,1,0,0,0]]\nOutput: 9\n Constraints:\n2 <= n <= 100\n0 <= grid[i][j] <= 1\nIt is guaranteed that the snake starts at empty cells." }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/discuss/1510460/Greedy-Approach-oror-Well-Explained-oror-Easy-to-understand", "python_solutions": "class Solution:\ndef minCostToMoveChips(self, position: List[int]) -> int:\n \n dic = Counter([n%2 for n in position])\n return min(dic[0],dic[1])", "slug": "minimum-cost-to-move-chips-to-the-same-position", "post_title": "\ud83d\udccc\ud83d\udccc Greedy Approach || Well-Explained || Easy-to-understand \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 5, "views": 165, "problem_title": "minimum cost to move chips to the same position", "number": 1217, "acceptance": 0.722, "difficulty": "Easy", "__index_level_0__": 18317, "question": "We have n chips, where the position of the ith chip is position[i].\nWe need to move all the chips to the same position. In one step, we can change the position of the ith chip from position[i] to:\nposition[i] + 2 or position[i] - 2 with cost = 0.\nposition[i] + 1 or position[i] - 1 with cost = 1.\nReturn the minimum cost needed to move all the chips to the same position.\n Example 1:\nInput: position = [1,2,3]\nOutput: 1\nExplanation: First step: Move the chip at position 3 to position 1 with cost = 0.\nSecond step: Move the chip at position 2 to position 1 with cost = 1.\nTotal cost is 1.\nExample 2:\nInput: position = [2,2,2,3,3]\nOutput: 2\nExplanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.\nExample 3:\nInput: position = [1,1000000000]\nOutput: 1\n Constraints:\n1 <= position.length <= 100\n1 <= position[i] <= 10^9" }, { "post_href": "https://leetcode.com/problems/longest-arithmetic-subsequence-of-given-difference/discuss/1605339/Python3-dp-and-hash-table-easy-to-understand", "python_solutions": "class Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n \"\"\"\n dp is a hashtable, dp[x] is the longest subsequence ending with number x\n \"\"\"\n dp = {}\n for x in arr:\n if x - difference in dp:\n dp[x] = dp[x-difference] + 1\n else:\n dp[x] = 1\n \n return max(dp.values())", "slug": "longest-arithmetic-subsequence-of-given-difference", "post_title": "[Python3] dp and hash table, easy to understand", "user": "nick19981122", "upvotes": 18, "views": 761, "problem_title": "longest arithmetic subsequence of given difference", "number": 1218, "acceptance": 0.518, "difficulty": "Medium", "__index_level_0__": 18346, "question": "Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.\nA subsequence is a sequence that can be derived from arr by deleting some or no elements without changing the order of the remaining elements.\n Example 1:\nInput: arr = [1,2,3,4], difference = 1\nOutput: 4\nExplanation: The longest arithmetic subsequence is [1,2,3,4].\nExample 2:\nInput: arr = [1,3,5,7], difference = 1\nOutput: 1\nExplanation: The longest arithmetic subsequence is any single element.\nExample 3:\nInput: arr = [1,5,7,8,5,3,4,2,1], difference = -2\nOutput: 4\nExplanation: The longest arithmetic subsequence is [7,5,3,1].\n Constraints:\n1 <= arr.length <= 105\n-104 <= arr[i], difference <= 104" }, { "post_href": "https://leetcode.com/problems/path-with-maximum-gold/discuss/1742414/very-easy-to-understand-using-backtracking-python3", "python_solutions": "class Solution:\n\tdef getMaximumGold(self, grid: List[List[int]]) -> int:\n\t\tm = len(grid)\n\t\tn = len(grid[0])\n\t\tdef solve(i,j,grid,vis,val):\n\t\t\t# print(i,j,grid,vis,val)\n\t\t\tif(i < 0 or i >= m or j < 0 or j >= n or grid[i][j] == 0 or vis[i][j]):\n\t\t\t\t# print(i,m,j,n)\n\t\t\t\treturn val\n\t\t\tvis[i][j] = True\n\t\t\ta = solve(i,j-1,grid,vis,val+grid[i][j])\n\t\t\tb = solve(i,j+1,grid,vis,val+grid[i][j])\n\t\t\tc = solve(i+1,j,grid,vis,val+grid[i][j])\n\t\t\td = solve(i-1,j,grid,vis,val+grid[i][j])\n\t\t\tvis[i][j] = False\n\t\t\treturn max(a,b,c,d)\n\t\tma = 0\n\t\tfor i in range(len(grid)):\n\t\t\tfor j in range(len(grid[0])):\n\t\t\t\tif(grid[i][j] != 0):\n\t\t\t\t\tvis = [[False for i in range(len(grid[0]))] for j in range(len(grid))]\n\t\t\t\t\tma = max(ma,solve(i,j,grid,vis,0))\n\t\treturn ma", "slug": "path-with-maximum-gold", "post_title": "very easy to understand using backtracking, python3", "user": "jagdishpawar8105", "upvotes": 1, "views": 99, "problem_title": "path with maximum gold", "number": 1219, "acceptance": 0.64, "difficulty": "Medium", "__index_level_0__": 18363, "question": "In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty.\nReturn the maximum amount of gold you can collect under the conditions:\nEvery time you are located in a cell you will collect all the gold in that cell.\nFrom your position, you can walk one step to the left, right, up, or down.\nYou can't visit the same cell more than once.\nNever visit a cell with 0 gold.\nYou can start and stop collecting gold from any position in the grid that has some gold.\n Example 1:\nInput: grid = [[0,6,0],[5,8,7],[0,9,0]]\nOutput: 24\nExplanation:\n[[0,6,0],\n [5,8,7],\n [0,9,0]]\nPath to get the maximum gold, 9 -> 8 -> 7.\nExample 2:\nInput: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\nOutput: 28\nExplanation:\n[[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\nPath to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 15\n0 <= grid[i][j] <= 100\nThere are at most 25 cells containing gold." }, { "post_href": "https://leetcode.com/problems/count-vowels-permutation/discuss/398231/Dynamic-programming-in-Python-with-in-depth-explanation-and-diagrams", "python_solutions": "class Solution:\n def countVowelPermutation(self, n: int) -> int:\n dp_array = [[0] * 5 for _ in range(n + 1)]\n dp_array[1] = [1, 1, 1, 1, 1]\n for i in range(2, n + 1):\n # a is allowed to follow e, i, or u.\n dp_array[i][0] = dp_array[i - 1][1] + dp_array[i - 1][2] + dp_array[i - 1][4]\n # e is allowed to follow a or i.\n dp_array[i][1] = dp_array[i - 1][0] + dp_array[i - 1][2]\n # i is allowed to follow e or o.\n dp_array[i][2] = dp_array[i - 1][1] + dp_array[i - 1][3]\n # o is allowed to follow i\n dp_array[i][3] = dp_array[i - 1][2]\n # u is allowed to follow i or o.\n dp_array[i][4] = dp_array[i - 1][2] + dp_array[i - 1][3]\n return sum(dp_array[n]) % ((10 ** 9) + 7)", "slug": "count-vowels-permutation", "post_title": "Dynamic programming in Python with in-depth explanation and diagrams", "user": "Hai_dee", "upvotes": 36, "views": 1600, "problem_title": "count vowels permutation", "number": 1220, "acceptance": 0.605, "difficulty": "Hard", "__index_level_0__": 18380, "question": "Given an integer n, your task is to count how many strings of length n can be formed under the following rules:\nEach character is a lower case vowel ('a', 'e', 'i', 'o', 'u')\nEach vowel 'a' may only be followed by an 'e'.\nEach vowel 'e' may only be followed by an 'a' or an 'i'.\nEach vowel 'i' may not be followed by another 'i'.\nEach vowel 'o' may only be followed by an 'i' or a 'u'.\nEach vowel 'u' may only be followed by an 'a'.\nSince the answer may be too large, return it modulo 10^9 + 7.\n Example 1:\nInput: n = 1\nOutput: 5\nExplanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\nExample 2:\nInput: n = 2\nOutput: 10\nExplanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\nExample 3: \nInput: n = 5\nOutput: 68\n Constraints:\n1 <= n <= 2 * 10^4" }, { "post_href": "https://leetcode.com/problems/split-a-string-in-balanced-strings/discuss/403688/Python-3-(three-lines)-(beats-100.00-)", "python_solutions": "class Solution:\n def balancedStringSplit(self, S: str) -> int:\n m = c = 0\n for s in S:\n if s == 'L': c += 1\n if s == 'R': c -= 1\n if c == 0: m += 1\n return m", "slug": "split-a-string-in-balanced-strings", "post_title": "Python 3 (three lines) (beats 100.00 %)", "user": "junaidmansuri", "upvotes": 30, "views": 2700, "problem_title": "split a string in balanced strings", "number": 1221, "acceptance": 0.848, "difficulty": "Easy", "__index_level_0__": 18424, "question": "Balanced strings are those that have an equal quantity of 'L' and 'R' characters.\nGiven a balanced string s, split it into some number of substrings such that:\nEach substring is balanced.\nReturn the maximum number of balanced strings you can obtain.\n Example 1:\nInput: s = \"RLRRLLRLRL\"\nOutput: 4\nExplanation: s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.\nExample 2:\nInput: s = \"RLRRRLLRLL\"\nOutput: 2\nExplanation: s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\nNote that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2nd and 5th substrings are not balanced.\nExample 3:\nInput: s = \"LLLLRRRR\"\nOutput: 1\nExplanation: s can be split into \"LLLLRRRR\".\n Constraints:\n2 <= s.length <= 1000\ns[i] is either 'L' or 'R'.\ns is a balanced string." }, { "post_href": "https://leetcode.com/problems/queens-that-can-attack-the-king/discuss/790679/Simple-Python-Solution", "python_solutions": "class Solution:\n # Time: O(1)\n # Space: O(1)\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n queen_set = {(i, j) for i, j in queens}\n res = []\n \n for dx, dy in [[0, 1], [1, 0], [-1, 0], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]]:\n x, y = king[0], king[1]\n while 0 <= x < 8 and 0 <= y < 8:\n x += dx\n y += dy\n if (x, y) in queen_set:\n res.append([x, y])\n break\n return res", "slug": "queens-that-can-attack-the-king", "post_title": "Simple Python Solution", "user": "whissely", "upvotes": 5, "views": 397, "problem_title": "queens that can attack the king", "number": 1222, "acceptance": 0.718, "difficulty": "Medium", "__index_level_0__": 18462, "question": "On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king.\nYou are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king.\nReturn the coordinates of the black queens that can directly attack the king. You may return the answer in any order.\n Example 1:\nInput: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\nOutput: [[0,1],[1,0],[3,3]]\nExplanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).\nExample 2:\nInput: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\nOutput: [[2,2],[3,4],[4,4]]\nExplanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).\n Constraints:\n1 <= queens.length < 64\nqueens[i].length == king.length == 2\n0 <= xQueeni, yQueeni, xKing, yKing < 8\nAll the given positions are unique." }, { "post_href": "https://leetcode.com/problems/dice-roll-simulation/discuss/1505338/Python-or-Intuitive-or-Recursion-%2B-Memo-or-Explanation", "python_solutions": "class Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n MOD = 10 ** 9 + 7\n \n @lru_cache(None)\n def func(idx, prevNum, prevNumFreq):\n if idx == n:\n return 1\n \n ans = 0\n for i in range(1, 7):\n if i == prevNum:\n if prevNumFreq < rollMax[i - 1]:\n ans += func(idx + 1, i, prevNumFreq + 1)\n \n else:\n ans += func(idx + 1, i, 1)\n \n return ans % MOD\n \n return func(0, 0, 0)", "slug": "dice-roll-simulation", "post_title": "Python | Intuitive | Recursion + Memo | Explanation", "user": "detective_dp", "upvotes": 2, "views": 267, "problem_title": "dice roll simulation", "number": 1223, "acceptance": 0.484, "difficulty": "Hard", "__index_level_0__": 18478, "question": "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.\nGiven an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7.\nTwo sequences are considered different if at least one element differs from each other.\n Example 1:\nInput: n = 2, rollMax = [1,1,2,2,2,3]\nOutput: 34\nExplanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\nExample 2:\nInput: n = 2, rollMax = [1,1,1,1,1,1]\nOutput: 30\nExample 3:\nInput: n = 3, rollMax = [1,1,1,2,2,3]\nOutput: 181\n Constraints:\n1 <= n <= 5000\nrollMax.length == 6\n1 <= rollMax[i] <= 15" }, { "post_href": "https://leetcode.com/problems/maximum-equal-frequency/discuss/2448664/Python-easy-to-read-and-understand-or-hash-table", "python_solutions": "class Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n cnt, freq, maxfreq, ans = collections.defaultdict(int), collections.defaultdict(int), 0, 0\n for i, num in enumerate(nums):\n cnt[num] = cnt.get(num, 0) + 1\n freq[cnt[num]] += 1\n freq[cnt[num]-1] -= 1\n maxfreq = max(maxfreq, cnt[num])\n if maxfreq == 1:\n ans = i+1\n elif maxfreq*freq[maxfreq] == i:\n ans = i+1\n elif (maxfreq-1)*(freq[maxfreq-1]+1) == i:\n ans = i+1\n return ans", "slug": "maximum-equal-frequency", "post_title": "Python easy to read and understand | hash table", "user": "sanial2001", "upvotes": 1, "views": 73, "problem_title": "maximum equal frequency", "number": 1224, "acceptance": 0.371, "difficulty": "Hard", "__index_level_0__": 18484, "question": "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.\nIf after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n Example 1:\nInput: nums = [2,2,1,1,5,3,3,5]\nOutput: 7\nExplanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\nExample 2:\nInput: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\nOutput: 13\n Constraints:\n2 <= nums.length <= 105\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/airplane-seat-assignment-probability/discuss/530102/Python3-symmetry", "python_solutions": "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n return 1 if n == 1 else 0.5", "slug": "airplane-seat-assignment-probability", "post_title": "[Python3] symmetry", "user": "ye15", "upvotes": 1, "views": 139, "problem_title": "airplane seat assignment probability", "number": 1227, "acceptance": 0.649, "difficulty": "Medium", "__index_level_0__": 18490, "question": "n passengers board an airplane with exactly n seats. The first passenger has lost the ticket and picks a seat randomly. But after that, the rest of the passengers will:\nTake their own seat if it is still available, and\nPick other seats randomly when they find their seat occupied\nReturn the probability that the nth person gets his own seat.\n Example 1:\nInput: n = 1\nOutput: 1.00000\nExplanation: The first person can only get the first seat.\nExample 2:\nInput: n = 2\nOutput: 0.50000\nExplanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n Constraints:\n1 <= n <= 105" }, { "post_href": "https://leetcode.com/problems/check-if-it-is-a-straight-line/discuss/1247752/Python3-simple-solution", "python_solutions": "class Solution:\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n x1, y1 = coordinates[0]\n x2, y2 = coordinates[1]\n for x, y in coordinates[2:]:\n if (y2 - y1) * (x - x1) != (x2 - x1) * (y - y1):\n return False\n return True", "slug": "check-if-it-is-a-straight-line", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 6, "views": 176, "problem_title": "check if it is a straight line", "number": 1232, "acceptance": 0.41, "difficulty": "Easy", "__index_level_0__": 18493, "question": "You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.\n Example 1:\nInput: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\nOutput: true\nExample 2:\nInput: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\nOutput: false\n Constraints:\n2 <= coordinates.length <= 1000\ncoordinates[i].length == 2\n-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4\ncoordinates contains no duplicate point." }, { "post_href": "https://leetcode.com/problems/remove-sub-folders-from-the-filesystem/discuss/1196525/Python3-simple-solution-using-%22startswith%22-method", "python_solutions": "class Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n ans = []\n for i, path in enumerate(sorted(folder)):\n if i == 0 or not path.startswith(ans[-1] + \"/\"):\n ans.append(path)\n return ans", "slug": "remove-sub-folders-from-the-filesystem", "post_title": "Python3 simple solution using \"startswith\" method", "user": "EklavyaJoshi", "upvotes": 3, "views": 130, "problem_title": "remove sub folders from the filesystem", "number": 1233, "acceptance": 0.654, "difficulty": "Medium", "__index_level_0__": 18523, "question": "Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.\nIf a folder[i] is located within another folder[j], it is called a sub-folder of it.\nThe format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.\nFor example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not.\n Example 1:\nInput: folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\nOutput: [\"/a\",\"/c/d\",\"/c/f\"]\nExplanation: Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.\nExample 2:\nInput: folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\nOutput: [\"/a\"]\nExplanation: Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".\nExample 3:\nInput: folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\nOutput: [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\n Constraints:\n1 <= folder.length <= 4 * 104\n2 <= folder[i].length <= 100\nfolder[i] contains only lowercase letters and '/'.\nfolder[i] always starts with the character '/'.\nEach folder name is unique." }, { "post_href": "https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/884039/Python3-sliding-window-with-explanation", "python_solutions": "class Solution:\n def balancedString(self, s: str) -> int:\n counter = collections.Counter(s)\n n = len(s) // 4\n extras = {}\n for key in counter:\n if counter[key] > n:\n extras[key] = counter[key] - n\n \n if not extras: return 0\n i = 0\n res = len(s)\n for j in range(len(s)):\n if s[j] in extras:\n extras[s[j]] -= 1\n \n while max(extras.values()) <= 0:\n res = min(res, j-i+1)\n if s[i] in extras:\n extras[s[i]] += 1\n i += 1\n \n \n return res", "slug": "replace-the-substring-for-balanced-string", "post_title": "[Python3] sliding window with explanation", "user": "hwsbjts", "upvotes": 10, "views": 888, "problem_title": "replace the substring for balanced string", "number": 1234, "acceptance": 0.369, "difficulty": "Medium", "__index_level_0__": 18536, "question": "You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.\nA string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.\nReturn the minimum length of the substring that can be replaced with any other string of the same length to make s balanced. If s is already balanced, return 0.\n Example 1:\nInput: s = \"QWER\"\nOutput: 0\nExplanation: s is already balanced.\nExample 2:\nInput: s = \"QQWE\"\nOutput: 1\nExplanation: We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.\nExample 3:\nInput: s = \"QQQW\"\nOutput: 2\nExplanation: We can replace the first \"QQ\" to \"ER\". \n Constraints:\nn == s.length\n4 <= n <= 105\nn is a multiple of 4.\ns contains only 'Q', 'W', 'E', and 'R'." }, { "post_href": "https://leetcode.com/problems/maximum-profit-in-job-scheduling/discuss/1431246/Easiest-oror-Heap-oror-98-faster-oror-Clean-and-Concise", "python_solutions": "class Solution:\ndef jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n\n jobs = sorted([(startTime[i],endTime[i],profit[i]) for i in range(len(startTime))])\n heap=[]\n cp,mp = 0,0 # cp->current profit, mp-> max-profit\n for s,e,p in jobs:\n while heap and heap[0][0]<=s:\n et,tmp = heapq.heappop(heap)\n cp = max(cp,tmp)\n heapq.heappush(heap,(e,cp+p))\n mp = max(mp,cp+p)\n \n return mp", "slug": "maximum-profit-in-job-scheduling", "post_title": "\ud83d\udc0d Easiest || Heap || 98% faster || Clean & Concise \ud83d\udccc", "user": "abhi9Rai", "upvotes": 17, "views": 1100, "problem_title": "maximum profit in job scheduling", "number": 1235, "acceptance": 0.512, "difficulty": "Hard", "__index_level_0__": 18542, "question": "We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].\nYou're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.\nIf you choose a job that ends at time X you will be able to start another job that starts at time X.\n Example 1:\nInput: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\nOutput: 120\nExplanation: The subset chosen is the first and fourth job. \nTime range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\nExample 2:\nInput: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\nOutput: 150\nExplanation: The subset chosen is the first, fourth and fifth job. \nProfit obtained 150 = 20 + 70 + 60.\nExample 3:\nInput: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\nOutput: 6\n Constraints:\n1 <= startTime.length == endTime.length == profit.length <= 5 * 104\n1 <= startTime[i] < endTime[i] <= 109\n1 <= profit[i] <= 104" }, { "post_href": "https://leetcode.com/problems/find-positive-integer-solution-for-a-given-equation/discuss/933212/Python-3-greater-91.68-faster.-O(n)-time", "python_solutions": "def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:\n\tx, y = 1, z\n\tpairs = []\n\t\n\twhile x<=z and y>0:\n\t\tcf = customfunction.f(x,y)\n\t\tif cf==z:\n\t\t\tpairs.append([x,y])\n\t\t\tx, y = x+1, y-1\n\t\telif cf > z:\n\t\t\ty -= 1\n\t\telse:\n\t\t\tx += 1\n\treturn pairs", "slug": "find-positive-integer-solution-for-a-given-equation", "post_title": "Python 3 -> 91.68% faster. O(n) time", "user": "mybuddy29", "upvotes": 27, "views": 1500, "problem_title": "find positive integer solution for a given equation", "number": 1237, "acceptance": 0.693, "difficulty": "Medium", "__index_level_0__": 18570, "question": "Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.\nWhile the exact formula is hidden, the function is monotonically increasing, i.e.:\nf(x, y) < f(x + 1, y)\nf(x, y) < f(x, y + 1)\nThe function interface is defined like this:\ninterface CustomFunction {\npublic:\n // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.\n int f(int x, int y);\n};\nWe will judge your solution as follows:\nThe judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z.\nThe judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.\nThe judge will call your findSolution and compare your results with the answer key.\nIf your results match the answer key, your solution will be Accepted.\n Example 1:\nInput: function_id = 1, z = 5\nOutput: [[1,4],[2,3],[3,2],[4,1]]\nExplanation: The hidden formula for function_id = 1 is f(x, y) = x + y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=4 -> f(1, 4) = 1 + 4 = 5.\nx=2, y=3 -> f(2, 3) = 2 + 3 = 5.\nx=3, y=2 -> f(3, 2) = 3 + 2 = 5.\nx=4, y=1 -> f(4, 1) = 4 + 1 = 5.\nExample 2:\nInput: function_id = 2, z = 5\nOutput: [[1,5],[5,1]]\nExplanation: The hidden formula for function_id = 2 is f(x, y) = x * y.\nThe following positive integer values of x and y make f(x, y) equal to 5:\nx=1, y=5 -> f(1, 5) = 1 * 5 = 5.\nx=5, y=1 -> f(5, 1) = 5 * 1 = 5.\n Constraints:\n1 <= function_id <= 9\n1 <= z <= 100\nIt is guaranteed that the solutions of f(x, y) == z will be in the range 1 <= x, y <= 1000.\nIt is also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= x, y <= 1000." }, { "post_href": "https://leetcode.com/problems/circular-permutation-in-binary-representation/discuss/1092321/Python3-backtracking", "python_solutions": "class Solution:\n def circularPermutation(self, n: int, start: int) -> List[int]:\n ans = []\n for i in range(1<> 1)\n return ans", "slug": "circular-permutation-in-binary-representation", "post_title": "[Python3] backtracking", "user": "ye15", "upvotes": 1, "views": 117, "problem_title": "circular permutation in binary representation", "number": 1238, "acceptance": 0.6890000000000001, "difficulty": "Medium", "__index_level_0__": 18578, "question": "Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :\np[0] = start\np[i] and p[i+1] differ by only one bit in their binary representation.\np[0] and p[2^n -1] must also differ by only one bit in their binary representation.\n Example 1:\nInput: n = 2, start = 3\nOutput: [3,2,0,1]\nExplanation: The binary representation of the permutation is (11,10,00,01). \nAll the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]\nExample 2:\nInput: n = 3, start = 2\nOutput: [2,6,7,5,4,0,1,3]\nExplanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).\n Constraints:\n1 <= n <= 16\n0 <= start < 2 ^ n" }, { "post_href": "https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/discuss/1478666/Two-Approach-oror-Well-Explained-oror-97-faster", "python_solutions": "class Solution:\ndef maxLength(self,arr):\n \n unique = ['']\n res = 0\n for i in range(len(arr)):\n for j in range(len(unique)):\n local = arr[i]+unique[j]\n if len(local)==len(set(local)):\n unique.append(local)\n res=max(res,len(local))\n \n return res", "slug": "maximum-length-of-a-concatenated-string-with-unique-characters", "post_title": "\ud83d\udc0d Two-Approach || Well-Explained || 97% faster \ud83d\udccc", "user": "abhi9Rai", "upvotes": 22, "views": 2200, "problem_title": "maximum length of a concatenated string with unique characters", "number": 1239, "acceptance": 0.522, "difficulty": "Medium", "__index_level_0__": 18586, "question": "You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.\nReturn the maximum possible length of s.\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n Example 1:\nInput: arr = [\"un\",\"iq\",\"ue\"]\nOutput: 4\nExplanation: All the valid concatenations are:\n- \"\"\n- \"un\"\n- \"iq\"\n- \"ue\"\n- \"uniq\" (\"un\" + \"iq\")\n- \"ique\" (\"iq\" + \"ue\")\nMaximum length is 4.\nExample 2:\nInput: arr = [\"cha\",\"r\",\"act\",\"ers\"]\nOutput: 6\nExplanation: Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").\nExample 3:\nInput: arr = [\"abcdefghijklmnopqrstuvwxyz\"]\nOutput: 26\nExplanation: The only string in arr has all 26 characters.\n Constraints:\n1 <= arr.length <= 16\n1 <= arr[i].length <= 26\narr[i] contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/tiling-a-rectangle-with-the-fewest-squares/discuss/1216988/Python3-backtracking", "python_solutions": "class Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n if n == m: return 1\n depth = [0]*m\n \n def fn(x): \n \"\"\"Explore tiling rectangle area via backtracking.\"\"\"\n nonlocal ans \n if x < ans: \n if min(depth) == n: ans = x # all tiled\n else: \n i = min(depth)\n j = jj = depth.index(i) # (i, j)\n while jj < m and depth[jj] == depth[j]: jj += 1\n k = min(n - i, jj - j)\n for kk in reversed(range(1, k+1)): \n for jj in range(j, j+kk): depth[jj] += kk\n fn(x+1)\n for jj in range(j, j+kk): depth[jj] -= kk\n \n ans = max(n, m)\n fn(0)\n return ans", "slug": "tiling-a-rectangle-with-the-fewest-squares", "post_title": "[Python3] backtracking", "user": "ye15", "upvotes": 1, "views": 334, "problem_title": "tiling a rectangle with the fewest squares", "number": 1240, "acceptance": 0.539, "difficulty": "Hard", "__index_level_0__": 18642, "question": "Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.\n Example 1:\nInput: n = 2, m = 3\nOutput: 3\nExplanation: 3 squares are necessary to cover the rectangle.\n2 (squares of 1x1)\n1 (square of 2x2)\nExample 2:\nInput: n = 5, m = 8\nOutput: 5\nExample 3:\nInput: n = 11, m = 13\nOutput: 6\n Constraints:\n1 <= n, m <= 13" }, { "post_href": "https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/discuss/1196255/Python3-solution-using-list-and-dictionary", "python_solutions": "class Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n if s1 == s2:\n return 0\n else:\n count = 0\n d = {('xx','yy'):1,('xy','yx'):2,('yy','xx'):1,('yx','xy'):2}\n x = []\n y = []\n for i,j in zip(s1,s2):\n if i != j:\n x.append(i)\n y.append(j)\n x.sort()\n y.sort(reverse=True)\n i,j = 0,0\n if len(x)%2 != 0 or len(y)%2 != 0:\n return -1\n while i < len(x) and j < len(y):\n z = (''.join(x[i:i+2]),''.join(y[i:i+2]))\n if z not in d:\n return -1\n else:\n count += d[z]\n i += 2\n j += 2\n return count", "slug": "minimum-swaps-to-make-strings-equal", "post_title": "Python3 solution using list and dictionary", "user": "EklavyaJoshi", "upvotes": 2, "views": 117, "problem_title": "minimum swaps to make strings equal", "number": 1247, "acceptance": 0.638, "difficulty": "Medium", "__index_level_0__": 18644, "question": "You are given two strings s1 and s2 of equal length consisting of letters \"x\" and \"y\" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].\nReturn the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.\n Example 1:\nInput: s1 = \"xx\", s2 = \"yy\"\nOutput: 1\nExplanation: Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".\nExample 2:\nInput: s1 = \"xy\", s2 = \"yx\"\nOutput: 2\nExplanation: Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\nSwap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\nNote that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.\nExample 3:\nInput: s1 = \"xx\", s2 = \"xy\"\nOutput: -1\n Constraints:\n1 <= s1.length, s2.length <= 1000\ns1.length == s2.length\ns1, s2 only contain 'x' or 'y'." }, { "post_href": "https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/1265615/Python-Two-pointer", "python_solutions": "class Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n right ,left = 0,0\n ans = 0 \n odd_cnt = 0\n ans = 0\n cur_sub_cnt = 0\n for right in range(len(nums)):\n \n if nums[right]%2 == 1:\n odd_cnt += 1\n cur_sub_cnt = 0\n \n while odd_cnt == k:\n if nums[left]%2 == 1:\n odd_cnt -= 1\n cur_sub_cnt += 1\n left += 1\n \n ans += cur_sub_cnt\n \n return ans", "slug": "count-number-of-nice-subarrays", "post_title": "Python - Two pointer", "user": "harshhx", "upvotes": 28, "views": 1300, "problem_title": "count number of nice subarrays", "number": 1248, "acceptance": 0.597, "difficulty": "Medium", "__index_level_0__": 18648, "question": "Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.\nReturn the number of nice sub-arrays.\n Example 1:\nInput: nums = [1,1,2,1,1], k = 3\nOutput: 2\nExplanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\nExample 2:\nInput: nums = [2,4,6], k = 1\nOutput: 0\nExplanation: There is no odd numbers in the array.\nExample 3:\nInput: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\nOutput: 16\n Constraints:\n1 <= nums.length <= 50000\n1 <= nums[i] <= 10^5\n1 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/discuss/503754/Python-Memory-Usage-Less-Than-100-Faster-than-100", "python_solutions": "class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n \n open = 0\n s = list(s)\n \n for i, c in enumerate(s):\n if c == '(': open += 1\n elif c == ')':\n if not open: s[i] = \"\"\n else: open -= 1\n \n for i in range(len(s)-1, -1, -1):\n if not open: break\n if s[i] == '(': s[i] = \"\"; open -= 1\n \n return \"\".join(s)", "slug": "minimum-remove-to-make-valid-parentheses", "post_title": "Python - Memory Usage Less Than 100%, Faster than 100%", "user": "mmbhatk", "upvotes": 24, "views": 2900, "problem_title": "minimum remove to make valid parentheses", "number": 1249, "acceptance": 0.657, "difficulty": "Medium", "__index_level_0__": 18663, "question": "Given a string s of '(' , ')' and lowercase English characters.\nYour task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.\nFormally, a parentheses string is valid if and only if:\nIt is the empty string, contains only lowercase characters, or\nIt can be written as AB (A concatenated with B), where A and B are valid strings, or\nIt can be written as (A), where A is a valid string.\n Example 1:\nInput: s = \"lee(t(c)o)de)\"\nOutput: \"lee(t(c)o)de\"\nExplanation: \"lee(t(co)de)\" , \"lee(t(c)ode)\" would also be accepted.\nExample 2:\nInput: s = \"a)b(c)d\"\nOutput: \"ab(c)d\"\nExample 3:\nInput: s = \"))((\"\nOutput: \"\"\nExplanation: An empty string is also valid.\n Constraints:\n1 <= s.length <= 105\ns[i] is either '(' , ')', or lowercase English letter." }, { "post_href": "https://leetcode.com/problems/check-if-it-is-a-good-array/discuss/1489417/This-problem-is-about-chinese-remainder-theorem.", "python_solutions": "class Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n import math \n n = len(nums)\n if n ==1:\n return nums[0] ==1\n d = math.gcd(nums[0], nums[1])\n for i in range(n):\n d = math.gcd(nums[i], d)\n return d ==1", "slug": "check-if-it-is-a-good-array", "post_title": "This problem is about chinese remainder theorem.", "user": "byuns9334", "upvotes": 2, "views": 244, "problem_title": "check if it is a good array", "number": 1250, "acceptance": 0.589, "difficulty": "Hard", "__index_level_0__": 18718, "question": "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.\nReturn True if the array is good otherwise return False.\n Example 1:\nInput: nums = [12,5,7,23]\nOutput: true\nExplanation: Pick numbers 5 and 7.\n5*3 + 7*(-2) = 1\nExample 2:\nInput: nums = [29,6,10]\nOutput: true\nExplanation: Pick numbers 29, 6 and 10.\n29*1 + 6*(-3) + 10*(-1) = 1\nExample 3:\nInput: nums = [3,6]\nOutput: false\n Constraints:\n1 <= nums.length <= 10^5\n1 <= nums[i] <= 10^9" }, { "post_href": "https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/discuss/1682009/Optimal-O(m%2Bn)-space-or-O(m*n)-time-complexity-solution", "python_solutions": "class Solution:\n def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:\n row_data = [0]*m\n col_data = [0]*n\n \n for tup in indices:\n row_data[tup[0]] = row_data[tup[0]] + 1\n col_data[tup[1]] = col_data[tup[1]] + 1\n \n odd_count = 0 \n for rowp in range(m):\n for colp in range(n):\n val = row_data[rowp] + col_data[colp]\n if val % 2 != 0:\n odd_count+=1\n \n return odd_count", "slug": "cells-with-odd-values-in-a-matrix", "post_title": "Optimal O(m+n) space | O(m*n) time complexity solution", "user": "snagsbybalin", "upvotes": 2, "views": 172, "problem_title": "cells with odd values in a matrix", "number": 1252, "acceptance": 0.7859999999999999, "difficulty": "Easy", "__index_level_0__": 18722, "question": "There is an m x n matrix that is initialized to all 0's. There is also a 2D array indices where each indices[i] = [ri, ci] represents a 0-indexed location to perform some increment operations on the matrix.\nFor each location indices[i], do both of the following:\nIncrement all the cells on row ri.\nIncrement all the cells on column ci.\nGiven m, n, and indices, return the number of odd-valued cells in the matrix after applying the increment to all locations in indices.\n Example 1:\nInput: m = 2, n = 3, indices = [[0,1],[1,1]]\nOutput: 6\nExplanation: Initial matrix = [[0,0,0],[0,0,0]].\nAfter applying first increment it becomes [[1,2,1],[0,1,0]].\nThe final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.\nExample 2:\nInput: m = 2, n = 2, indices = [[1,1],[0,0]]\nOutput: 0\nExplanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.\n Constraints:\n1 <= m, n <= 50\n1 <= indices.length <= 100\n0 <= ri < m\n0 <= ci < n\n Follow up: Could you solve this in O(n + m + indices.length) time with only O(n + m) extra space?" }, { "post_href": "https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/845641/Python-3-or-Greedy-or-Explanations", "python_solutions": "class Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n s, n = sum(colsum), len(colsum)\n if upper + lower != s: return []\n u, d = [0] * n, [0] * n\n for i in range(n):\n if colsum[i] == 2 and upper > 0 and lower > 0:\n u[i] = d[i] = 1\n upper, lower = upper-1, lower-1\n elif colsum[i] == 1: \n if upper > 0 and upper >= lower:\n u[i], upper = 1, upper-1\n elif lower > 0 and lower > upper:\n d[i], lower = 1, lower-1\n else: return [] \n elif not colsum[i]: continue\n else: return []\n return [u, d]", "slug": "reconstruct-a-2-row-binary-matrix", "post_title": "Python 3 | Greedy | Explanations", "user": "idontknoooo", "upvotes": 3, "views": 399, "problem_title": "reconstruct a 2 row binary matrix", "number": 1253, "acceptance": 0.4379999999999999, "difficulty": "Medium", "__index_level_0__": 18736, "question": "Given the following details of a matrix with n columns and 2 rows :\nThe matrix is a binary matrix, which means each element in the matrix can be 0 or 1.\nThe sum of elements of the 0-th(upper) row is given as upper.\nThe sum of elements of the 1-st(lower) row is given as lower.\nThe sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.\nYour task is to reconstruct the matrix with upper, lower and colsum.\nReturn it as a 2-D integer array.\nIf there are more than one valid solution, any of them will be accepted.\nIf no valid solution exists, return an empty 2-D array.\n Example 1:\nInput: upper = 2, lower = 1, colsum = [1,1,1]\nOutput: [[1,1,0],[0,0,1]]\nExplanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.\nExample 2:\nInput: upper = 2, lower = 3, colsum = [2,2,1,1]\nOutput: []\nExample 3:\nInput: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]\nOutput: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]\n Constraints:\n1 <= colsum.length <= 10^5\n0 <= upper, lower <= colsum.length\n0 <= colsum[i] <= 2" }, { "post_href": "https://leetcode.com/problems/number-of-closed-islands/discuss/1250335/DFS-oror-Well-explained-oror-93-faster-oror", "python_solutions": "class Solution:\ndef closedIsland(self, grid: List[List[int]]) -> int:\n \n def dfs(i,j):\n if grid[i][j]==1:\n return True\n if i<=0 or i>=m-1 or j<=0 or j>=n-1:\n return False\n grid[i][j]=1\n up=dfs(i-1,j)\n down=dfs(i+1,j)\n left=dfs(i,j-1)\n right=dfs(i,j+1)\n return left and right and up and down\n \n m,n = len(grid),len(grid[0])\n c=0\n\t# iterate through the grid from 1 to length of grid for rows and columns.\n # the iteration starts from 1 because if a 0 is present in the 0th column, it can't be a closed island.\n for i in range(1,m-1):\n for j in range(1,n-1):\n\t\t\t# if the item in the grid is 0 and it is surrounded by\n # up, down, left, right 1's then increment the count.\n if grid[i][j]==0 and dfs(i,j):\n c+=1\n return c", "slug": "number-of-closed-islands", "post_title": "\ud83d\udc0d DFS || Well-explained || 93% faster ||", "user": "abhi9Rai", "upvotes": 14, "views": 836, "problem_title": "number of closed islands", "number": 1254, "acceptance": 0.642, "difficulty": "Medium", "__index_level_0__": 18746, "question": "Given a 2D grid consists of 0s (land) and 1s (water). An island is a maximal 4-directionally connected group of 0s and a closed island is an island totally (all left, top, right, bottom) surrounded by 1s.\nReturn the number of closed islands.\n Example 1:\nInput: grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]\nOutput: 2\nExplanation: \nIslands in gray are closed because they are completely surrounded by water (group of 1s).\nExample 2:\nInput: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\nOutput: 1\nExample 3:\nInput: grid = [[1,1,1,1,1,1,1],\n [1,0,0,0,0,0,1],\n [1,0,1,1,1,0,1],\n [1,0,1,0,1,0,1],\n [1,0,1,1,1,0,1],\n [1,0,0,0,0,0,1],\n [1,1,1,1,1,1,1]]\nOutput: 2\n Constraints:\n1 <= grid.length, grid[0].length <= 100\n0 <= grid[i][j] <=1" }, { "post_href": "https://leetcode.com/problems/maximum-score-words-formed-by-letters/discuss/2407807/PYTHON-SOL-or-RECURSION-%2B-MEMOIZATION-or-EXPLAINED-or-CLEAR-AND-CONSCISE-or", "python_solutions": "class Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n count , n , dp = [0]*26 , len(words) , {}\n \n for c in letters: count[ord(c) - 97] += 1\n \n def recursion(index,count):\n if index == n: return 0\n \n tpl = tuple(count)\n \n if (index,tpl) in dp: return dp[(index,tpl)]\n \n ans = recursion(index + 1, count)\n \n flag , tmp , cpy , add = True , defaultdict(int) , count.copy() , 0\n for c in words[index]: tmp[c] += 1\n \n for key in tmp:\n if tmp[key] <= cpy[ord(key) - 97]:\n cpy[ord(key) - 97] -= tmp[key]\n add += score[ord(key) - 97] * tmp[key] \n else:\n flag = False\n break\n if flag : ans = max(ans, recursion(index + 1, cpy) + add)\n \n dp[(index,tpl)] = ans\n \n return ans\n \n return recursion(0 , count)", "slug": "maximum-score-words-formed-by-letters", "post_title": "PYTHON SOL | RECURSION + MEMOIZATION | EXPLAINED | CLEAR AND CONSCISE |", "user": "reaper_27", "upvotes": 0, "views": 42, "problem_title": "maximum score words formed by letters", "number": 1255, "acceptance": 0.728, "difficulty": "Hard", "__index_level_0__": 18775, "question": "Given a list of words, list of single letters (might be repeating) and score of every character.\nReturn the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).\nIt is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.\n Example 1:\nInput: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\nOutput: 23\nExplanation:\nScore a=1, c=9, d=5, g=3, o=2\nGiven letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\nWords \"dad\" and \"dog\" only get a score of 21.\nExample 2:\nInput: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\nOutput: 27\nExplanation:\nScore a=4, b=4, c=4, x=5, z=10\nGiven letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\nWord \"xxxz\" only get a score of 25.\nExample 3:\nInput: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\nOutput: 0\nExplanation:\nLetter \"e\" can only be used once.\n Constraints:\n1 <= words.length <= 14\n1 <= words[i].length <= 15\n1 <= letters.length <= 100\nletters[i].length == 1\nscore.length == 26\n0 <= score[i] <= 10\nwords[i], letters[i] contains only lower case English letters." }, { "post_href": "https://leetcode.com/problems/shift-2d-grid/discuss/1935910/Just-Flatten-and-Rotate-the-Array", "python_solutions": "class Solution:\n def rotate(self, nums: List[int], k: int) -> None: # From Leetcode Problem 189. Rotate Array\n n = len(nums)\n k = k % n\n nums[:] = nums[n - k:] + nums[:n - k]\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0])\n arr = [i for sublist in grid for i in sublist] # Flatten out the array\n self.rotate(arr,k) # Rotate the array \n grid = [[arr[i*n+j] for j in range(n)] for i in range(m)] # Convert Flattened output to 2d Matrix\n return grid # Return 2d Result", "slug": "shift-2d-grid", "post_title": "\u2b50 Just Flatten and Rotate the Array", "user": "anCoderr", "upvotes": 5, "views": 330, "problem_title": "shift 2d grid", "number": 1260, "acceptance": 0.68, "difficulty": "Easy", "__index_level_0__": 18779, "question": "Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.\nIn one shift operation:\nElement at grid[i][j] moves to grid[i][j + 1].\nElement at grid[i][n - 1] moves to grid[i + 1][0].\nElement at grid[m - 1][n - 1] moves to grid[0][0].\nReturn the 2D grid after applying shift operation k times.\n Example 1:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[9,1,2],[3,4,5],[6,7,8]]\nExample 2:\nInput: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\nOutput: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\nExample 3:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9\nOutput: [[1,2,3],[4,5,6],[7,8,9]]\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m <= 50\n1 <= n <= 50\n-1000 <= grid[i][j] <= 1000\n0 <= k <= 100" }, { "post_href": "https://leetcode.com/problems/greatest-sum-divisible-by-three/discuss/497058/Python-3-(four-lines)-(Math-Solution)-(no-DP)-(beats-~92)", "python_solutions": "class Solution:\n def maxSumDivThree(self, N: List[int]) -> int:\n A, B, S = heapq.nsmallest(2,[n for n in N if n % 3 == 1]), heapq.nsmallest(2,[n for n in N if n % 3 == 2]), sum(N)\n if S % 3 == 0: return S\n if S % 3 == 1: return S - min(A[0], sum(B) if len(B) > 1 else math.inf)\n if S % 3 == 2: return S - min(B[0], sum(A) if len(A) > 1 else math.inf)\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "greatest-sum-divisible-by-three", "post_title": "Python 3 (four lines) (Math Solution) (no DP) (beats ~92%)", "user": "junaidmansuri", "upvotes": 5, "views": 731, "problem_title": "greatest sum divisible by three", "number": 1262, "acceptance": 0.509, "difficulty": "Medium", "__index_level_0__": 18824, "question": "Given an integer array nums, return the maximum possible sum of elements of the array such that it is divisible by three.\n Example 1:\nInput: nums = [3,6,5,1,8]\nOutput: 18\nExplanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).\nExample 2:\nInput: nums = [4]\nOutput: 0\nExplanation: Since 4 is not divisible by 3, do not pick any number.\nExample 3:\nInput: nums = [1,2,3,4,4]\nOutput: 12\nExplanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).\n Constraints:\n1 <= nums.length <= 4 * 104\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-moves-to-move-a-box-to-their-target-location/discuss/2643673/Python3-Double-BFS-or-O(m2-*-n2)", "python_solutions": "class Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n \n neighbors = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n \n def player_bfs(st_row, st_col, tgt_row, tgt_col):\n nonlocal rows, cols\n if (st_row, st_col) == (tgt_row, tgt_col):\n return True\n q = deque([(st_row, st_col)]) \n seen = [[False] * cols for _ in range(rows)]\n seen[st_row][st_col] = True\n \n while q:\n row, col = q.pop()\n for r, c in neighbors:\n if 0 <= row+r < rows and 0 <= col+c < cols and not seen[row+r][col+c] and grid[row+r][col+c] == '.':\n if row+r == tgt_row and col+c == tgt_col:\n return True\n seen[row+r][col+c] = True\n q.appendleft((row+r, col+c))\n return False\n \n def box_bfs(st_row, st_col):\n nonlocal rows, cols, target\n q = deque([(st_row, st_col, start[0], start[1], 0)])\n seen = {st_row, st_col, start[0], start[1]}\n \n while q:\n row, col, prow, pcol, moves = q.pop()\n grid[row][col] = 'B'\n for r, c in neighbors:\n box_can_move = 0 <= row+r < rows and 0 <= col+c < cols and (row+r, col+c, row-r, col-c) not in seen and grid[row+r][col+c] == '.'\n if box_can_move and player_bfs(prow, pcol, row-r, col-c):\n if (row+r, col+c) == target:\n return moves + 1\n seen.add((row+r, col+c, row-r, col-c))\n q.appendleft((row+r, col+c, row-r, col-c, moves+1))\n grid[row][col] = '.'\n \n return -1\n \n start = target = box = None\n rows, cols = len(grid), len(grid[0])\n for r, row in enumerate(grid):\n for c, pos in enumerate(row):\n if pos == 'S':\n start = (r, c)\n grid[r][c] = '.'\n elif pos == 'T':\n target = (r, c)\n grid[r][c] = '.'\n elif pos == 'B':\n box = (r, c)\n grid[r][c] = '.'\n \n return box_bfs(*box)", "slug": "minimum-moves-to-move-a-box-to-their-target-location", "post_title": "Python3 Double BFS | O(m^2 * n^2)", "user": "ryangrayson", "upvotes": 0, "views": 24, "problem_title": "minimum moves to move a box to their target location", "number": 1263, "acceptance": 0.49, "difficulty": "Hard", "__index_level_0__": 18828, "question": "A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.\nThe game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.\nYour task is to move the box 'B' to the target position 'T' under the following rules:\nThe character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).\nThe character '.' represents the floor which means a free cell to walk.\nThe character '#' represents the wall which means an obstacle (impossible to walk there).\nThere is only one box 'B' and one target cell 'T' in the grid.\nThe 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.\nThe player cannot walk through the box.\nReturn the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.\n Example 1:\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: 3\nExplanation: We return only the number of times the box is pushed.\nExample 2:\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: -1\nExample 3:\nInput: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\nOutput: 5\nExplanation: push the box down, left, left, up and up.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 20\ngrid contains only characters '.', '#', 'S', 'T', or 'B'.\nThere is only one character 'S', 'B', and 'T' in the grid." }, { "post_href": "https://leetcode.com/problems/minimum-time-visiting-all-points/discuss/1114113/Python3-solution-with-explaination", "python_solutions": "class Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n timer = 0\n for i in range(len(points)-1):\n dx = abs(points[i+1][0] - points[i][0])\n dy = abs(points[i+1][1] - points[i][1])\n \n timer = timer + max(dx,dy)\n \n return timer", "slug": "minimum-time-visiting-all-points", "post_title": "Python3 solution with explaination", "user": "shreytheshreyas", "upvotes": 4, "views": 285, "problem_title": "minimum time visiting all points", "number": 1266, "acceptance": 0.7909999999999999, "difficulty": "Easy", "__index_level_0__": 18830, "question": "On a 2D plane, there are n points with integer coordinates points[i] = [xi, yi]. Return the minimum time in seconds to visit all the points in the order given by points.\nYou can move according to these rules:\nIn 1 second, you can either:\nmove vertically by one unit,\nmove horizontally by one unit, or\nmove diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).\nYou have to visit the points in the same order as they appear in the array.\nYou are allowed to pass through points that appear later in the order, but these do not count as visits.\n Example 1:\nInput: points = [[1,1],[3,4],[-1,0]]\nOutput: 7\nExplanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] \nTime from [1,1] to [3,4] = 3 seconds \nTime from [3,4] to [-1,0] = 4 seconds\nTotal time = 7 seconds\nExample 2:\nInput: points = [[3,2],[-2,2]]\nOutput: 5\n Constraints:\npoints.length == n\n1 <= n <= 100\npoints[i].length == 2\n-1000 <= points[i][0], points[i][1] <= 1000" }, { "post_href": "https://leetcode.com/problems/count-servers-that-communicate/discuss/1587912/93-faster-oror-Well-Explained-oror-Thought-Process-oror-Clean-and-Concise", "python_solutions": "class Solution:\ndef countServers(self, grid: List[List[int]]) -> int:\n \n m,n = len(grid),len(grid[0])\n rows = [0]*m\n cols = [0]*n\n total = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]==1:\n rows[i]+=1\n cols[j]+=1\n total+=1\n \n cnt = 0\n for i in range(m):\n for j in range(n):\n if grid[i][j]==1 and rows[i]==1 and cols[j]==1:\n cnt+=1\n \n return total-cnt", "slug": "count-servers-that-communicate", "post_title": "\ud83d\udccc\ud83d\udccc 93% faster || Well-Explained || Thought Process || Clean and Concise \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 2, "views": 147, "problem_title": "count servers that communicate", "number": 1267, "acceptance": 0.593, "difficulty": "Medium", "__index_level_0__": 18862, "question": "You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.\n\nReturn the number of servers that communicate with any other server.\n Example 1:\nInput: grid = [[1,0],[0,1]]\nOutput: 0\nExplanation: No servers can communicate with others.\nExample 2:\nInput: grid = [[1,0],[1,1]]\nOutput: 3\nExplanation: All three servers can communicate with at least one other server.\nExample 3:\nInput: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\nOutput: 4\nExplanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m <= 250\n1 <= n <= 250\ngrid[i][j] == 0 or 1" }, { "post_href": "https://leetcode.com/problems/search-suggestions-system/discuss/436564/Python-A-simple-approach-without-using-Trie", "python_solutions": "class Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n list_ = []\n products.sort()\n for i, c in enumerate(searchWord):\n products = [ p for p in products if len(p) > i and p[i] == c ]\n list_.append(products[:3])\n return list_", "slug": "search-suggestions-system", "post_title": "[Python] A simple approach without using Trie", "user": "crosserclaws", "upvotes": 39, "views": 3500, "problem_title": "search suggestions system", "number": 1268, "acceptance": 0.665, "difficulty": "Medium", "__index_level_0__": 18873, "question": "You are given an array of strings products and a string searchWord.\nDesign a system that suggests at most three product names from products after each character of searchWord is typed. Suggested products should have common prefix with searchWord. If there are more than three products with a common prefix return the three lexicographically minimums products.\nReturn a list of lists of the suggested products after each character of searchWord is typed.\n Example 1:\nInput: products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\nOutput: [[\"mobile\",\"moneypot\",\"monitor\"],[\"mobile\",\"moneypot\",\"monitor\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"]]\nExplanation: products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"].\nAfter typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"].\nAfter typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"].\nExample 2:\nInput: products = [\"havana\"], searchWord = \"havana\"\nOutput: [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\nExplanation: The only word \"havana\" will be always suggested while typing the search word.\n Constraints:\n1 <= products.length <= 1000\n1 <= products[i].length <= 3000\n1 <= sum(products[i].length) <= 2 * 104\nAll the strings of products are unique.\nproducts[i] consists of lowercase English letters.\n1 <= searchWord.length <= 1000\nsearchWord consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/discuss/2488667/LeetCode-The-Hard-Way-DP-with-Explanation", "python_solutions": "class Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n M = 10 ** 9 + 7\n @lru_cache(None)\n def dfs(pos, steps):\n # if we walk outside the array or use all the steps\n # then return 0\n if pos < 0 or pos > steps or pos > arrLen - 1: return 0\n # if we use all the steps, return 1 only if pos is 0\n if steps == 0: return pos == 0\n return (\n # move to the left\n dfs(pos - 1, steps - 1) +\n # stay at current position\n dfs(pos, steps - 1) +\n # move to the right\n dfs(pos + 1, steps - 1) \n ) % M\n return dfs(0, steps)", "slug": "number-of-ways-to-stay-in-the-same-place-after-some-steps", "post_title": "[LeetCode The Hard Way] DP with Explanation", "user": "wingkwong", "upvotes": 1, "views": 94, "problem_title": "number of ways to stay in the same place after some steps", "number": 1269, "acceptance": 0.436, "difficulty": "Hard", "__index_level_0__": 18909, "question": "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).\nGiven two integers steps and arrLen, return the number of ways such that your pointer is still at index 0 after exactly steps steps. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: steps = 3, arrLen = 2\nOutput: 4\nExplanation: There are 4 differents ways to stay at index 0 after 3 steps.\nRight, Left, Stay\nStay, Right, Left\nRight, Stay, Left\nStay, Stay, Stay\nExample 2:\nInput: steps = 2, arrLen = 4\nOutput: 2\nExplanation: There are 2 differents ways to stay at index 0 after 2 steps\nRight, Left\nStay, Stay\nExample 3:\nInput: steps = 4, arrLen = 2\nOutput: 8\n Constraints:\n1 <= steps <= 500\n1 <= arrLen <= 106" }, { "post_href": "https://leetcode.com/problems/find-winner-on-a-tic-tac-toe-game/discuss/1767406/Python-3-solution-with-comments", "python_solutions": "class Solution:\n def tictactoe(self, moves: List[List[int]]) -> str:\n # keep track of the \"net score\" of each row/col/diagonal\n # player A adds 1 to the \"net score\" of each row/col/diagonal they play in,\n # player B subtracts 1\n # scores[0], scores[1] and scores[2] are for rows 0, 1 and 2\n # scores[3], scores[4] and scores[5] are for cols 0, 1 and 2\n # scores[6] and scores[7] are for the forward and backward diagonal\n scores = [0] * 8\n \n for i, (row, col) in enumerate(moves):\n if i % 2 == 0: # if player A is playing\n x = 1\n else: # if player B is playing\n x = -1\n \n scores[row] += x\n scores[col + 3] += x\n if row == col:\n scores[6] += x\n if 2 - row == col:\n scores[7] += x\n \n for score in scores:\n if score == 3:\n return 'A'\n elif score == -3:\n return 'B'\n \n return 'Draw' if len(moves) == 9 else 'Pending'", "slug": "find-winner-on-a-tic-tac-toe-game", "post_title": "Python 3 solution with comments", "user": "dereky4", "upvotes": 15, "views": 871, "problem_title": "find winner on a tic tac toe game", "number": 1275, "acceptance": 0.5429999999999999, "difficulty": "Easy", "__index_level_0__": 18913, "question": "Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:\nPlayers take turns placing characters into empty squares ' '.\nThe first player A always places 'X' characters, while the second player B always places 'O' characters.\n'X' and 'O' characters are always placed into empty squares, never on filled ones.\nThe game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\nThe game also ends if all squares are non-empty.\nNo more moves can be played if the game is over.\nGiven a 2D integer array moves where moves[i] = [rowi, coli] indicates that the ith move will be played on grid[rowi][coli]. return the winner of the game if it exists (A or B). In case the game ends in a draw return \"Draw\". If there are still movements to play return \"Pending\".\nYou can assume that moves is valid (i.e., it follows the rules of Tic-Tac-Toe), the grid is initially empty, and A will play first.\n Example 1:\nInput: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\nOutput: \"A\"\nExplanation: A wins, they always play first.\nExample 2:\nInput: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\nOutput: \"B\"\nExplanation: B wins.\nExample 3:\nInput: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\nOutput: \"Draw\"\nExplanation: The game ends in a draw since there are no moves to make.\n Constraints:\n1 <= moves.length <= 9\nmoves[i].length == 2\n0 <= rowi, coli <= 2\nThere are no repeated elements on moves.\nmoves follow the rules of tic tac toe." }, { "post_href": "https://leetcode.com/problems/number-of-burgers-with-no-waste-of-ingredients/discuss/551868/Math-%2B-Python-Using-2-variables-linear-algebra-to-solve-the-problem", "python_solutions": "class Solution:\n def numOfBurgers(self, tomatoSlices, cheeseSlices):\n\t\t# on the basis of the matrix solution\n ans = [0.5 * tomatoSlices - cheeseSlices, -0.5 * tomatoSlices + 2 * cheeseSlices]\n\t\t\n\t\t# using the constraints to see if solution satisfies it\n if 0 <= int(ans[0]) == ans[0] and 0 <= int(ans[1]) == ans[1]:\n return [int(ans[0]), int(ans[1])]\n else:\n return []", "slug": "number-of-burgers-with-no-waste-of-ingredients", "post_title": "[Math + Python] Using 2 variables linear algebra to solve the problem", "user": "Suraj1127", "upvotes": 3, "views": 203, "problem_title": "number of burgers with no waste of ingredients", "number": 1276, "acceptance": 0.506, "difficulty": "Medium", "__index_level_0__": 18938, "question": "Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:\nJumbo Burger: 4 tomato slices and 1 cheese slice.\nSmall Burger: 2 Tomato slices and 1 cheese slice.\nReturn [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].\n Example 1:\nInput: tomatoSlices = 16, cheeseSlices = 7\nOutput: [1,6]\nExplantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\nThere will be no remaining ingredients.\nExample 2:\nInput: tomatoSlices = 17, cheeseSlices = 4\nOutput: []\nExplantion: There will be no way to use all ingredients to make small and jumbo burgers.\nExample 3:\nInput: tomatoSlices = 4, cheeseSlices = 17\nOutput: []\nExplantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.\n Constraints:\n0 <= tomatoSlices, cheeseSlices <= 107" }, { "post_href": "https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/1736397/Python-Thought-process-for-the-DP-solution-with-very-simple-explanation-(with-images)", "python_solutions": "class Solution:\n def countSquares(self, matrix: List[List[int]]) -> int:\n \n count=matrix.count(1)\n count=0\n for r in range(len(matrix)):\n for c in range(len(matrix[0])):\n if matrix[r][c]==1:\n count+=1\n if r==0 or c==0: continue\n \n old_val=matrix[r][c]\n matrix[r][c]=min(matrix[r-1][c-1], matrix[r][c-1],matrix[r-1][c]) + 1 if matrix[r][c]==1 else 0\n count= count+ matrix[r][c]- old_val \n return count", "slug": "count-square-submatrices-with-all-ones", "post_title": "Python \ud83d\udc0d Thought process for the DP solution with very simple explanation (with images)", "user": "InjySarhan", "upvotes": 4, "views": 354, "problem_title": "count square submatrices with all ones", "number": 1277, "acceptance": 0.7440000000000001, "difficulty": "Medium", "__index_level_0__": 18949, "question": "Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.\n Example 1:\nInput: matrix =\n[\n [0,1,1,1],\n [1,1,1,1],\n [0,1,1,1]\n]\nOutput: 15\nExplanation: \nThere are 10 squares of side 1.\nThere are 4 squares of side 2.\nThere is 1 square of side 3.\nTotal number of squares = 10 + 4 + 1 = 15.\nExample 2:\nInput: matrix = \n[\n [1,0,1],\n [1,1,0],\n [1,1,0]\n]\nOutput: 7\nExplanation: \nThere are 6 squares of side 1. \nThere is 1 square of side 2. \nTotal number of squares = 6 + 1 = 7.\n Constraints:\n1 <= arr.length <= 300\n1 <= arr[0].length <= 300\n0 <= arr[i][j] <= 1" }, { "post_href": "https://leetcode.com/problems/palindrome-partitioning-iii/discuss/2593400/Dynamic-Programming-oror-Recursion-oror-Memoization-oror-Easy-Intuition-oror-Python", "python_solutions": "class Solution:\n def palindromePartition(self, s: str, k: int) -> int:\n \n \n\t\t#This is the cost function \n \n def Cost(s):\n i,j,c=0,len(s)-1,0\n \n while i int:\n p,s=1,0\n while n!=0:\n p*=(n%10)\n s+=(n%10)\n n//=10\n return p-s", "slug": "subtract-the-product-and-sum-of-digits-of-an-integer", "post_title": "Python 3 (20ms) | 3 Solutions | Fastest Iterative & One-Liners | Super Easy", "user": "MrShobhit", "upvotes": 12, "views": 659, "problem_title": "subtract the product and sum of digits of an integer", "number": 1281, "acceptance": 0.867, "difficulty": "Easy", "__index_level_0__": 18970, "question": "Given an integer number n, return the difference between the product of its digits and the sum of its digits.\n Example 1:\nInput: n = 234\nOutput: 15 \nExplanation: \nProduct of digits = 2 * 3 * 4 = 24 \nSum of digits = 2 + 3 + 4 = 9 \nResult = 24 - 9 = 15\nExample 2:\nInput: n = 4421\nOutput: 21\nExplanation: \nProduct of digits = 4 * 4 * 2 * 1 = 32 \nSum of digits = 4 + 4 + 2 + 1 = 11 \nResult = 32 - 11 = 21\n Constraints:\n1 <= n <= 10^5" }, { "post_href": "https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/discuss/712693/Python-O(n)-Easy-to-Understand", "python_solutions": "class Solution:\n # Time: O(n)\n # Space: O(n)\n def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:\n res, dic = [], {}\n for idx, group in enumerate(groupSizes):\n if group not in dic:\n dic[group] = [idx]\n else:\n dic[group].append(idx)\n \n if len(dic[group]) == group:\n res.append(dic[group])\n del dic[group]\n return res", "slug": "group-the-people-given-the-group-size-they-belong-to", "post_title": "Python O(n) Easy to Understand", "user": "whissely", "upvotes": 5, "views": 214, "problem_title": "group the people given the group size they belong to", "number": 1282, "acceptance": 0.857, "difficulty": "Medium", "__index_level_0__": 19027, "question": "There are n people that are split into some unknown number of groups. Each person is labeled with a unique ID from 0 to n - 1.\nYou are given an integer array groupSizes, where groupSizes[i] is the size of the group that person i is in. For example, if groupSizes[1] = 3, then person 1 must be in a group of size 3.\nReturn a list of groups such that each person i is in a group of size groupSizes[i].\nEach person should appear in exactly one group, and every person must be in a group. If there are multiple answers, return any of them. It is guaranteed that there will be at least one valid solution for the given input.\n Example 1:\nInput: groupSizes = [3,3,3,3,3,1,3]\nOutput: [[5],[0,1,2],[3,4,6]]\nExplanation: \nThe first group is [5]. The size is 1, and groupSizes[5] = 1.\nThe second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\nThe third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\nOther possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].\nExample 2:\nInput: groupSizes = [2,1,3,3,3,2]\nOutput: [[1],[0,5],[2,3,4]]\n Constraints:\ngroupSizes.length == n\n1 <= n <= 500\n1 <= groupSizes[i] <= n" }, { "post_href": "https://leetcode.com/problems/find-the-smallest-divisor-given-a-threshold/discuss/863333/Python3-Binary-search-with-explanation", "python_solutions": "class Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n left, right = 1, max(nums)\n while left + 1 < right:\n mid = (left + right) // 2\n div_sum = self.get_sum(mid, nums)\n if div_sum > threshold:\n left = mid\n else:\n right = mid\n \n div_sum = self.get_sum(left, nums)\n if div_sum <= threshold:\n return left\n return right\n \n \n def get_sum(self, divisor, nums):\n res = 0\n for n in nums:\n tmp = n // divisor\n if tmp * divisor < n:\n tmp += 1\n \n res += tmp\n \n return res", "slug": "find-the-smallest-divisor-given-a-threshold", "post_title": "Python3 Binary search with explanation", "user": "ethuoaiesec", "upvotes": 3, "views": 313, "problem_title": "find the smallest divisor given a threshold", "number": 1283, "acceptance": 0.5539999999999999, "difficulty": "Medium", "__index_level_0__": 19062, "question": "Given an array of integers nums and an integer threshold, we will choose a positive integer divisor, divide all the array by it, and sum the division's result. Find the smallest divisor such that the result mentioned above is less than or equal to threshold.\nEach result of the division is rounded to the nearest integer greater than or equal to that element. (For example: 7/3 = 3 and 10/2 = 5).\nThe test cases are generated so that there will be an answer.\n Example 1:\nInput: nums = [1,2,5,9], threshold = 6\nOutput: 5\nExplanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. \nIf the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). \nExample 2:\nInput: nums = [44,22,33,11,1], threshold = 5\nOutput: 44\n Constraints:\n1 <= nums.length <= 5 * 104\n1 <= nums[i] <= 106\nnums.length <= threshold <= 106" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix/discuss/446552/Python-3-(ten-lines)-(Check-All-Permutations)", "python_solutions": "class Solution:\n def minFlips(self, G: List[List[int]]) -> int:\n M, N = len(G), len(G[0])\n P = [(i,j) for i,j in itertools.product(range(M),range(N))]\n for n in range(M*N+1):\n for p in itertools.permutations(P,n):\n H = list(map(list,G))\n for (x,y) in p:\n for (i,j) in (x,y-1),(x,y),(x,y+1),(x-1,y),(x+1,y):\n if 0 <= i < M and 0 <= j < N: H[i][j] = 1 - H[i][j]\n if max(max(H)) == 0: return n\n return -1\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix", "post_title": "Python 3 (ten lines) (Check All Permutations)", "user": "junaidmansuri", "upvotes": 3, "views": 441, "problem_title": "minimum number of flips to convert binary matrix to zero matrix", "number": 1284, "acceptance": 0.72, "difficulty": "Hard", "__index_level_0__": 19077, "question": "Given a m x n binary matrix mat. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing 1 to 0 and 0 to 1). A pair of cells are called neighbors if they share one edge.\nReturn the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.\nA binary matrix is a matrix with all cells equal to 0 or 1 only.\nA zero matrix is a matrix with all cells equal to 0.\n Example 1:\nInput: mat = [[0,0],[0,1]]\nOutput: 3\nExplanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\nExample 2:\nInput: mat = [[0]]\nOutput: 0\nExplanation: Given matrix is a zero matrix. We do not need to change it.\nExample 3:\nInput: mat = [[1,0,0],[1,0,0]]\nOutput: -1\nExplanation: Given matrix cannot be a zero matrix.\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 3\nmat[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/element-appearing-more-than-25-in-sorted-array/discuss/452166/Python-3-(four-different-one-line-solutions)-(beats-100)", "python_solutions": "class Solution:\n def findSpecialInteger(self, A: List[int]) -> int:\n return collections.Counter(A).most_common(1)[0][0]\n\t\t\n\nfrom statistics import mode\n\nclass Solution:\n def findSpecialInteger(self, A: List[int]) -> int:\n return mode(A)\n\n\nclass Solution:\n def findSpecialInteger(self, A: List[int]) -> int:\n return max(set(A), key = A.count)\n\t\t\n\t\t\nclass Solution:\n def findSpecialInteger(self, A: List[int]) -> int:\n return (lambda C: max(C.keys(), key = lambda x: C[x]))(collections.Counter(A))\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "element-appearing-more-than-25-in-sorted-array", "post_title": "Python 3 (four different one-line solutions) (beats 100%)", "user": "junaidmansuri", "upvotes": 18, "views": 1800, "problem_title": "element appearing more than 25 percent in sorted array", "number": 1287, "acceptance": 0.595, "difficulty": "Easy", "__index_level_0__": 19078, "question": "Given an integer array sorted in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer.\n Example 1:\nInput: arr = [1,2,2,6,6,6,6,7,10]\nOutput: 6\nExample 2:\nInput: arr = [1,1]\nOutput: 1\n Constraints:\n1 <= arr.length <= 104\n0 <= arr[i] <= 105" }, { "post_href": "https://leetcode.com/problems/remove-covered-intervals/discuss/1784520/Python3-SORTING-Explained", "python_solutions": "class Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n res, longest = len(intervals), 0\n srtd = sorted(intervals, key = lambda i: (i[0], -i[1]))\n \n for _, end in srtd:\n if end <= longest:\n res -= 1\n else:\n longest = end\n \n return res", "slug": "remove-covered-intervals", "post_title": "\u2714\ufe0f [Python3] SORTING \ud83d\udc40, Explained", "user": "artod", "upvotes": 46, "views": 1600, "problem_title": "remove covered intervals", "number": 1288, "acceptance": 0.5720000000000001, "difficulty": "Medium", "__index_level_0__": 19099, "question": "Given an array intervals where intervals[i] = [li, ri] represent the interval [li, ri), remove all intervals that are covered by another interval in the list.\nThe interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.\nReturn the number of remaining intervals.\n Example 1:\nInput: intervals = [[1,4],[3,6],[2,8]]\nOutput: 2\nExplanation: Interval [3,6] is covered by [2,8], therefore it is removed.\nExample 2:\nInput: intervals = [[1,4],[2,3]]\nOutput: 1\n Constraints:\n1 <= intervals.length <= 1000\nintervals[i].length == 2\n0 <= li < ri <= 105\nAll the given intervals are unique." }, { "post_href": "https://leetcode.com/problems/minimum-falling-path-sum-ii/discuss/1998001/Python-DP-Solution-or-Min-and-Second-min-or-Faster-than-79.77", "python_solutions": "class Solution:\n def minFallingPathSum(self, grid: List[List[int]]) -> int:\n rows = len(grid)\n cols = len(grid[0])\n min1 = min11 = float('inf') # min1 -> minimum , min11 -> second minimum in even indexed row\n min2 = min22 = float('inf') # min2 -> minimum , min22 -> second minimum in odd indexed row\n for i in range(rows):\n for j in range(cols):\n if i==0:\n if grid[i][j]<=min1: # Logic to find minimum and second minimum\n min11 = min1\n min1 = grid[i][j]\n elif grid[i][j] then add the second minimum value\n grid[i][j] += min11\n else: # Else -> add the minimum value\n grid[i][j] += min1\n if grid[i][j] int:\n answer = 0\n while head: \n answer = 2*answer + head.val \n head = head.next \n return answer", "slug": "convert-binary-number-in-a-linked-list-to-integer", "post_title": "[Python] Simple. 20ms.", "user": "rohin7", "upvotes": 200, "views": 7800, "problem_title": "convert binary number in a linked list to integer", "number": 1290, "acceptance": 0.825, "difficulty": "Easy", "__index_level_0__": 19134, "question": "Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.\nReturn the decimal value of the number in the linked list.\nThe most significant bit is at the head of the linked list.\n Example 1:\nInput: head = [1,0,1]\nOutput: 5\nExplanation: (101) in base 2 = (5) in base 10\nExample 2:\nInput: head = [0]\nOutput: 0\n Constraints:\nThe Linked List is not empty.\nNumber of nodes will not exceed 30.\nEach node's value is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/sequential-digits/discuss/1713379/Python-3-(20ms)-or-Faster-than-95-or-Generating-All-Sequential-Digits-within-Range", "python_solutions": "class Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n l=len(str(low))\n h=len(str(high))\n ans=[]\n a=[12,23,34,45,56,67,78,89]\n t=0\n while l<=h:\n for i in a:\n for j in range(0,l-2):\n t=i%10\n if i==9:\n break\n i=int(str(i)+str(t+1))\n if i%10==0:\n break\n if i>=low and i<=high:\n ans.append(i)\n l+=1\n return ans", "slug": "sequential-digits", "post_title": "Python 3 (20ms) | Faster than 95% | Generating All Sequential Digits within Range", "user": "MrShobhit", "upvotes": 3, "views": 64, "problem_title": "sequential digits", "number": 1291, "acceptance": 0.613, "difficulty": "Medium", "__index_level_0__": 19163, "question": "An integer has sequential digits if and only if each digit in the number is one more than the previous digit.\nReturn a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.\n Example 1:\nInput: low = 100, high = 300\nOutput: [123,234]\nExample 2:\nInput: low = 1000, high = 13000\nOutput: [1234,2345,3456,4567,5678,6789,12345]\n Constraints:\n10 <= low <= high <= 10^9" }, { "post_href": "https://leetcode.com/problems/maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/discuss/691648/Python3-binary-search-like-bisect_right-Maximum-Side-Length-of-a-Square-with-Sum-less-Threshold", "python_solutions": "class Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n ans = 0 \n m = len(mat)\n n = len(mat[0])\n presum = [[0] * (n+1) for _ in range(m+1)]\n for i in range(1, m+1):\n for j in range(1, n+1):\n presum[i][j] = mat[i-1][j-1] + presum[i][j-1] + presum[i-1][j] - presum[i-1][j-1] \n lo, hi = 1, min(i, j) + 1\n while lo < hi:\n mid = (lo + hi)//2\n cursum = presum[i][j] - presum[i-mid][j] - presum[i][j-mid] + presum[i-mid][j-mid]\n if cursum > threshold:\n hi = mid\n else:\n lo = mid + 1\n ans = max(ans, lo-1)\n return ans", "slug": "maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold", "post_title": "Python3 binary search like bisect_right - Maximum Side Length of a Square with Sum <= Threshold", "user": "r0bertz", "upvotes": 1, "views": 165, "problem_title": "maximum side length of a square with sum less than or equal to threshold", "number": 1292, "acceptance": 0.532, "difficulty": "Medium", "__index_level_0__": 19198, "question": "Given a m x n matrix mat and an integer threshold, return the maximum side-length of a square with a sum less than or equal to threshold or return 0 if there is no such square.\n Example 1:\nInput: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\nOutput: 2\nExplanation: The maximum side length of square with sum less than 4 is 2 as shown.\nExample 2:\nInput: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1\nOutput: 0\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 300\n0 <= mat[i][j] <= 104\n0 <= threshold <= 105" }, { "post_href": "https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/discuss/2758292/Python-Simple-and-Easy-Way-to-Solve-or-95-Faster", "python_solutions": "class Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n m, n = len(grid), len(grid[0])\n \n # x, y, obstacles, steps\n q = deque([(0,0,k,0)])\n seen = set()\n \n while q:\n x, y, left, steps = q.popleft()\n if (x,y,left) in seen or left<0:\n continue\n if (x, y) == (m-1, n-1):\n return steps\n seen.add((x,y,left))\n if grid[x][y] == 1:\n left-=1\n for dx, dy in [(1,0), (-1,0), (0,1), (0,-1)]:\n new_x, new_y = x+dx, y+dy\n if 0<=new_x (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).\nExample 2:\nInput: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\nOutput: -1\nExplanation: We need to eliminate at least two obstacles to find such a walk.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 40\n1 <= k <= m * n\ngrid[i][j] is either 0 or 1.\ngrid[0][0] == grid[m - 1][n - 1] == 0" }, { "post_href": "https://leetcode.com/problems/find-numbers-with-even-number-of-digits/discuss/468107/Python-3-lightning-fast-one-line-solution", "python_solutions": "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n return len([x for x in nums if len(str(x)) % 2 == 0])", "slug": "find-numbers-with-even-number-of-digits", "post_title": "Python 3 lightning fast one line solution", "user": "denisrasulev", "upvotes": 31, "views": 7300, "problem_title": "find numbers with even number of digits", "number": 1295, "acceptance": 0.77, "difficulty": "Easy", "__index_level_0__": 19237, "question": "Given an array nums of integers, return how many of them contain an even number of digits.\n Example 1:\nInput: nums = [12,345,2,6,7896]\nOutput: 2\nExplanation: \n12 contains 2 digits (even number of digits). \n345 contains 3 digits (odd number of digits). \n2 contains 1 digit (odd number of digits). \n6 contains 1 digit (odd number of digits). \n7896 contains 4 digits (even number of digits). \nTherefore only 12 and 7896 contain an even number of digits.\nExample 2:\nInput: nums = [555,901,482,1771]\nOutput: 1 \nExplanation: \nOnly 1771 contains an even number of digits.\n Constraints:\n1 <= nums.length <= 500\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/discuss/785364/O(N-log(N))-time-and-O(N)-space-Python3-using-Hashmap-and-lists", "python_solutions": "class Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n hand = nums\n W = k\n if not hand and W > 0:\n return False\n if W > len(hand):\n return False\n if W == 0 or W == 1: \n return True\n expectation_map = {}\n # self.count keep track of the numbers of cards that have been successfully counted as a straight,\n # when self.count == len(hand) => All cards are part of a valid straight \n self.count = 0\n handLength = len(hand)\n\n #Sort the hand.\n sortedHand = sorted(hand)\n\n \n \"\"\"\n This method updates the expectation map in the following way:\n a) If the len(l) == W\n => We've completed a straight of length W, add it towards the final count\n b) if the next expected number (num+1) is already in the map \n => add the list to a queue of hands waiting to make a straight\n c) if expected number (num+1) not in the map \n => Add a new expectation key with value as a new queue with this list \n \"\"\"\n def update_expectation_with_list(expectation_map, num, l, W):\n # If we have W consecutive numbers, we're done with this set, count towards final count\n if len(l) == W:\n self.count += W\n # we need more numbers to make this straight, add back with next expected num \n else:\n exp = num + 1\n # Some other list is already expecting this number, add to the queue\n if exp in expectation_map:\n expectation_map[exp].append(l)\n\n # New expected number, create new key and set [l] as value\n else:\n expectation_map[exp] = [l]\n \n \"\"\"\n Very similar to update_expectation_with_list. The difference here is we have the first card of the straight and thus we need to handle it correctly (set the value as a list of lists)\n \"\"\"\n def update_expectation_with_integer(expectation_map, num):\n exp = num + 1\n # Some other list is already expecting this number, add to the queue\n if exp in expectation_map:\n expectation_map[exp].append([num])\n # New expected number, create new key and set [num] as value\n else:\n expectation_map[exp] = [[num]]\n \n for idx,num in enumerate(sortedHand):\n # A possible straight can be formed with this number\n if num in expectation_map:\n # there are multiple hands waiting for this number\n if len(expectation_map[num]) > 1:\n # pop the first hand\n l = expectation_map[num].pop(0)\n # add num to this hand\n l.append(num)\n # Update the expectation map\n update_expectation_with_list(expectation_map, num, l, W)\n \n # there's only one hand expecting this number\n else:\n # pop the first hand\n l = expectation_map[num].pop(0)\n l.append(num)\n\n # Important : del the key! There's no other hand expecting this number\n expectation_map.pop(num) \n update_expectation_with_list(expectation_map, num, l, W)\n \n # Nothing is expecting this number, add new expectation to the map\n else:\n update_expectation_with_integer(expectation_map, num)\n \n return self.count == handLength", "slug": "divide-array-in-sets-of-k-consecutive-numbers", "post_title": "O(N log(N)) time and O(N) space- Python3 using Hashmap and lists", "user": "prajwalpv", "upvotes": 1, "views": 169, "problem_title": "divide array in sets of k consecutive numbers", "number": 1296, "acceptance": 0.5660000000000001, "difficulty": "Medium", "__index_level_0__": 19294, "question": "Given an array of integers nums and a positive integer k, check whether it is possible to divide this array into sets of k consecutive numbers.\nReturn true if it is possible. Otherwise, return false.\n Example 1:\nInput: nums = [1,2,3,3,4,4,5,6], k = 4\nOutput: true\nExplanation: Array can be divided into [1,2,3,4] and [3,4,5,6].\nExample 2:\nInput: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput: true\nExplanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].\nExample 3:\nInput: nums = [1,2,3,4], k = 3\nOutput: false\nExplanation: Each array should be divided in subarrays of size 3.\n Constraints:\n1 <= k <= nums.length <= 105\n1 <= nums[i] <= 109\n Note: This question is the same as 846: https://leetcode.com/problems/hand-of-straights/" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/discuss/1905801/python-easy-approach", "python_solutions": "class Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n s1 = []\n count ={}\n while minSize <= maxSize:\n for i in range(0,len(s)):\n if (i+ minSize) <=len(s) and len(set(s[i: i+ minSize])) <= maxLetters:\n s1.append(s[i: i+ minSize])\n minSize += 1 \n for i in s1:\n count[i] = count[i] + 1 if i in count else 1 \n return max(count.values()) if count else 0", "slug": "maximum-number-of-occurrences-of-a-substring", "post_title": "python easy approach", "user": "hari07", "upvotes": 4, "views": 286, "problem_title": "maximum number of occurrences of a substring", "number": 1297, "acceptance": 0.52, "difficulty": "Medium", "__index_level_0__": 19299, "question": "Given a string s, return the maximum number of occurrences of any substring under the following rules:\nThe number of unique characters in the substring must be less than or equal to maxLetters.\nThe substring size must be between minSize and maxSize inclusive.\n Example 1:\nInput: s = \"aababcaab\", maxLetters = 2, minSize = 3, maxSize = 4\nOutput: 2\nExplanation: Substring \"aab\" has 2 occurrences in the original string.\nIt satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).\nExample 2:\nInput: s = \"aaaa\", maxLetters = 1, minSize = 3, maxSize = 3\nOutput: 2\nExplanation: Substring \"aaa\" occur 2 times in the string. It can overlap.\n Constraints:\n1 <= s.length <= 105\n1 <= maxLetters <= 26\n1 <= minSize <= maxSize <= min(26, s.length)\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-candies-you-can-get-from-boxes/discuss/2841531/Easy-to-understand-BFS-Solution-(with-explanation)", "python_solutions": "class Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n myKeys = set()\n canVisit = set(initialBoxes)\n q = initialBoxes[:]\n # Check [all keys we can get] and [all boxes we can visit]\n while q:\n box = q.pop(0)\n myKeys.update(set((keys[box]))) # Add the keys in box into \"myKeys\"\n canVisit.add(box) # Add current box into \"canVisit\"\n newBoxes = containedBoxes[box] # Add next boxes to the queue\n for nb in newBoxes:\n q.append(nb)\n \n ans = 0\n # Visit all boxes we can visit \n for i in canVisit:\n # We can open the box only if we have the key or box's status is open(1)\n if i in myKeys or status[i] == 1:\n ans += candies[i]\n return ans", "slug": "maximum-candies-you-can-get-from-boxes", "post_title": "Easy to understand BFS Solution (with explanation)", "user": "child70370636", "upvotes": 0, "views": 1, "problem_title": "maximum candies you can get from boxes", "number": 1298, "acceptance": 0.609, "difficulty": "Hard", "__index_level_0__": 19304, "question": "You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:\nstatus[i] is 1 if the ith box is open and 0 if the ith box is closed,\ncandies[i] is the number of candies in the ith box,\nkeys[i] is a list of the labels of the boxes you can open after opening the ith box.\ncontainedBoxes[i] is a list of the boxes you found inside the ith box.\nYou are given an integer array initialBoxes that contains the labels of the boxes you initially have. You can take all the candies in any open box and you can use the keys in it to open new boxes and you also can use the boxes you find in it.\nReturn the maximum number of candies you can get following the rules above.\n Example 1:\nInput: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\nOutput: 16\nExplanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\nBox 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2.\nIn box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\nTotal number of candies collected = 7 + 4 + 5 = 16 candy.\nExample 2:\nInput: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\nOutput: 6\nExplanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\nThe total number of candies will be 6.\n Constraints:\nn == status.length == candies.length == keys.length == containedBoxes.length\n1 <= n <= 1000\nstatus[i] is either 0 or 1.\n1 <= candies[i] <= 1000\n0 <= keys[i].length <= n\n0 <= keys[i][j] < n\nAll values of keys[i] are unique.\n0 <= containedBoxes[i].length <= n\n0 <= containedBoxes[i][j] < n\nAll values of containedBoxes[i] are unique.\nEach box is contained in one box at most.\n0 <= initialBoxes.length <= n\n0 <= initialBoxes[i] < n" }, { "post_href": "https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/discuss/1058153/Easy-and-simple-python-solution-or-O(n)", "python_solutions": "class Solution:\n def replaceElements(self, arr: List[int]) -> List[int]:\n mx = arr[-1]\n arr[-1] = -1\n for i in range(len(arr) - 2, -1, -1):\n temp = arr[i]\n arr[i] = mx\n if mx < temp: mx = temp\n return arr", "slug": "replace-elements-with-greatest-element-on-right-side", "post_title": "Easy and simple python solution | O(n)", "user": "vanigupta20024", "upvotes": 5, "views": 510, "problem_title": "replace elements with greatest element on right side", "number": 1299, "acceptance": 0.747, "difficulty": "Easy", "__index_level_0__": 19306, "question": "Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.\nAfter doing so, return the array.\n Example 1:\nInput: arr = [17,18,5,4,6,1]\nOutput: [18,6,6,6,1,-1]\nExplanation: \n- index 0 --> the greatest element to the right of index 0 is index 1 (18).\n- index 1 --> the greatest element to the right of index 1 is index 4 (6).\n- index 2 --> the greatest element to the right of index 2 is index 4 (6).\n- index 3 --> the greatest element to the right of index 3 is index 4 (6).\n- index 4 --> the greatest element to the right of index 4 is index 5 (1).\n- index 5 --> there are no elements to the right of index 5, so we put -1.\nExample 2:\nInput: arr = [400]\nOutput: [-1]\nExplanation: There are no elements to the right of index 0.\n Constraints:\n1 <= arr.length <= 104\n1 <= arr[i] <= 105" }, { "post_href": "https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/463586/Python3-Sort-and-scan", "python_solutions": "class Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n arr.sort()\n s, n = 0, len(arr)\n \n for i in range(n):\n ans = round((target - s)/n)\n if ans <= arr[i]: return ans \n s += arr[i]\n n -= 1\n \n return arr[-1]", "slug": "sum-of-mutated-array-closest-to-target", "post_title": "[Python3] Sort & scan", "user": "ye15", "upvotes": 20, "views": 1700, "problem_title": "sum of mutated array closest to target", "number": 1300, "acceptance": 0.431, "difficulty": "Medium", "__index_level_0__": 19347, "question": "Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.\nIn case of a tie, return the minimum such integer.\nNotice that the answer is not neccesarilly a number from arr.\n Example 1:\nInput: arr = [4,9,3], target = 10\nOutput: 3\nExplanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.\nExample 2:\nInput: arr = [2,3,5], target = 10\nOutput: 5\nExample 3:\nInput: arr = [60864,25176,27249,21296,20204], target = 56803\nOutput: 11361\n Constraints:\n1 <= arr.length <= 104\n1 <= arr[i], target <= 105" }, { "post_href": "https://leetcode.com/problems/number-of-paths-with-max-score/discuss/463581/Python3-Bottom-up-DP", "python_solutions": "class Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n \"\"\"bottom-up dp\"\"\"\n n = len(board) #dimension\n\n #count > 0 also indicates state is reachable\n dp = [[0, 0] for _ in range(n+1)] #score-count (augment by 1 for convenience)\n \n for i in reversed(range(n)):\n #not assuming reachability while updating state\n copy = [[0, 0] for _ in range(n+1)] #to be updated to new dp\n for j in reversed(range(n)): \n if board[i][j] == \"X\": continue #skip obstacle\n if board[i][j] == \"S\": #initialize \"S\"\n copy[j] = [0, 1]\n continue \n #find max score from neighbors\n for candidate in (copy[j+1], dp[j], dp[j+1]): #right/below/right-below\n if not candidate[1]: continue #not reachable\n if copy[j][0] < candidate[0]: copy[j] = candidate[:]\n elif copy[j][0] == candidate[0]: copy[j][1] = (copy[j][1] + candidate[1])%(10**9+7)\n #update with board number \n if board[i][j] != \"E\": copy[j][0] += int(board[i][j])\n dp = copy\n return dp[0]", "slug": "number-of-paths-with-max-score", "post_title": "[Python3] Bottom-up DP", "user": "ye15", "upvotes": 1, "views": 65, "problem_title": "number of paths with max score", "number": 1301, "acceptance": 0.387, "difficulty": "Hard", "__index_level_0__": 19355, "question": "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'.\nYou need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\nReturn a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.\nIn case there is no path, return [0, 0].\n Example 1:\nInput: board = [\"E23\",\"2X2\",\"12S\"]\nOutput: [7,1]\nExample 2:\nInput: board = [\"E12\",\"1X1\",\"21S\"]\nOutput: [4,2]\nExample 3:\nInput: board = [\"E11\",\"XXX\",\"11S\"]\nOutput: [0,0]\n Constraints:\n2 <= board.length == board[i].length <= 100" }, { "post_href": "https://leetcode.com/problems/deepest-leaves-sum/discuss/1763924/Python-Simple-Level-Order-Traversal", "python_solutions": "class Solution:\n def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:\n q = [(root, 0)]\n ans = 0\n curr_level = 0 # Maintains the current level we are at\n while len(q) != 0: # Do a simple Level Order Traversal\n current, max_level = q.pop(0)\n if max_level > curr_level: # Update the ans as curr_level gets outdated\n curr_level = max_level # Update curr_level\n ans = 0 # Ans needs to be constructed for the new level i.e. max_level\n ans += current.val\n if current.left is not None:\n q.append((current.left, max_level + 1))\n if current.right is not None:\n q.append((current.right, max_level + 1))\n return ans", "slug": "deepest-leaves-sum", "post_title": "Python Simple Level Order Traversal", "user": "anCoderr", "upvotes": 3, "views": 139, "problem_title": "deepest leaves sum", "number": 1302, "acceptance": 0.868, "difficulty": "Medium", "__index_level_0__": 19360, "question": "Given the root of a binary tree, return the sum of values of its deepest leaves.\n Example 1:\nInput: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\nOutput: 15\nExample 2:\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 19\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n1 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/discuss/463818/Two-Solutions-in-Python-3-(one-line)-(beats-100)-(24-ms)", "python_solutions": "class Solution:\n def sumZero(self, n: int) -> List[int]:\n return list(range(1,n))+[-n*(n-1)//2]", "slug": "find-n-unique-integers-sum-up-to-zero", "post_title": "Two Solutions in Python 3 (one line) (beats 100%) (24 ms)", "user": "junaidmansuri", "upvotes": 12, "views": 1300, "problem_title": "find n unique integers sum up to zero", "number": 1304, "acceptance": 0.7709999999999999, "difficulty": "Easy", "__index_level_0__": 19393, "question": "Given an integer n, return any array containing n unique integers such that they add up to 0.\n Example 1:\nInput: n = 5\nOutput: [-7,-1,1,3,4]\nExplanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].\nExample 2:\nInput: n = 3\nOutput: [-1,0,1]\nExample 3:\nInput: n = 1\nOutput: [0]\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/all-elements-in-two-binary-search-trees/discuss/523589/python-only-2-lines-easy-to-read-with-explanation.-Can-it-be-any-shorter", "python_solutions": "class Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n h = lambda r: h(r.left) + [r.val] + h(r.right) if r else []\n return sorted( h(root1) + h(root2) )", "slug": "all-elements-in-two-binary-search-trees", "post_title": "python, only 2 lines, easy to read, with explanation. Can it be any shorter?", "user": "rmoskalenko", "upvotes": 2, "views": 155, "problem_title": "all elements in two binary search trees", "number": 1305, "acceptance": 0.7979999999999999, "difficulty": "Medium", "__index_level_0__": 19438, "question": "Given two binary search trees root1 and root2, return a list containing all the integers from both trees sorted in ascending order.\n Example 1:\nInput: root1 = [2,1,4], root2 = [1,0,3]\nOutput: [0,1,1,2,3,4]\nExample 2:\nInput: root1 = [1,null,8], root2 = [8,1]\nOutput: [1,1,8,8]\n Constraints:\nThe number of nodes in each tree is in the range [0, 5000].\n-105 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/jump-game-iii/discuss/571683/Python3-3-Lines-DFS.-O(N)-time-and-space.-Recursion", "python_solutions": "class Solution:\n def canReach(self, arr: List[int], i: int) -> bool:\n if i < 0 or i >= len(arr) or arr[i] < 0: return False\n arr[i] *= -1 # Mark visited\n return arr[i] == 0 or self.canReach(arr, i - arr[i]) or self.canReach(arr, i + arr[i])", "slug": "jump-game-iii", "post_title": "[Python3] 3 Lines DFS. O(N) time and space. Recursion", "user": "jimmyyentran", "upvotes": 5, "views": 245, "problem_title": "jump game iii", "number": 1306, "acceptance": 0.631, "difficulty": "Medium", "__index_level_0__": 19463, "question": "Given an array of non-negative integers arr, you are initially positioned at start index of the array. When you are at index i, you can jump to i + arr[i] or i - arr[i], check if you can reach any index with value 0.\nNotice that you can not jump outside of the array at any time.\n Example 1:\nInput: arr = [4,2,3,0,3,1,2], start = 5\nOutput: true\nExplanation: \nAll possible ways to reach at index 3 with value 0 are: \nindex 5 -> index 4 -> index 1 -> index 3 \nindex 5 -> index 6 -> index 4 -> index 1 -> index 3 \nExample 2:\nInput: arr = [4,2,3,0,3,1,2], start = 0\nOutput: true \nExplanation: \nOne possible way to reach at index 3 with value 0 is: \nindex 0 -> index 4 -> index 1 -> index 3\nExample 3:\nInput: arr = [3,0,2,1,2], start = 2\nOutput: false\nExplanation: There is no way to reach at index 1 with value 0.\n Constraints:\n1 <= arr.length <= 5 * 104\n0 <= arr[i] < arr.length\n0 <= start < arr.length" }, { "post_href": "https://leetcode.com/problems/verbal-arithmetic-puzzle/discuss/1216642/Python3-backtracking", "python_solutions": "class Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n if max(map(len, words)) > len(result): return False # edge case \n \n words.append(result)\n digits = [0]*10 \n mp = {} # mapping from letter to digit \n \n def fn(i, j, val): \n \"\"\"Find proper mapping for words[i][~j] and result[~j] via backtracking.\"\"\"\n if j == len(result): return val == 0 # base condition \n if i == len(words): return val % 10 == 0 and fn(0, j+1, val//10)\n \n if j >= len(words[i]): return fn(i+1, j, val)\n if words[i][~j] in mp: \n if j and j+1 == len(words[i]) and mp[words[i][~j]] == 0: return # backtrack (no leading 0)\n if i+1 == len(words): return fn(i+1, j, val - mp[words[i][~j]])\n else: return fn(i+1, j, val + mp[words[i][~j]])\n else: \n for k, x in enumerate(digits): \n if not x and (k or j == 0 or j+1 < len(words[i])): \n mp[words[i][~j]] = k\n digits[k] = 1\n if i+1 == len(words) and fn(i+1, j, val-k): return True \n if i+1 < len(words) and fn(i+1, j, val+k): return True \n digits[k] = 0\n mp.pop(words[i][~j])\n \n return fn(0, 0, 0)", "slug": "verbal-arithmetic-puzzle", "post_title": "[Python3] backtracking", "user": "ye15", "upvotes": 4, "views": 398, "problem_title": "verbal arithmetic puzzle", "number": 1307, "acceptance": 0.348, "difficulty": "Hard", "__index_level_0__": 19508, "question": "Given an equation, represented by words on the left side and the result on the right side.\nYou need to check if the equation is solvable under the following rules:\nEach character is decoded as one digit (0 - 9).\nNo two characters can map to the same digit.\nEach words[i] and result are decoded as one number without leading zeros.\nSum of numbers on the left side (words) will equal to the number on the right side (result).\nReturn true if the equation is solvable, otherwise return false.\n Example 1:\nInput: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\nOutput: true\nExplanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\nSuch that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652\nExample 2:\nInput: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\nOutput: true\nExplanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\nSuch that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214\nExample 3:\nInput: words = [\"LEET\",\"CODE\"], result = \"POINT\"\nOutput: false\nExplanation: There is no possible mapping to satisfy the equation, so we return false.\nNote that two different characters cannot map to the same digit.\n Constraints:\n2 <= words.length <= 5\n1 <= words[i].length, result.length <= 7\nwords[i], result contain only uppercase English letters.\nThe number of different characters used in the expression is at most 10." }, { "post_href": "https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping/discuss/470770/Python-3-(two-lines)-(beats-100)-(16-ms)-(With-Explanation)", "python_solutions": "class Solution:\n def freqAlphabets(self, s: str) -> str:\n for i in range(26,0,-1): s = s.replace(str(i)+'#'*(i>9),chr(96+i))\n return s\n \n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "decrypt-string-from-alphabet-to-integer-mapping", "post_title": "Python 3 (two lines) (beats 100%) (16 ms) (With Explanation)", "user": "junaidmansuri", "upvotes": 107, "views": 6100, "problem_title": "decrypt string from alphabet to integer mapping", "number": 1309, "acceptance": 0.795, "difficulty": "Easy", "__index_level_0__": 19511, "question": "You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:\nCharacters ('a' to 'i') are represented by ('1' to '9') respectively.\nCharacters ('j' to 'z') are represented by ('10#' to '26#') respectively.\nReturn the string formed after mapping.\nThe test cases are generated so that a unique mapping will always exist.\n Example 1:\nInput: s = \"10#11#12\"\nOutput: \"jkab\"\nExplanation: \"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".\nExample 2:\nInput: s = \"1326#\"\nOutput: \"acz\"\n Constraints:\n1 <= s.length <= 1000\ns consists of digits and the '#' letter.\ns will be a valid string such that mapping is always possible." }, { "post_href": "https://leetcode.com/problems/xor-queries-of-a-subarray/discuss/470834/Python-3-(two-lines)-(beats-100)-(412-ms)", "python_solutions": "class Solution:\n def xorQueries(self, A: List[int], Q: List[List[int]]) -> List[int]:\n B = [A[0]]\n for a in A[1:]: B.append(B[-1]^a)\n B.append(0)\n return [B[L-1]^B[R] for L,R in Q]", "slug": "xor-queries-of-a-subarray", "post_title": "Python 3 (two lines) (beats 100%) (412 ms)", "user": "junaidmansuri", "upvotes": 5, "views": 639, "problem_title": "xor queries of a subarray", "number": 1310, "acceptance": 0.722, "difficulty": "Medium", "__index_level_0__": 19550, "question": "You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].\nFor each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).\nReturn an array answer where answer[i] is the answer to the ith query.\n Example 1:\nInput: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\nOutput: [2,7,14,8] \nExplanation: \nThe binary representation of the elements in the array are:\n1 = 0001 \n3 = 0011 \n4 = 0100 \n8 = 1000 \nThe XOR values for queries are:\n[0,1] = 1 xor 3 = 2 \n[1,2] = 3 xor 4 = 7 \n[0,3] = 1 xor 3 xor 4 xor 8 = 14 \n[3,3] = 8\nExample 2:\nInput: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\nOutput: [8,0,4,4]\n Constraints:\n1 <= arr.length, queries.length <= 3 * 104\n1 <= arr[i] <= 109\nqueries[i].length == 2\n0 <= lefti <= righti < arr.length" }, { "post_href": "https://leetcode.com/problems/get-watched-videos-by-your-friends/discuss/491936/Python3-Breadth-first-search", "python_solutions": "class Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n queue = [id]\n count = 0\n seen = set(queue)\n while queue and count < level: #bfs\n count += 1\n temp = set()\n for i in queue: \n for j in friends[i]:\n if j not in seen: \n temp.add(j)\n seen.add(j)\n queue = temp\n \n movies = dict()\n for i in queue: \n for m in watchedVideos[i]: \n movies[m] = movies.get(m, 0) + 1\n return [k for _, k in sorted((v, k) for k, v in movies.items())]", "slug": "get-watched-videos-by-your-friends", "post_title": "[Python3] Breadth-first search", "user": "ye15", "upvotes": 2, "views": 322, "problem_title": "get watched videos by your friends", "number": 1311, "acceptance": 0.4589999999999999, "difficulty": "Medium", "__index_level_0__": 19563, "question": "There are n people, each person has a unique id between 0 and n-1. Given the arrays watchedVideos and friends, where watchedVideos[i] and friends[i] contain the list of watched videos and the list of friends respectively for the person with id = i.\nLevel 1 of videos are all watched videos by your friends, level 2 of videos are all watched videos by the friends of your friends and so on. In general, the level k of videos are all watched videos by people with the shortest path exactly equal to k with you. Given your id and the level of videos, return the list of videos ordered by their frequencies (increasing). For videos with the same frequency order them alphabetically from least to greatest. \n Example 1:\nInput: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\nOutput: [\"B\",\"C\"] \nExplanation: \nYou have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\nPerson with id = 1 -> watchedVideos = [\"C\"] \nPerson with id = 2 -> watchedVideos = [\"B\",\"C\"] \nThe frequencies of watchedVideos by your friends are: \nB -> 1 \nC -> 2\nExample 2:\nInput: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\nOutput: [\"D\"]\nExplanation: \nYou have id = 0 (green color in the figure) and the only friend of your friends is the person with id = 3 (yellow color in the figure).\n Constraints:\nn == watchedVideos.length == friends.length\n2 <= n <= 100\n1 <= watchedVideos[i].length <= 100\n1 <= watchedVideos[i][j].length <= 8\n0 <= friends[i].length < n\n0 <= friends[i][j] < n\n0 <= id < n\n1 <= level < n\nif friends[i] contains j, then friends[j] contains i" }, { "post_href": "https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/470856/Python-3-(four-lines)-(DP)-(LCS)", "python_solutions": "class Solution:\n def minInsertions(self, S: str) -> int:\n L = len(S)\n DP = [[0 for _ in range(L+1)] for _ in range(L+1)]\n for i,j in itertools.product(range(L),range(L)): DP[i+1][j+1] = DP[i][j] + 1 if S[i] == S[L-1-j] else max(DP[i][j+1],DP[i+1][j])\n return L - DP[-1][-1]\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "minimum-insertion-steps-to-make-a-string-palindrome", "post_title": "Python 3 (four lines) (DP) (LCS)", "user": "junaidmansuri", "upvotes": 2, "views": 537, "problem_title": "minimum insertion steps to make a string palindrome", "number": 1312, "acceptance": 0.657, "difficulty": "Hard", "__index_level_0__": 19570, "question": "Given a string s. In one step you can insert any character at any index of the string.\nReturn the minimum number of steps to make s palindrome.\nA Palindrome String is one that reads the same backward as well as forward.\n Example 1:\nInput: s = \"zzazz\"\nOutput: 0\nExplanation: The string \"zzazz\" is already palindrome we do not need any insertions.\nExample 2:\nInput: s = \"mbadm\"\nOutput: 2\nExplanation: String can be \"mbdadbm\" or \"mdbabdm\".\nExample 3:\nInput: s = \"leetcode\"\nOutput: 5\nExplanation: Inserting 5 characters the string becomes \"leetcodocteel\".\n Constraints:\n1 <= s.length <= 500\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/decompress-run-length-encoded-list/discuss/478426/Python-3-(one-line)-(beats-100)", "python_solutions": "class Solution:\n def decompressRLElist(self, N: List[int]) -> List[int]:\n L, A = len(N), []\n for i in range(0,L,2):\n A.extend(N[i]*[N[i+1]])\n return A", "slug": "decompress-run-length-encoded-list", "post_title": "Python 3 (one line) (beats 100%)", "user": "junaidmansuri", "upvotes": 23, "views": 3400, "problem_title": "decompress run length encoded list", "number": 1313, "acceptance": 0.8590000000000001, "difficulty": "Easy", "__index_level_0__": 19585, "question": "We are given a list nums of integers representing a list compressed with run-length encoding.\nConsider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list.\nReturn the decompressed list.\n Example 1:\nInput: nums = [1,2,3,4]\nOutput: [2,4,4,4]\nExplanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\nThe second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\nAt the end the concatenation [2] + [4,4,4] is [2,4,4,4].\nExample 2:\nInput: nums = [1,1,2,3]\nOutput: [1,3,3]\n Constraints:\n2 <= nums.length <= 100\nnums.length % 2 == 0\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/matrix-block-sum/discuss/711729/Python-DP-O(m*n)", "python_solutions": "class Solution:\n def matrixBlockSum(self, mat: List[List[int]], K: int) -> List[List[int]]:\n m, n = len(mat), len(mat[0])\n mat[:] = [[0] * (n + 1)] + [[0] + row for row in mat]\n res = [[0] * n for i in range(m)]\n\n for i in range(1, m + 1):\n for j in range(1, n + 1):\n mat[i][j] += mat[i - 1][j] + mat[i][j - 1] - mat[i - 1][j - 1]\n \n for i in range(m):\n for j in range(n):\n r1, r2 = max(i - K, 0), min(i + K + 1, m)\n c1, c2 = max(j - K, 0), min(j + K + 1, n)\n res[i][j] = mat[r2][c2] - mat[r2][c1] - mat[r1][c2] + mat[r1][c1]\n\n return res", "slug": "matrix-block-sum", "post_title": "Python DP O(m*n)", "user": "SWeszler", "upvotes": 8, "views": 1100, "problem_title": "matrix block sum", "number": 1314, "acceptance": 0.754, "difficulty": "Medium", "__index_level_0__": 19632, "question": "Given a m x n matrix mat and an integer k, return a matrix answer where each answer[i][j] is the sum of all elements mat[r][c] for:\ni - k <= r <= i + k,\nj - k <= c <= j + k, and\n(r, c) is a valid position in the matrix.\n Example 1:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\nOutput: [[12,21,16],[27,45,33],[24,39,28]]\nExample 2:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\nOutput: [[45,45,45],[45,45,45],[45,45,45]]\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n, k <= 100\n1 <= mat[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/discuss/514777/Python3-96ms-solution", "python_solutions": "class Solution:\n def __init__(self):\n self.summary = 0\n\n def sumEvenGrandparent(self, root: TreeNode) -> int:\n self.walk(root, False, False)\n return self.summary\n\n def walk(self, node: TreeNode, parent_even: bool, grand_parent_even: bool):\n if node is None:\n return\n if grand_parent_even:\n self.summary += node.val\n next_parent_even = True if node.val % 2 == 0 else False\n self.walk(node.left, next_parent_even, parent_even)\n self.walk(node.right, next_parent_even, parent_even)\n return", "slug": "sum-of-nodes-with-even-valued-grandparent", "post_title": "Python3 96ms solution", "user": "tjucoder", "upvotes": 7, "views": 740, "problem_title": "sum of nodes with even valued grandparent", "number": 1315, "acceptance": 0.856, "difficulty": "Medium", "__index_level_0__": 19650, "question": "Given the root of a binary tree, return the sum of values of nodes with an even-valued grandparent. If there are no nodes with an even-valued grandparent, return 0.\nA grandparent of a node is the parent of its parent if it exists.\n Example 1:\nInput: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\nOutput: 18\nExplanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.\nExample 2:\nInput: root = [1]\nOutput: 0\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n1 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/distinct-echo-substrings/discuss/1341886/Python-3-Rolling-hash-(5780ms)", "python_solutions": "class Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n n = len(text)\n\t\t\n def helper(size):\n base = 1 << 5\n M = 10 ** 9 + 7\n a = pow(base, size, M)\n t = 0\n vis = defaultdict(set)\n vis_pattern = set()\n ans = 0\n for i in range(n):\n t = (base * t + ord(text[i]) - ord('a')) % M\n if i >= size:\n t -= a * (ord(text[i - size]) - ord('a'))\n t %= M\n if t not in vis_pattern and (i - size * 2 + 1) in vis[t]:\n ans += 1\n vis_pattern.add(t)\n if i >= size - 1:\n vis[t].add(i - size + 1)\n return ans\n\n return sum(helper(size) for size in range(1, n//2+1))", "slug": "distinct-echo-substrings", "post_title": "[Python 3] Rolling hash (5780ms)", "user": "chestnut890123", "upvotes": 2, "views": 203, "problem_title": "distinct echo substrings", "number": 1316, "acceptance": 0.497, "difficulty": "Hard", "__index_level_0__": 19672, "question": "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 Example 1:\nInput: text = \"abcabcabc\"\nOutput: 3\nExplanation: The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".\nExample 2:\nInput: text = \"leetcodeleetcode\"\nOutput: 2\nExplanation: The 2 substrings are \"ee\" and \"leetcodeleetcode\".\n Constraints:\n1 <= text.length <= 2000\ntext has only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/convert-integer-to-the-sum-of-two-no-zero-integers/discuss/1219360/Python-Fast-and-Easy-Soln", "python_solutions": "class Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n left = 0\n right = n\n ans = []\n while True:\n if str(left).count(\"0\")==0 and str(right).count(\"0\")==0:\n ans.append(left)\n ans.append(right)\n break\n left+=1\n right-=1\n return ans", "slug": "convert-integer-to-the-sum-of-two-no-zero-integers", "post_title": "Python Fast & Easy Soln", "user": "iamkshitij77", "upvotes": 2, "views": 212, "problem_title": "convert integer to the sum of two no zero integers", "number": 1317, "acceptance": 0.56, "difficulty": "Easy", "__index_level_0__": 19676, "question": "No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.\nGiven an integer n, return a list of two integers [a, b] where:\na and b are No-Zero integers.\na + b = n\nThe test cases are generated so that there is at least one valid solution. If there are many valid solutions, you can return any of them.\n Example 1:\nInput: n = 2\nOutput: [1,1]\nExplanation: Let a = 1 and b = 1.\nBoth a and b are no-zero integers, and a + b = 2 = n.\nExample 2:\nInput: n = 11\nOutput: [2,9]\nExplanation: Let a = 2 and b = 9.\nBoth a and b are no-zero integers, and a + b = 9 = n.\nNote that there are other valid answers as [8, 3] that can be accepted.\n Constraints:\n2 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/489623/Python-Simple-Solution-Python-Memory-usage-less-than-100", "python_solutions": "class Solution:\n def minFlips(self, a: int, b: int, c: int) -> int: \n count = 0\n while a or b or c:\n if (a & 1) | (b & 1) != (c & 1):\n if (c & 1): count += 1\n else: count += (a & 1) + (b & 1)\n a, b, c = a >> 1, b >> 1, c >> 1\n return count", "slug": "minimum-flips-to-make-a-or-b-equal-to-c", "post_title": "Python - Simple Solution - Python - Memory usage less than 100%", "user": "mmbhatk", "upvotes": 5, "views": 339, "problem_title": "minimum flips to make a or b equal to c", "number": 1318, "acceptance": 0.66, "difficulty": "Medium", "__index_level_0__": 19692, "question": "Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).\nFlip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.\n Example 1:\nInput: a = 2, b = 6, c = 5\nOutput: 3\nExplanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)\nExample 2:\nInput: a = 4, b = 2, c = 7\nOutput: 1\nExample 3:\nInput: a = 1, b = 2, c = 3\nOutput: 0\n Constraints:\n1 <= a <= 10^9\n1 <= b <= 10^9\n1 <= c <= 10^9" }, { "post_href": "https://leetcode.com/problems/number-of-operations-to-make-network-connected/discuss/2420269/Operations-to-make-network-connected-oror-Python3-oror-Union-Find", "python_solutions": "class Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n self.components = n\n # We need atleast n-1 connections to connect n networks\n if(len(connections) < n-1):\n return -1\n # If we have n-1 connections, we only need to count to number of components\n # Union-Find \n \n parent = [i for i in range(0, n)]\n rank = [0] * n\n for x, y in connections:\n self.union(x, y, parent, rank)\n # we require no. of components - 1 edge to connect n components\n return self.components - 1 \n \n def find(self, x, parent):\n if(parent[x] != x):\n parent[x] = self.find(parent[x], parent)\n return parent[x]\n \n def union(self, x, y, parent, rank):\n parent_x = self.find(x, parent)\n parent_y = self.find(y, parent)\n \n if(parent_x == parent_y):\n return\n rank_x = rank[parent_x]\n rank_y = rank[parent_y]\n \n if(rank_x > rank_y):\n parent[parent_y] = parent_x\n elif(rank_x < rank_y):\n parent[parent_x] = parent_y\n else:\n parent[parent_y] = parent_x\n rank[parent_x] += 1\n self.components -= 1", "slug": "number-of-operations-to-make-network-connected", "post_title": "Operations to make network connected || Python3 || Union-Find", "user": "vanshika_2507", "upvotes": 1, "views": 30, "problem_title": "number of operations to make network connected", "number": 1319, "acceptance": 0.585, "difficulty": "Medium", "__index_level_0__": 19707, "question": "There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.\nYou are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.\nReturn the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.\n Example 1:\nInput: n = 4, connections = [[0,1],[0,2],[1,2]]\nOutput: 1\nExplanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.\nExample 2:\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\nOutput: 2\nExample 3:\nInput: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\nOutput: -1\nExplanation: There are not enough cables.\n Constraints:\n1 <= n <= 105\n1 <= connections.length <= min(n * (n - 1) / 2, 105)\nconnections[i].length == 2\n0 <= ai, bi < n\nai != bi\nThere are no repeated connections.\nNo two computers are connected by more than one cable." }, { "post_href": "https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/1509241/Well-Coded-oror-Clean-and-Concise-oror-93-faster", "python_solutions": "class Solution:\ndef minimumDistance(self, word: str) -> int:\n def dist(pre,cur):\n if pre==None:\n return 0\n x1,y1 = divmod(ord(pre)-ord('A'),6)\n x2,y2 = divmod(ord(cur)-ord('A'),6)\n return abs(x1-x2) + abs(y1-y2)\n \n @lru_cache(None)\n def fingers(i,l,r):\n if i == len(word):\n return 0\n n1 = dist(l,word[i]) + fingers(i+1,word[i],r)\n n2 = dist(r,word[i]) + fingers(i+1,l,word[i])\n return min(n1,n2)\n \n return fingers(0,None,None)", "slug": "minimum-distance-to-type-a-word-using-two-fingers", "post_title": "\ud83d\udccc\ud83d\udccc Well-Coded || Clean & Concise || 93% faster \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 2, "views": 228, "problem_title": "minimum distance to type a word using two fingers", "number": 1320, "acceptance": 0.597, "difficulty": "Hard", "__index_level_0__": 19720, "question": "You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.\nFor 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).\nGiven the string word, return the minimum total distance to type such string using only two fingers.\nThe distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.\nNote that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.\n Example 1:\nInput: word = \"CAKE\"\nOutput: 3\nExplanation: Using two fingers, one optimal way to type \"CAKE\" is: \nFinger 1 on letter 'C' -> cost = 0 \nFinger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \nFinger 2 on letter 'K' -> cost = 0 \nFinger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \nTotal distance = 3\nExample 2:\nInput: word = \"HAPPY\"\nOutput: 6\nExplanation: Using two fingers, one optimal way to type \"HAPPY\" is:\nFinger 1 on letter 'H' -> cost = 0\nFinger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\nFinger 2 on letter 'P' -> cost = 0\nFinger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\nFinger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\nTotal distance = 6\n Constraints:\n2 <= word.length <= 300\nword consists of uppercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-69-number/discuss/2787125/PYTHON-oror-EASY-TO-UNDERSTAND-oror-WELL-EXPLAINED", "python_solutions": "class Solution:\n def maximum69Number (self, nums: int) -> int:\n nums = str(nums) #changing integer to string\n j = 1 #maximum number you can change atmost\n for i in range(len(nums)):\n if nums[i] == \"6\" and (j == 1): #checking if the element is \"6\" and we are change only once\n bef = nums[:i] #stored element before the element 6 using slicing\n aft = nums[i+1:] #stored element after the element 6 using slicing\n nums = bef + \"9\"+aft #adding element in place of 6\n j-=1 # we will reduct 1. so that above condition cant satisfy again.\n nums = int(nums)\n return nums", "slug": "maximum-69-number", "post_title": "PYTHON || EASY TO UNDERSTAND || WELL EXPLAINED", "user": "thesunnysinha", "upvotes": 5, "views": 372, "problem_title": "maximum 69 number", "number": 1323, "acceptance": 0.821, "difficulty": "Easy", "__index_level_0__": 19724, "question": "You are given a positive integer num consisting only of digits 6 and 9.\nReturn the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).\n Example 1:\nInput: num = 9669\nOutput: 9969\nExplanation: \nChanging the first digit results in 6669.\nChanging the second digit results in 9969.\nChanging the third digit results in 9699.\nChanging the fourth digit results in 9666.\nThe maximum number is 9969.\nExample 2:\nInput: num = 9996\nOutput: 9999\nExplanation: Changing the last digit 6 to 9 results in the maximum number.\nExample 3:\nInput: num = 9999\nOutput: 9999\nExplanation: It is better not to apply any change.\n Constraints:\n1 <= num <= 104\nnum consists of only 6 and 9 digits." }, { "post_href": "https://leetcode.com/problems/print-words-vertically/discuss/1277233/python-94.44-or-easy-or-with-comments", "python_solutions": "class Solution:\n def printVertically(self, s: str) -> List[str]:\n \n \n st=0 # track of index to take element from each word \n s=s.split()\n ans=[]\n y=0\n for i in s:\n y=max(y,len(i))\n \n while st TreeNode:\n def RLN(R):\n if R == None: return None\n R.left, R.right = RLN(R.left), RLN(R.right)\n return None if R.val == t and R.left == R.right else R\n return RLN(R)\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "delete-leaves-with-a-given-value", "post_title": "Python 3 (beats 100%) (five lines) (recursive)", "user": "junaidmansuri", "upvotes": 2, "views": 302, "problem_title": "delete leaves with a given value", "number": 1325, "acceptance": 0.747, "difficulty": "Medium", "__index_level_0__": 19806, "question": "Given a binary tree root and an integer target, delete all the leaf nodes with value target.\nNote that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot).\n Example 1:\nInput: root = [1,2,3,2,null,2,4], target = 2\nOutput: [1,null,3,null,4]\nExplanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). \nAfter removing, new nodes become leaf nodes with value (target = 2) (Picture in center).\nExample 2:\nInput: root = [1,3,3,3,2], target = 3\nOutput: [1,3,null,null,2]\nExample 3:\nInput: root = [1,2,null,2,null,2], target = 2\nOutput: [1]\nExplanation: Leaf nodes in green with value (target = 2) are removed at each step.\n Constraints:\nThe number of nodes in the tree is in the range [1, 3000].\n1 <= Node.val, target <= 1000" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/discuss/484299/Python-%3A-O(N)", "python_solutions": "class Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n jumps = [0]*(n+1)\n for i in range(n+1):\n l, r = max(0,i-ranges[i]), min(n,i+ranges[i])\n jumps[l] = max(jumps[l],r-l)\n step = start = end = 0\n while end < n:\n start, end = end+1, max(i+jumps[i] for i in range(start, end+1))\n if start > end:\n return -1\n step += 1\n return step", "slug": "minimum-number-of-taps-to-open-to-water-a-garden", "post_title": "Python : O(N)", "user": "fallenranger", "upvotes": 22, "views": 2500, "problem_title": "minimum number of taps to open to water a garden", "number": 1326, "acceptance": 0.477, "difficulty": "Hard", "__index_level_0__": 19825, "question": "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).\nThere are n + 1 taps located at points [0, 1, ..., n] in the garden.\nGiven an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.\nReturn the minimum number of taps that should be open to water the whole garden, If the garden cannot be watered return -1.\n Example 1:\nInput: n = 5, ranges = [3,4,1,1,0,0]\nOutput: 1\nExplanation: The tap at point 0 can cover the interval [-3,3]\nThe tap at point 1 can cover the interval [-3,5]\nThe tap at point 2 can cover the interval [1,3]\nThe tap at point 3 can cover the interval [2,4]\nThe tap at point 4 can cover the interval [4,4]\nThe tap at point 5 can cover the interval [5,5]\nOpening Only the second tap will water the whole garden [0,5]\nExample 2:\nInput: n = 3, ranges = [0,0,0,0]\nOutput: -1\nExplanation: Even if you activate all the four taps you cannot water the whole garden.\n Constraints:\n1 <= n <= 104\nranges.length == n + 1\n0 <= ranges[i] <= 100" }, { "post_href": "https://leetcode.com/problems/break-a-palindrome/discuss/846873/Python-3-or-Greedy-one-pass-or-Explanations", "python_solutions": "class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n n = len(palindrome)\n if n == 1: return ''\n for i, c in enumerate(palindrome):\n if c != 'a' and ((i != n // 2 and n % 2) or not n % 2): return palindrome[:i] + 'a' + palindrome[i+1:] \n else: return palindrome[:-1] + 'b'", "slug": "break-a-palindrome", "post_title": "Python 3 | Greedy one pass | Explanations", "user": "idontknoooo", "upvotes": 7, "views": 1300, "problem_title": "break a palindrome", "number": 1328, "acceptance": 0.531, "difficulty": "Medium", "__index_level_0__": 19838, "question": "Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.\nReturn the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, \"abcc\" is lexicographically smaller than \"abcd\" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.\n Example 1:\nInput: palindrome = \"abccba\"\nOutput: \"aaccba\"\nExplanation: There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\nOf all the ways, \"aaccba\" is the lexicographically smallest.\nExample 2:\nInput: palindrome = \"a\"\nOutput: \"\"\nExplanation: There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.\n Constraints:\n1 <= palindrome.length <= 1000\npalindrome consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/sort-the-matrix-diagonally/discuss/920657/Python3-simple-solution", "python_solutions": "class Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n \n \n d = defaultdict(list)\n \n for i in range(len(mat)):\n for j in range(len(mat[0])):\n d[i-j].append(mat[i][j])\n \n for k in d.keys():\n d[k].sort()\n \n for i in range(len(mat)):\n for j in range(len(mat[0])):\n mat[i][j] = d[i-j].pop(0)\n return mat", "slug": "sort-the-matrix-diagonally", "post_title": "Python3 simple solution", "user": "ermolushka2", "upvotes": 8, "views": 463, "problem_title": "sort the matrix diagonally", "number": 1329, "acceptance": 0.836, "difficulty": "Medium", "__index_level_0__": 19889, "question": "A matrix diagonal is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the matrix diagonal starting from mat[2][0], where mat is a 6 x 3 matrix, includes cells mat[2][0], mat[3][1], and mat[4][2].\nGiven an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.\n Example 1:\nInput: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\nOutput: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\nExample 2:\nInput: mat = [[11,25,66,1,69,7],[23,55,17,45,15,52],[75,31,36,44,58,8],[22,27,33,25,68,4],[84,28,14,11,5,50]]\nOutput: [[5,17,4,1,52,7],[11,11,25,45,8,69],[14,23,25,44,58,15],[22,27,31,36,50,66],[84,28,75,33,55,68]]\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 100\n1 <= mat[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/discuss/489882/O(n)-Solution-with-explanation", "python_solutions": "class Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n maxi, mini = -math.inf, math.inf\n \n for a, b in zip(nums, nums[1:]):\n maxi = max(min(a, b), maxi)\n mini = min(max(a, b), mini)\n change = max(0, (maxi - mini) * 2)\n \n # solving the boundary situation\n for a, b in zip(nums, nums[1:]):\n tmp1 = - abs(a - b) + abs(nums[0] - b)\n tmp2 = - abs(a - b) + abs(nums[-1] - a)\n change = max([tmp1, tmp2, change])\n\t\t\t\n original_value = sum(abs(a - b) for a, b in zip(nums, nums[1:]))\n return original_value + change", "slug": "reverse-subarray-to-maximize-array-value", "post_title": "O(n) Solution with explanation", "user": "neal99", "upvotes": 325, "views": 7300, "problem_title": "reverse subarray to maximize array value", "number": 1330, "acceptance": 0.401, "difficulty": "Hard", "__index_level_0__": 19929, "question": "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.\nYou are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\nFind maximum possible value of the final array.\n Example 1:\nInput: nums = [2,3,1,5,4]\nOutput: 10\nExplanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\nExample 2:\nInput: nums = [2,4,9,24,2,1,10]\nOutput: 68\n Constraints:\n1 <= nums.length <= 3 * 104\n-105 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/rank-transform-of-an-array/discuss/2421511/Python-Elegant-and-Short-or-Two-lines-or-HashMap-%2B-Sorting", "python_solutions": "class Solution:\n\t\"\"\"\n\tTime: O(n*log(n))\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef arrayRankTransform(self, arr: List[int]) -> List[int]:\n\t\tranks = {num: r for r, num in enumerate(sorted(set(arr)), start=1)}\n\t\treturn [ranks[num] for num in arr]", "slug": "rank-transform-of-an-array", "post_title": "Python Elegant & Short | Two lines | HashMap + Sorting", "user": "Kyrylo-Ktl", "upvotes": 2, "views": 220, "problem_title": "rank transform of an array", "number": 1331, "acceptance": 0.591, "difficulty": "Easy", "__index_level_0__": 19930, "question": "Given an array of integers arr, replace each element with its rank.\nThe rank represents how large the element is. The rank has the following rules:\nRank is an integer starting from 1.\nThe larger the element, the larger the rank. If two elements are equal, their rank must be the same.\nRank should be as small as possible.\n Example 1:\nInput: arr = [40,10,20,30]\nOutput: [4,1,2,3]\nExplanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.\nExample 2:\nInput: arr = [100,100,100]\nOutput: [1,1,1]\nExplanation: Same elements share the same rank.\nExample 3:\nInput: arr = [37,12,28,9,100,56,80,5,12]\nOutput: [5,3,4,2,8,6,7,1,3]\n Constraints:\n0 <= arr.length <= 105\n-109 <= arr[i] <= 109" }, { "post_href": "https://leetcode.com/problems/remove-palindromic-subsequences/discuss/2124192/Python-oror-2-Easy-oror-One-liner", "python_solutions": "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n return 1 if s == s[::-1] else 2", "slug": "remove-palindromic-subsequences", "post_title": "\u2705 Python || 2 Easy || One liner", "user": "constantine786", "upvotes": 45, "views": 3500, "problem_title": "remove palindromic subsequences", "number": 1332, "acceptance": 0.7609999999999999, "difficulty": "Easy", "__index_level_0__": 19954, "question": "You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.\nReturn the minimum number of steps to make the given string empty.\nA string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.\nA string is called palindrome if is one that reads the same backward as well as forward.\n Example 1:\nInput: s = \"ababa\"\nOutput: 1\nExplanation: s is already a palindrome, so its entirety can be removed in a single step.\nExample 2:\nInput: s = \"abb\"\nOutput: 2\nExplanation: \"abb\" -> \"bb\" -> \"\". \nRemove palindromic subsequence \"a\" then \"bb\".\nExample 3:\nInput: s = \"baabb\"\nOutput: 2\nExplanation: \"baabb\" -> \"b\" -> \"\". \nRemove palindromic subsequence \"baab\" then \"b\".\n Constraints:\n1 <= s.length <= 1000\ns[i] is either 'a' or 'b'." }, { "post_href": "https://leetcode.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance/discuss/1464395/Python3-solution", "python_solutions": "class Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n def f(x):\n if (veganFriendly == 1 and x[2] == 1 and x[3] <= maxPrice and x[4] <= maxDistance) or (veganFriendly == 0 and x[3] <= maxPrice and x[4] <= maxDistance):\n return True\n else:\n return False\n y = list(filter(f,restaurants))\n y.sort(key=lambda a:a[0],reverse=True)\n y.sort(key=lambda a:a[1],reverse=True)\n return [i[0] for i in y]", "slug": "filter-restaurants-by-vegan-friendly-price-and-distance", "post_title": "Python3 solution", "user": "EklavyaJoshi", "upvotes": 3, "views": 242, "problem_title": "filter restaurants by vegan friendly, price and distance", "number": 1333, "acceptance": 0.596, "difficulty": "Medium", "__index_level_0__": 19992, "question": "Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.\nThe veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.\nReturn the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.\n Example 1:\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10\nOutput: [3,1,5] \nExplanation: \nThe restaurants are:\nRestaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\nRestaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\nRestaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\nRestaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\nRestaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \nAfter filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). \nExample 2:\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10\nOutput: [4,3,2,1,5]\nExplanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.\nExample 3:\nInput: restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3\nOutput: [4,5]\n Constraints:\n1 <= restaurants.length <= 10^4\nrestaurants[i].length == 5\n1 <= idi, ratingi, pricei, distancei <= 10^5\n1 <= maxPrice, maxDistance <= 10^5\nveganFriendlyi and veganFriendly are 0 or 1.\nAll idi are distinct." }, { "post_href": "https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/discuss/491784/Python3-Floyd-Warshall-algo", "python_solutions": "class Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n \"\"\"Floyd-Warshall algorithm\"\"\"\n dist = [[float(\"inf\")]*n for _ in range(n)]\n for i in range(n): dist[i][i] = 0\n for i, j, w in edges: dist[i][j] = dist[j][i] = w\n \n for k in range(n):\n for i in range(n):\n for j in range(n):\n dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])\n \n ans = {sum(d <= distanceThreshold for d in dist[i]): i for i in range(n)}\n return ans[min(ans)]", "slug": "find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance", "post_title": "[Python3] Floyd-Warshall algo", "user": "ye15", "upvotes": 2, "views": 98, "problem_title": "find the city with the smallest number of neighbors at a threshold distance", "number": 1334, "acceptance": 0.5329999999999999, "difficulty": "Medium", "__index_level_0__": 20000, "question": "There are n cities numbered from 0 to n-1. Given the array edges where edges[i] = [fromi, toi, weighti] represents a bidirectional and weighted edge between cities fromi and toi, and given the integer distanceThreshold.\nReturn the city with the smallest number of cities that are reachable through some path and whose distance is at most distanceThreshold, If there are multiple such cities, return the city with the greatest number.\nNotice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.\n Example 1:\nInput: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\nOutput: 3\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 4 for each city are:\nCity 0 -> [City 1, City 2] \nCity 1 -> [City 0, City 2, City 3] \nCity 2 -> [City 0, City 1, City 3] \nCity 3 -> [City 1, City 2] \nCities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.\nExample 2:\nInput: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\nOutput: 0\nExplanation: The figure above describes the graph. \nThe neighboring cities at a distanceThreshold = 2 for each city are:\nCity 0 -> [City 1] \nCity 1 -> [City 0, City 4] \nCity 2 -> [City 3, City 4] \nCity 3 -> [City 2, City 4]\nCity 4 -> [City 1, City 2, City 3] \nThe city 0 has 1 neighboring city at a distanceThreshold = 2.\n Constraints:\n2 <= n <= 100\n1 <= edges.length <= n * (n - 1) / 2\nedges[i].length == 3\n0 <= fromi < toi < n\n1 <= weighti, distanceThreshold <= 10^4\nAll pairs (fromi, toi) are distinct." }, { "post_href": "https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/discuss/2709132/91-Faster-Solution", "python_solutions": "class Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n jobCount = len(jobDifficulty) \n if jobCount < d:\n return -1\n\n @lru_cache(None)\n def topDown(jobIndex: int, remainDayCount: int) -> int:\n remainJobCount = jobCount - jobIndex\n if remainDayCount == 1:\n return max(jobDifficulty[jobIndex:])\n \n if remainJobCount == remainDayCount:\n return sum(jobDifficulty[jobIndex:])\n\n minDiff = float('inf')\n maxToday = 0\n for i in range(jobIndex, jobCount - remainDayCount + 1):\n maxToday = max(maxToday, jobDifficulty[i])\n minDiff = min(minDiff, maxToday + topDown(i+1, remainDayCount-1))\n return minDiff\n\n return topDown(0, d)", "slug": "minimum-difficulty-of-a-job-schedule", "post_title": "91% Faster Solution", "user": "namanxk", "upvotes": 4, "views": 485, "problem_title": "minimum difficulty of a job schedule", "number": 1335, "acceptance": 0.5870000000000001, "difficulty": "Hard", "__index_level_0__": 20011, "question": "You want to schedule a list of jobs in d days. Jobs are dependent (i.e To work on the ith job, you have to finish all the jobs j where 0 <= j < i).\nYou have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.\nYou are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].\nReturn the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.\n Example 1:\nInput: jobDifficulty = [6,5,4,3,2,1], d = 2\nOutput: 7\nExplanation: First day you can finish the first 5 jobs, total difficulty = 6.\nSecond day you can finish the last job, total difficulty = 1.\nThe difficulty of the schedule = 6 + 1 = 7 \nExample 2:\nInput: jobDifficulty = [9,9,9], d = 4\nOutput: -1\nExplanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\nExample 3:\nInput: jobDifficulty = [1,1,1], d = 3\nOutput: 3\nExplanation: The schedule is one job per day. total difficulty will be 3.\n Constraints:\n1 <= jobDifficulty.length <= 300\n0 <= jobDifficulty[i] <= 1000\n1 <= d <= 10" }, { "post_href": "https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/discuss/1201679/C%2B%2B-Python3-No-Heap-No-BS-Simple-Sort-99.20", "python_solutions": "class Solution:\n\tdef kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n\t\tm = len(mat)\n\t\trows = sorted(range(m), key=lambda i: (mat[i], i))\n\t\tdel rows[k:]\n\t\treturn rows", "slug": "the-k-weakest-rows-in-a-matrix", "post_title": "[C++, Python3] No Heap, No BS, Simple Sort 99.20%", "user": "mycoding1729", "upvotes": 163, "views": 6300, "problem_title": "the k weakest rows in a matrix", "number": 1337, "acceptance": 0.728, "difficulty": "Easy", "__index_level_0__": 20040, "question": "You are given an m x n binary matrix mat of 1's (representing soldiers) and 0's (representing civilians). The soldiers are positioned in front of the civilians. That is, all the 1's will appear to the left of all the 0's in each row.\nA row i is weaker than a row j if one of the following is true:\nThe number of soldiers in row i is less than the number of soldiers in row j.\nBoth rows have the same number of soldiers and i < j.\nReturn the indices of the k weakest rows in the matrix ordered from weakest to strongest.\n Example 1:\nInput: mat = \n[[1,1,0,0,0],\n [1,1,1,1,0],\n [1,0,0,0,0],\n [1,1,0,0,0],\n [1,1,1,1,1]], \nk = 3\nOutput: [2,0,3]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 2 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 2 \n- Row 4: 5 \nThe rows ordered from weakest to strongest are [2,0,3,1,4].\nExample 2:\nInput: mat = \n[[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \nk = 2\nOutput: [0,2]\nExplanation: \nThe number of soldiers in each row is: \n- Row 0: 1 \n- Row 1: 4 \n- Row 2: 1 \n- Row 3: 1 \nThe rows ordered from weakest to strongest are [0,2,3,1].\n Constraints:\nm == mat.length\nn == mat[i].length\n2 <= n, m <= 100\n1 <= k <= m\nmatrix[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/reduce-array-size-to-the-half/discuss/2443490/Easy-to-understand-or-C%2B%2B-or-PYTHON-or", "python_solutions": "class Solution:\n def minSetSize(self, arr: List[int]) -> int:\n freq = Counter(arr);\n f = [];\n for val in freq.values():\n f.append(val);\n f.sort(reverse=True)\n ans = 0;\n n = 0;\n while(len(arr)//2>n):\n n += f[ans];\n ans += 1;\n return ans;", "slug": "reduce-array-size-to-the-half", "post_title": "Easy to understand | C++ | PYTHON |", "user": "dharmeshkporiya", "upvotes": 3, "views": 43, "problem_title": "reduce array size to the half", "number": 1338, "acceptance": 0.6970000000000001, "difficulty": "Medium", "__index_level_0__": 20090, "question": "You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.\nReturn the minimum size of the set so that at least half of the integers of the array are removed.\n Example 1:\nInput: arr = [3,3,3,3,5,5,5,2,2,7]\nOutput: 2\nExplanation: Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).\nPossible sets of size 2 are {3,5},{3,2},{5,2}.\nChoosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.\nExample 2:\nInput: arr = [7,7,7,7,7,7]\nOutput: 1\nExplanation: The only possible set you can choose is {7}. This will make the new array empty.\n Constraints:\n2 <= arr.length <= 105\narr.length is even.\n1 <= arr[i] <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/discuss/496700/Python3-post-order-dfs", "python_solutions": "class Solution:\n def maxProduct(self, root: Optional[TreeNode]) -> int:\n vals = []\n \n def fn(node): \n \"\"\"Return sum of sub-tree.\"\"\"\n if not node: return 0 \n ans = node.val + fn(node.left) + fn(node.right)\n vals.append(ans)\n return ans\n \n total = fn(root)\n return max((total-x)*x for x in vals) % 1_000_000_007", "slug": "maximum-product-of-splitted-binary-tree", "post_title": "[Python3] post-order dfs", "user": "ye15", "upvotes": 39, "views": 1500, "problem_title": "maximum product of splitted binary tree", "number": 1339, "acceptance": 0.434, "difficulty": "Medium", "__index_level_0__": 20130, "question": "Given the root of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.\nReturn the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.\nNote that you need to maximize the answer before taking the mod and not after taking it.\n Example 1:\nInput: root = [1,2,3,4,5,6]\nOutput: 110\nExplanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\nExample 2:\nInput: root = [1,null,2,3,4,null,null,5,6]\nOutput: 90\nExplanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n Constraints:\nThe number of nodes in the tree is in the range [2, 5 * 104].\n1 <= Node.val <= 104" }, { "post_href": "https://leetcode.com/problems/jump-game-v/discuss/1670065/Well-Coded-and-Easy-Explanation-oror-Use-of-Memoization", "python_solutions": "class Solution:\n\tdef maxJumps(self, arr: List[int], d: int) -> int:\n\n\t\tdp = defaultdict(int)\n\t\tdef dfs(i):\n\t\t\tif i in dp: return dp[i]\n\t\t\tm_path = 0\n\t\t\tfor j in range(i+1,i+d+1):\n\t\t\t\tif j>=len(arr) or arr[j]>=arr[i]: break\n\t\t\t\tm_path = max(m_path,dfs(j))\n\n\t\t\tfor j in range(i-1,i-d-1,-1):\n\t\t\t\tif j<0 or arr[j]>=arr[i]: break\n\t\t\t\tm_path = max(m_path,dfs(j))\n\t\t\tdp[i] = m_path+1\n\t\t\treturn m_path+1\n\n\t\tres = 0\n\t\tfor i in range(len(arr)):\n\t\t\tres = max(res,dfs(i))\n\t\treturn res", "slug": "jump-game-v", "post_title": "\ud83d\udccc\ud83d\udccc Well-Coded and Easy Explanation || Use of Memoization \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 5, "views": 173, "problem_title": "jump game v", "number": 1340, "acceptance": 0.625, "difficulty": "Hard", "__index_level_0__": 20147, "question": "Given an array of integers arr and an integer d. In one step you can jump from index i to index:\ni + x where: i + x < arr.length and 0 < x <= d.\ni - x where: i - x >= 0 and 0 < x <= d.\nIn addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).\nYou can choose any index of the array and start jumping. Return the maximum number of indices you can visit.\nNotice that you can not jump outside of the array at any time.\n Example 1:\nInput: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\nOutput: 4\nExplanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\nNote that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\nSimilarly You cannot jump from index 3 to index 2 or index 1.\nExample 2:\nInput: arr = [3,3,3,3,3], d = 3\nOutput: 1\nExplanation: You can start at any index. You always cannot jump to any index.\nExample 3:\nInput: arr = [7,6,5,4,3,2,1], d = 1\nOutput: 7\nExplanation: Start at index 0. You can visit all the indicies. \n Constraints:\n1 <= arr.length <= 1000\n1 <= arr[i] <= 105\n1 <= d <= arr.length" }, { "post_href": "https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/discuss/2738381/Python-Elegant-and-Short-or-O(1)-or-Recursive-Iterative-Bit-Manipulation", "python_solutions": "class Solution:\n \"\"\"\n Time: O(log(n))\n Memory: O(log(n))\n \"\"\"\n\n def numberOfSteps(self, num: int) -> int:\n if num == 0:\n return 0\n return 1 + self.numberOfSteps(num - 1 if num & 1 else num >> 1)", "slug": "number-of-steps-to-reduce-a-number-to-zero", "post_title": "Python Elegant & Short | O(1) | Recursive / Iterative / Bit Manipulation", "user": "Kyrylo-Ktl", "upvotes": 28, "views": 1300, "problem_title": "number of steps to reduce a number to zero", "number": 1342, "acceptance": 0.8540000000000001, "difficulty": "Easy", "__index_level_0__": 20151, "question": "Given an integer num, return the number of steps to reduce it to zero.\nIn one step, if the current number is even, you have to divide it by 2, otherwise, you have to subtract 1 from it.\n Example 1:\nInput: num = 14\nOutput: 6\nExplanation: \nStep 1) 14 is even; divide by 2 and obtain 7. \nStep 2) 7 is odd; subtract 1 and obtain 6.\nStep 3) 6 is even; divide by 2 and obtain 3. \nStep 4) 3 is odd; subtract 1 and obtain 2. \nStep 5) 2 is even; divide by 2 and obtain 1. \nStep 6) 1 is odd; subtract 1 and obtain 0.\nExample 2:\nInput: num = 8\nOutput: 4\nExplanation: \nStep 1) 8 is even; divide by 2 and obtain 4. \nStep 2) 4 is even; divide by 2 and obtain 2. \nStep 3) 2 is even; divide by 2 and obtain 1. \nStep 4) 1 is odd; subtract 1 and obtain 0.\nExample 3:\nInput: num = 123\nOutput: 12\n Constraints:\n0 <= num <= 106" }, { "post_href": "https://leetcode.com/problems/number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/discuss/1816745/Python-Solution-oror-Sliding-Window", "python_solutions": "class Solution:\n def numOfSubarrays(self, arr, k, threshold):\n windowStart = 0\n max_avg = 0\n avg = 0\n c=0\n result = []\n windowSum = 0\n for windowEnd in range(len(arr)):\n windowSum += arr[windowEnd]\n if((windowEnd)>=k-1):\n avg = windowSum//k\n result.append(avg)\n windowSum -= arr[windowStart]\n windowStart += 1\n for i in range(len(result)):\n if(result[i]>=threshold):\n c=c+1\n return c", "slug": "number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold", "post_title": "Python Solution || Sliding Window", "user": "aashutoshjha21022002", "upvotes": 3, "views": 281, "problem_title": "number of sub arrays of size k and average greater than or equal to threshold", "number": 1343, "acceptance": 0.6759999999999999, "difficulty": "Medium", "__index_level_0__": 20207, "question": "Given an array of integers arr and two integers k and threshold, return the number of sub-arrays of size k and average greater than or equal to threshold.\n Example 1:\nInput: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\nOutput: 3\nExplanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).\nExample 2:\nInput: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\nOutput: 6\nExplanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.\n Constraints:\n1 <= arr.length <= 105\n1 <= arr[i] <= 104\n1 <= k <= arr.length\n0 <= threshold <= 104" }, { "post_href": "https://leetcode.com/problems/angle-between-hands-of-a-clock/discuss/1911342/Python-one-line-solution-based-on-aptitude-formula", "python_solutions": "class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n return min(abs(30*hour-5.5*minutes),360-abs(30*hour-5.5*minutes))", "slug": "angle-between-hands-of-a-clock", "post_title": "Python one line solution based on aptitude formula", "user": "amannarayansingh10", "upvotes": 2, "views": 49, "problem_title": "angle between hands of a clock", "number": 1344, "acceptance": 0.634, "difficulty": "Medium", "__index_level_0__": 20227, "question": "Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.\nAnswers within 10-5 of the actual value will be accepted as correct.\n Example 1:\nInput: hour = 12, minutes = 30\nOutput: 165\nExample 2:\nInput: hour = 3, minutes = 30\nOutput: 75\nExample 3:\nInput: hour = 3, minutes = 15\nOutput: 7.5\n Constraints:\n1 <= hour <= 12\n0 <= minutes <= 59" }, { "post_href": "https://leetcode.com/problems/jump-game-iv/discuss/1691093/Python3-RECURSIVE-BFS-(_)-Explained", "python_solutions": "class Solution:\n def minJumps(self, arr: List[int]) -> int:\n N, groups = len(arr), defaultdict(list)\n\n for i, el in enumerate(arr): \n groups[el].append(i)\n\n vis, vis_groups = set(), set()\n \n def bfs(lvl, dist):\n nextLvl = set()\n \n for i in lvl:\n if i in vis: continue\n if i == N-1: return dist\n \n vis.add(i)\n \n if i: nextLvl.add(i-1)\n if i+1 < N: nextLvl.add(i+1)\n \n if not arr[i] in vis_groups:\n vis_groups.add(arr[i])\n nextLvl.update(groups[arr[i]])\n \n return bfs(nextLvl, dist + 1)\n \n return bfs(set([0]), 0)", "slug": "jump-game-iv", "post_title": "\u2714\ufe0f [Python3] RECURSIVE BFS (\u0482\u25e1_\u25e1) \u1564, Explained \ud83d\udca5", "user": "artod", "upvotes": 9, "views": 321, "problem_title": "jump game iv", "number": 1345, "acceptance": 0.44, "difficulty": "Hard", "__index_level_0__": 20245, "question": "Given an array of integers arr, you are initially positioned at the first index of the array.\nIn one step you can jump from index i to index:\ni + 1 where: i + 1 < arr.length.\ni - 1 where: i - 1 >= 0.\nj where: arr[i] == arr[j] and i != j.\nReturn the minimum number of steps to reach the last index of the array.\nNotice that you can not jump outside of the array at any time.\n Example 1:\nInput: arr = [100,-23,-23,404,100,23,23,23,3,404]\nOutput: 3\nExplanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\nExample 2:\nInput: arr = [7]\nOutput: 0\nExplanation: Start index is the last index. You do not need to jump.\nExample 3:\nInput: arr = [7,6,9,6,9,6,9,7]\nOutput: 1\nExplanation: You can jump directly from index 0 to index 7 which is last index of the array.\n Constraints:\n1 <= arr.length <= 5 * 104\n-108 <= arr[i] <= 108" }, { "post_href": "https://leetcode.com/problems/check-if-n-and-its-double-exist/discuss/503507/Python-3-(five-lines)-(beats-100)", "python_solutions": "class Solution:\n def checkIfExist(self, A: List[int]) -> bool:\n if A.count(0) > 1: return True\n S = set(A) - {0}\n for a in A:\n if 2*a in S: return True\n return False\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "check-if-n-and-its-double-exist", "post_title": "Python 3 (five lines) (beats 100%)", "user": "junaidmansuri", "upvotes": 20, "views": 4100, "problem_title": "check if n and its double exist", "number": 1346, "acceptance": 0.362, "difficulty": "Easy", "__index_level_0__": 20255, "question": "Given an array arr of integers, check if there exist two indices i and j such that :\ni != j\n0 <= i, j < arr.length\narr[i] == 2 * arr[j]\n Example 1:\nInput: arr = [10,2,5,3]\nOutput: true\nExplanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]\nExample 2:\nInput: arr = [3,1,7,11]\nOutput: false\nExplanation: There is no i and j that satisfy the conditions.\n Constraints:\n2 <= arr.length <= 500\n-103 <= arr[i] <= 103" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/discuss/503535/Python-3-(two-lines)-(beats-100)", "python_solutions": "class Solution:\n def minSteps(self, S: str, T: str) -> int:\n D = collections.Counter(S) - collections.Counter(T)\n return sum(max(0, D[s]) for s in set(S))\n\t\t\n\t\t\n- Junaid Mansuri\n- Chicago, IL", "slug": "minimum-number-of-steps-to-make-two-strings-anagram", "post_title": "Python 3 (two lines) (beats 100%)", "user": "junaidmansuri", "upvotes": 9, "views": 2100, "problem_title": "minimum number of steps to make two strings anagram", "number": 1347, "acceptance": 0.774, "difficulty": "Medium", "__index_level_0__": 20304, "question": "You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.\nReturn the minimum number of steps to make t an anagram of s.\nAn Anagram of a string is a string that contains the same characters with a different (or the same) ordering.\n Example 1:\nInput: s = \"bab\", t = \"aba\"\nOutput: 1\nExplanation: Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.\nExample 2:\nInput: s = \"leetcode\", t = \"practice\"\nOutput: 5\nExplanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.\nExample 3:\nInput: s = \"anagram\", t = \"mangaar\"\nOutput: 0\nExplanation: \"anagram\" and \"mangaar\" are anagrams. \n Constraints:\n1 <= s.length <= 5 * 104\ns.length == t.length\ns and t consist of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/maximum-students-taking-exam/discuss/1899957/Python-Bitmasking-dp-solution-with-explanation", "python_solutions": "class Solution:\n def maxStudents(self, seats: list[list[str]]) -> int:\n def count_bits(num: int) -> int:\n # Count how many bits having value 1 in num.\n cnt = 0\n while num:\n cnt += 1\n num &= num - 1\n\n return cnt\n\n R, C = len(seats), len(seats[0])\n validSeats = []\n\n # Calculate valid seats mask for each row.\n for row in seats:\n curr = 0\n for seat in row:\n curr = (curr << 1) + (seat == '.')\n\n validSeats.append(curr)\n\n # dp[i][mask] stands for the maximum students on ith row with students\n # following the mask.\n dp = [[-1] * (1 << C) for _ in range(R + 1)]\n dp[0][0] = 0\n for r in range(1, R + 1):\n seatMask = validSeats[r - 1]\n for studentMask in range(1 << C):\n validBits = count_bits(studentMask)\n\n # 1. Check if a student mask is a subset of seatMask so that\n # the target student could sit on a seat.\n # 2. The student should not sit next to each other.\n if (\n studentMask & seatMask == studentMask and\n studentMask & (studentMask >> 1) == 0\n ):\n # Then check the upper student mask and make sure that\n # 1. no student is on the upper left.\n # 2. no student is on the upper right.\n # Then the upper mask is a valid candidate for the current\n # student mask.\n for upperStudentMask in range(1 << C):\n if (\n studentMask & (upperStudentMask >> 1) == 0 and\n studentMask & (upperStudentMask << 1) == 0 and\n dp[r - 1][upperStudentMask] != -1\n ):\n dp[r][studentMask] = max(\n dp[r][studentMask],\n dp[r - 1][upperStudentMask] + validBits\n )\n\n return max(dp[-1])", "slug": "maximum-students-taking-exam", "post_title": "[Python] Bitmasking dp solution with explanation", "user": "eroneko", "upvotes": 0, "views": 56, "problem_title": "maximum students taking exam", "number": 1349, "acceptance": 0.483, "difficulty": "Hard", "__index_level_0__": 20334, "question": "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.\nStudents can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible.\nStudents must be placed in seats in good condition.\n Example 1:\nInput: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\nOutput: 4\nExplanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \nExample 2:\nInput: seats = [[\".\",\"#\"],\n [\"#\",\"#\"],\n [\"#\",\".\"],\n [\"#\",\"#\"],\n [\".\",\"#\"]]\nOutput: 3\nExplanation: Place all students in available seats. \nExample 3:\nInput: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n [\".\",\"#\",\".\",\"#\",\".\"],\n [\".\",\".\",\"#\",\".\",\".\"],\n [\".\",\"#\",\".\",\"#\",\".\"],\n [\"#\",\".\",\".\",\".\",\"#\"]]\nOutput: 10\nExplanation: Place students in available seats in column 1, 3 and 5.\n Constraints:\nseats contains only characters '.' and'#'.\nm == seats.length\nn == seats[i].length\n1 <= m <= 8\n1 <= n <= 8" }, { "post_href": "https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix/discuss/2193369/Python3-slight-tweak-in-binary-search", "python_solutions": "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n result = 0\n rows = len(grid)\n cols = len(grid[0])\n \n i = 0\n j = cols - 1\n while i < rows and j>=0:\n curr = grid[i][j]\n if(curr < 0):\n j-=1\n else:\n result+=((cols-1) - j) #capture the no.of negative number in this row and jump to next row\n i+=1\n \n\t\t#left out negative rows\n while i < rows:\n result+=cols\n i+=1\n \n return result", "slug": "count-negative-numbers-in-a-sorted-matrix", "post_title": "\ud83d\udccc Python3 slight tweak in binary search", "user": "Dark_wolf_jss", "upvotes": 6, "views": 73, "problem_title": "count negative numbers in a sorted matrix", "number": 1351, "acceptance": 0.752, "difficulty": "Easy", "__index_level_0__": 20336, "question": "Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.\n Example 1:\nInput: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\nOutput: 8\nExplanation: There are 8 negatives number in the matrix.\nExample 2:\nInput: grid = [[3,2],[1,0]]\nOutput: 0\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 100\n-100 <= grid[i][j] <= 100\n Follow up: Could you find an O(n + m) solution?" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/discuss/726456/Python3-solution-with-detailed-explanation", "python_solutions": "# Solution 1\ndef maxEvents(self, events: List[List[int]]) -> int:\n events = sorted(events, key=lambda x: x[1])\n visited = set()\n for s, e in events:\n for t in range(s, e+1):\n if t not in visited:\n visited.add(t)\n break\n return len(visited)", "slug": "maximum-number-of-events-that-can-be-attended", "post_title": "Python3 solution with detailed explanation", "user": "peyman_np", "upvotes": 12, "views": 2400, "problem_title": "maximum number of events that can be attended", "number": 1353, "acceptance": 0.3289999999999999, "difficulty": "Medium", "__index_level_0__": 20386, "question": "You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.\nYou can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.\nReturn the maximum number of events you can attend.\n Example 1:\nInput: events = [[1,2],[2,3],[3,4]]\nOutput: 3\nExplanation: You can attend all the three events.\nOne way to attend them all is as shown.\nAttend the first event on day 1.\nAttend the second event on day 2.\nAttend the third event on day 3.\nExample 2:\nInput: events= [[1,2],[2,3],[3,4],[1,2]]\nOutput: 4\n Constraints:\n1 <= events.length <= 105\nevents[i].length == 2\n1 <= startDayi <= endDayi <= 105" }, { "post_href": "https://leetcode.com/problems/construct-target-array-with-multiple-sums/discuss/2189540/Python-Easy-Solution-oror-Less-Line-Of-Code-oror-Heapify", "python_solutions": "class Solution:\n\tdef isPossible(self, target: List[int]) -> bool:\n\n\t\theapq._heapify_max(target)\n\t\ts = sum(target)\n\n\t\twhile target[0] != 1:\n\t\t\tsub = s - target[0]\n\t\t\tif sub == 0: return False\n\t\t\tn = max((target[0] - 1) // sub, 1)\n\t\t\ts -= n * sub\n\t\t\ttarget0 = target[0] - n * sub\n\t\t\tif target0 < 1: return False\n\t\t\theapq._heapreplace_max(target, target0)\n\n\t\treturn True\n\t```", "slug": "construct-target-array-with-multiple-sums", "post_title": "Python Easy Solution || Less Line Of Code || Heapify", "user": "vaibhav0077", "upvotes": 14, "views": 1400, "problem_title": "construct target array with multiple sums", "number": 1354, "acceptance": 0.363, "difficulty": "Hard", "__index_level_0__": 20393, "question": "You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure :\nlet x be the sum of all elements currently in your array.\nchoose index i, such that 0 <= i < n and set the value of arr at index i to x.\nYou may repeat this procedure as many times as needed.\nReturn true if it is possible to construct the target array from arr, otherwise, return false.\n Example 1:\nInput: target = [9,3,5]\nOutput: true\nExplanation: Start with arr = [1, 1, 1] \n[1, 1, 1], sum = 3 choose index 1\n[1, 3, 1], sum = 5 choose index 2\n[1, 3, 5], sum = 9 choose index 0\n[9, 3, 5] Done\nExample 2:\nInput: target = [1,1,1,2]\nOutput: false\nExplanation: Impossible to create target array from [1,1,1,1].\nExample 3:\nInput: target = [8,5]\nOutput: true\n Constraints:\nn == target.length\n1 <= n <= 5 * 104\n1 <= target[i] <= 109" }, { "post_href": "https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/discuss/2697450/Python-or-1-liner-lambda-key", "python_solutions": "class Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n return sorted(arr, key = lambda item: (str(bin(item))[2:].count(\"1\"), item))", "slug": "sort-integers-by-the-number-of-1-bits", "post_title": "Python | 1-liner lambda key", "user": "LordVader1", "upvotes": 4, "views": 791, "problem_title": "sort integers by the number of 1 bits", "number": 1356, "acceptance": 0.72, "difficulty": "Easy", "__index_level_0__": 20399, "question": "You are given an integer array arr. Sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.\nReturn the array after sorting it.\n Example 1:\nInput: arr = [0,1,2,3,4,5,6,7,8]\nOutput: [0,1,2,4,8,3,5,6,7]\nExplantion: [0] is the only integer with 0 bits.\n[1,2,4,8] all have 1 bit.\n[3,5,6] have 2 bits.\n[7] has 3 bits.\nThe sorted array by bits is [0,1,2,4,8,3,5,6,7]\nExample 2:\nInput: arr = [1024,512,256,128,64,32,16,8,4,2,1]\nOutput: [1,2,4,8,16,32,64,128,256,512,1024]\nExplantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.\n Constraints:\n1 <= arr.length <= 500\n0 <= arr[i] <= 104" }, { "post_href": "https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/851021/Python-3-or-Two-Pointers-or-Explanation", "python_solutions": "class Solution:\n def numberOfSubstrings(self, s: str) -> int:\n a = b = c = 0 # counter for letter a/b/c\n ans, i, n = 0, 0, len(s) # i: slow pointer\n for j, letter in enumerate(s): # j: fast pointer\n if letter == 'a': a += 1 # increment a/b/c accordingly\n elif letter == 'b': b += 1\n else: c += 1\n while a > 0 and b > 0 and c > 0: # if all of a/b/c are contained, move slow pointer\n ans += n-j # count possible substr, if a substr ends at j, then there are n-j substrs to the right that are containing all a/b/c\n if s[i] == 'a': a -= 1 # decrement counter accordingly\n elif s[i] == 'b': b -= 1\n else: c -= 1\n i += 1 # move slow pointer\n return ans", "slug": "number-of-substrings-containing-all-three-characters", "post_title": "Python 3 | Two Pointers | Explanation", "user": "idontknoooo", "upvotes": 23, "views": 1200, "problem_title": "number of substrings containing all three characters", "number": 1358, "acceptance": 0.631, "difficulty": "Medium", "__index_level_0__": 20440, "question": "Given a string s consisting only of characters a, b and c.\nReturn the number of substrings containing at least one occurrence of all these characters a, b and c.\n Example 1:\nInput: s = \"abcabc\"\nOutput: 10\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\" and \"abc\" (again). \nExample 2:\nInput: s = \"aaacb\"\nOutput: 3\nExplanation: The substrings containing at least one occurrence of the characters a, b and c are \"aaacb\", \"aacb\" and \"acb\". \nExample 3:\nInput: s = \"abc\"\nOutput: 1\n Constraints:\n3 <= s.length <= 5 x 10^4\ns only consists of a, b or c characters." }, { "post_href": "https://leetcode.com/problems/count-all-valid-pickup-and-delivery-options/discuss/1825566/Python-oror-Easy-To-Understand-oror-98-Faster-oror-Maths", "python_solutions": "class Solution:\n def countOrders(self, n: int) -> int:\n n=2*n\n ans=1\n while n>=2:\n ans = ans *((n*(n-1))//2)\n n-=2\n ans=ans%1000000007\n return ans", "slug": "count-all-valid-pickup-and-delivery-options", "post_title": "\u2705Python || Easy To Understand || 98% Faster || Maths", "user": "rahulmittall", "upvotes": 3, "views": 53, "problem_title": "count all valid pickup and delivery options", "number": 1359, "acceptance": 0.629, "difficulty": "Hard", "__index_level_0__": 20453, "question": "Given n orders, each order consists of a pickup and a delivery service.\nCount all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). \nSince the answer may be too large, return it modulo 10^9 + 7.\n Example 1:\nInput: n = 1\nOutput: 1\nExplanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\nExample 2:\nInput: n = 2\nOutput: 6\nExplanation: All possible orders: \n(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\nThis is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\nExample 3:\nInput: n = 3\nOutput: 90\n Constraints:\n1 <= n <= 500" }, { "post_href": "https://leetcode.com/problems/number-of-days-between-two-dates/discuss/1814530/Python3-Solution-from-Scratch-NOT-USING-DATETIME", "python_solutions": "class Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n \n def f_date(date): # calculates days passed since '1900-01-01'\n year0 = '1900'\n year1, month1, day1 = date.split('-')\n \n days = 0\n for y in range(int(year0), int(year1)):\n days += 365\n if y%100 == 0:\n if y%400 == 0:\n days += 1\n else:\n if y%4 == 0:\n days += 1\n \n for m in range(int(month1)):\n if m in [1, 3, 5, 7, 8, 10, 12]:\n days += 31\n if m in [4, 6, 9, 11]:\n days += 30\n if m == 2:\n days += 28\n if int(year1)%100 == 0:\n if int(year1)%400 == 0:\n days += 1\n else:\n if int(year1)%4 ==0:\n days += 1\n days += int(day1)\n return days\n\t\t\t\n return abs(f_date(date1) - f_date(date2))", "slug": "number-of-days-between-two-dates", "post_title": "Python3 Solution from Scratch - NOT USING DATETIME", "user": "rmateusc", "upvotes": 3, "views": 617, "problem_title": "number of days between two dates", "number": 1360, "acceptance": 0.476, "difficulty": "Easy", "__index_level_0__": 20467, "question": "Write a program to count the number of days between two dates.\nThe two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.\n Example 1:\nInput: date1 = \"2019-06-29\", date2 = \"2019-06-30\"\nOutput: 1\nExample 2:\nInput: date1 = \"2020-01-15\", date2 = \"2019-12-31\"\nOutput: 15\n Constraints:\nThe given dates are valid dates between the years 1971 and 2100." }, { "post_href": "https://leetcode.com/problems/validate-binary-tree-nodes/discuss/1393392/Diagram-Explained-Clean-4-checks-single-parents-single-root-no-cycle-all-connected", "python_solutions": "class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n n = len(leftChild)\n \n # tree has 2 requirements\n # 1. every node has a single parent\n # 2. single root (only one node has NO parent)\n # 3. no cycle\n # 4. all nodes connected to each other (single component)\n \n parent = [-1] * n\n \n # checking condition (1. and 2.)\n for idx, (left, right) in enumerate(zip(leftChild, rightChild)):\n \n if left != -1:\n # FAILED: condition (1.)\n if parent[left] != -1: return False\n parent[left] = idx\n \n if right != -1:\n # FAILED: condition (1.)\n if parent[right] != -1: return False\n parent[right] = idx\n \n # FAILED condition (2.)\n if parent.count(-1) != 1: return False\n \n # checking condition (3. and 4.)\n vis = set()\n def dfs_has_cycle(u):\n if u in vis:\n return True\n else:\n vis.add(u)\n \n for kid in [leftChild[u], rightChild[u]]:\n if kid != -1:\n if dfs_has_cycle(kid): return True\n \n # FAILED condition (3.) - found a cycle\n if dfs_has_cycle(parent.index(-1)): return False\n \n # FAILED condition (4.) - DFS did not visit all nodes!\n if len(vis) != n: return False\n \n # did not FAIL any condition, success ;)\n return True\n\n\"\"\"\nTricky test case (cycle and not connected):\n4\n[1,-1,3,-1]\n[2,-1,-1,-1]\n\n\"\"\"", "slug": "validate-binary-tree-nodes", "post_title": "Diagram Explained Clean 4 checks [single parents, single root, no cycle, all connected]", "user": "yozaam", "upvotes": 6, "views": 232, "problem_title": "validate binary tree nodes", "number": 1361, "acceptance": 0.4029999999999999, "difficulty": "Medium", "__index_level_0__": 20474, "question": "You have n binary tree nodes numbered from 0 to n - 1 where node i has two children leftChild[i] and rightChild[i], return true if and only if all the given nodes form exactly one valid binary tree.\nIf node i has no left child then leftChild[i] will equal -1, similarly for the right child.\nNote that the nodes have no values and that we only use the node numbers in this problem.\n Example 1:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\nOutput: true\nExample 2:\nInput: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\nOutput: false\nExample 3:\nInput: n = 2, leftChild = [1,0], rightChild = [-1,-1]\nOutput: false\n Constraints:\nn == leftChild.length == rightChild.length\n1 <= n <= 104\n-1 <= leftChild[i], rightChild[i] <= n - 1" }, { "post_href": "https://leetcode.com/problems/closest-divisors/discuss/517720/Python3-A-concise-solution", "python_solutions": "class Solution:\n def closestDivisors(self, num: int) -> List[int]:\n for i in range(int((num+2)**0.5), 0, -1):\n if not (num+1)%i: return (i, (num+1)//i)\n if not (num+2)%i: return (i, (num+2)//i)", "slug": "closest-divisors", "post_title": "[Python3] A concise solution", "user": "ye15", "upvotes": 1, "views": 50, "problem_title": "closest divisors", "number": 1362, "acceptance": 0.599, "difficulty": "Medium", "__index_level_0__": 20490, "question": "Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.\nReturn the two integers in any order.\n Example 1:\nInput: num = 8\nOutput: [3,3]\nExplanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.\nExample 2:\nInput: num = 123\nOutput: [5,25]\nExample 3:\nInput: num = 999\nOutput: [40,25]\n Constraints:\n1 <= num <= 10^9" }, { "post_href": "https://leetcode.com/problems/largest-multiple-of-three/discuss/519005/Clean-Python-3-counting-sort-O(N)O(1)-timespace-100", "python_solutions": "class Solution:\n def largestMultipleOfThree(self, digits: List[int]) -> str:\n def dump(r: int) -> str:\n if r:\n for i in range(3):\n idx = 3 * i + r\n if counts[idx]:\n counts[idx] -= 1\n break\n else:\n rest = 2\n for j in range(3):\n idx = 3 * j + (-r % 3)\n while rest and counts[idx]:\n counts[idx] -= 1\n rest -= 1\n if not rest: break\n if rest: return ''\n if any(counts):\n result = ''\n for i in reversed(range(10)):\n result += str(i) * counts[i]\n return str(int(result))\n return ''\n\n total, counts = 0, [0] * 10\n for digit in digits:\n counts[digit] += 1\n total += digit\n return dump(total % 3)", "slug": "largest-multiple-of-three", "post_title": "Clean Python 3, counting sort O(N)/O(1) time/space, 100%", "user": "lenchen1112", "upvotes": 2, "views": 268, "problem_title": "largest multiple of three", "number": 1363, "acceptance": 0.3329999999999999, "difficulty": "Hard", "__index_level_0__": 20499, "question": "Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.\nSince the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.\n Example 1:\nInput: digits = [8,1,9]\nOutput: \"981\"\nExample 2:\nInput: digits = [8,6,7,1,0]\nOutput: \"8760\"\nExample 3:\nInput: digits = [1]\nOutput: \"\"\n Constraints:\n1 <= digits.length <= 104\n0 <= digits[i] <= 9" }, { "post_href": "https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/discuss/613343/Simple-Python-Solution-72ms-and-13.8-MB-EXPLAINED", "python_solutions": "class Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n a=[]\n numi = sorted(nums)\n for i in range(0,len(nums)):\n a.append(numi.index(nums[i]))\n return a", "slug": "how-many-numbers-are-smaller-than-the-current-number", "post_title": "Simple Python Solution [72ms and 13.8 MB] EXPLAINED", "user": "code_zero", "upvotes": 10, "views": 849, "problem_title": "how many numbers are smaller than the current number", "number": 1365, "acceptance": 0.867, "difficulty": "Easy", "__index_level_0__": 20506, "question": "Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i].\nReturn the answer in an array.\n Example 1:\nInput: nums = [8,1,2,2,3]\nOutput: [4,0,1,1,3]\nExplanation: \nFor nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \nFor nums[1]=1 does not exist any smaller number than it.\nFor nums[2]=2 there exist one smaller number than it (1). \nFor nums[3]=2 there exist one smaller number than it (1). \nFor nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\nExample 2:\nInput: nums = [6,5,4,8]\nOutput: [2,1,0,3]\nExample 3:\nInput: nums = [7,7,7,7]\nOutput: [0,0,0,0]\n Constraints:\n2 <= nums.length <= 500\n0 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/rank-teams-by-votes/discuss/2129031/python-3-oror-simple-O(n)O(1)-solution", "python_solutions": "class Solution:\n def rankTeams(self, votes: List[str]) -> str:\n teamVotes = collections.defaultdict(lambda: [0] * 26)\n for vote in votes:\n for pos, team in enumerate(vote):\n teamVotes[team][pos] += 1\n \n return ''.join(sorted(teamVotes.keys(), reverse=True,\n key=lambda team: (teamVotes[team], -ord(team))))", "slug": "rank-teams-by-votes", "post_title": "python 3 || simple O(n)/O(1) solution", "user": "dereky4", "upvotes": 5, "views": 465, "problem_title": "rank teams by votes", "number": 1366, "acceptance": 0.586, "difficulty": "Medium", "__index_level_0__": 20554, "question": "In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.\nThe ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.\nYou are given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.\nReturn a string of all teams sorted by the ranking system.\n Example 1:\nInput: votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\nOutput: \"ACB\"\nExplanation: \nTeam A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\nTeam B was ranked second by 2 voters and ranked third by 3 voters.\nTeam C was ranked second by 3 voters and ranked third by 2 voters.\nAs most of the voters ranked C second, team C is the second team, and team B is the third.\nExample 2:\nInput: votes = [\"WXYZ\",\"XYZW\"]\nOutput: \"XWYZ\"\nExplanation:\nX is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position. \nExample 3:\nInput: votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\nOutput: \"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\nExplanation: Only one voter, so their votes are used for the ranking.\n Constraints:\n1 <= votes.length <= 1000\n1 <= votes[i].length <= 26\nvotes[i].length == votes[j].length for 0 <= i, j < votes.length.\nvotes[i][j] is an English uppercase letter.\nAll characters of votes[i] are unique.\nAll the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length." }, { "post_href": "https://leetcode.com/problems/linked-list-in-binary-tree/discuss/525814/Python3-A-naive-dp-approach", "python_solutions": "class Solution:\n def isSubPath(self, head: ListNode, root: TreeNode) -> bool:\n #build longest prefix-suffix array\n pattern, lps = [head.val], [0] #longest prefix-suffix array\n j = 0\n while head.next: \n head = head.next \n pattern.append(head.val)\n \n while j and head.val != pattern[j]: j = lps[j-1]\n if head.val == pattern[j]: j += 1\n lps.append(j)\n \n def dfs(root, i): \n \"\"\"Return True of tree rooted at \"root\" match pattern\"\"\"\n if i == len(pattern): return True\n if not root: return False \n \n while i > 0 and root.val != pattern[i]: i = lps[i-1]\n if root.val == pattern[i]: i += 1\n return dfs(root.left, i) or dfs(root.right, i)\n \n return dfs(root, 0)", "slug": "linked-list-in-binary-tree", "post_title": "[Python3] A naive dp approach", "user": "ye15", "upvotes": 1, "views": 96, "problem_title": "linked list in binary tree", "number": 1367, "acceptance": 0.435, "difficulty": "Medium", "__index_level_0__": 20565, "question": "Given a binary tree root and a linked list with head as the first node. \nReturn True if all the elements in the linked list starting from the head correspond to some downward path connected in the binary tree otherwise return False.\nIn this context downward path means a path that starts at some node and goes downwards.\n Example 1:\nInput: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\nExplanation: Nodes in blue form a subpath in the binary Tree. \nExample 2:\nInput: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: true\nExample 3:\nInput: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\nOutput: false\nExplanation: There is no path in the binary tree that contains all the elements of the linked list from head.\n Constraints:\nThe number of nodes in the tree will be in the range [1, 2500].\nThe number of nodes in the list will be in the range [1, 100].\n1 <= Node.val <= 100 for each node in the linked list and binary tree." }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/discuss/1504913/Python-or-Template-or-0-1-BFS-vs-Dijkstra-or-Explanation", "python_solutions": "class Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n graph = {}\n m, n = len(grid), len(grid[0])\n \n def addEdges(i, j):\n graph[(i, j)] = {}\n neighbors = [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]\n for each in neighbors:\n x, y = each\n if x < 0 or y < 0 or x > m - 1 or y > n - 1:\n continue\n else:\n graph[(i, j)][(x, y)] = 1\n \n if grid[i][j] == 1:\n if j != n - 1:\n graph[(i, j)][(i, j + 1)] = 0\n \n elif grid[i][j] == 2:\n if j != 0:\n graph[(i, j)][(i, j - 1)] = 0\n \n elif grid[i][j] == 3:\n if i != m - 1:\n graph[(i, j)][(i + 1, j)] = 0\n \n else:\n if i != 0:\n graph[(i, j)][(i - 1, j)] = 0\n \n \n for i in range(m):\n for j in range(n):\n addEdges(i, j)\n \n\t\t# convert row, col to index value in distances array\n def convert(x, y):\n return x * n + y\n \n def BFS(graph):\n q = deque()\n q.append([0, 0, 0])\n distances = [float(inf)] * (m * n)\n \n while q:\n cost, x, y = q.popleft()\n if (x, y) == (m - 1, n - 1):\n return cost\n \n idx = convert(x, y)\n if distances[idx] < cost:\n continue\n \n distances[idx] = cost\n for node, nxtCost in graph[(x, y)].items():\n nxtIndex = convert(node[0], node[1])\n if distances[nxtIndex] <= cost + nxtCost:\n continue\n \n distances[nxtIndex] = cost + nxtCost\n if nxtCost == 0:\n q.appendleft([cost, node[0], node[1]])\n else:\n q.append([cost + 1, node[0], node[1]])\n \n \n def dijkstra(graph):\n distances = [float(inf)] * (m * n)\n myheap = [[0, 0, 0]]\n #distances[0] = 0\n \n while myheap:\n cost, x, y = heappop(myheap)\n if (x, y) == (m - 1, n - 1):\n return cost\n \n idx = convert(x, y)\n if distances[idx] < cost:\n continue\n else:\n distances[idx] = cost\n for node, nxtCost in graph[(x, y)].items():\n total = cost + nxtCost\n nxtIndex = convert(node[0], node[1])\n if distances[nxtIndex] <= total:\n continue\n else:\n distances[nxtIndex] = total\n heappush(myheap, [total, node[0], node[1]])\n \n return distances[-1]\n \n #return dijkstra(graph)\n return BFS(graph)", "slug": "minimum-cost-to-make-at-least-one-valid-path-in-a-grid", "post_title": "Python | Template | 0-1 BFS vs Dijkstra | Explanation", "user": "detective_dp", "upvotes": 3, "views": 290, "problem_title": "minimum cost to make at least one valid path in a grid", "number": 1368, "acceptance": 0.613, "difficulty": "Hard", "__index_level_0__": 20573, "question": "Given an m x n grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of grid[i][j] can be:\n1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])\n2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])\n3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])\n4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])\nNotice that there could be some signs on the cells of the grid that point outside the grid.\nYou will initially start at the upper left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1) following the signs on the grid. The valid path does not have to be the shortest.\nYou can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.\nReturn the minimum cost to make the grid have at least one valid path.\n Example 1:\nInput: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\nOutput: 3\nExplanation: You will start at point (0, 0).\nThe path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\nThe total cost = 3.\nExample 2:\nInput: grid = [[1,1,3],[3,2,2],[1,1,4]]\nOutput: 0\nExplanation: You can follow the path from (0, 0) to (2, 2).\nExample 3:\nInput: grid = [[1,2],[4,3]]\nOutput: 1\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 100\n1 <= grid[i][j] <= 4" }, { "post_href": "https://leetcode.com/problems/increasing-decreasing-string/discuss/543172/Python-3-Using-Set-and-Sort-with-commentary", "python_solutions": "class Solution:\n def sortString(self, s: str) -> str:\n s = list(s)\n # Big S: O(n)\n result = []\n \n # Logic is capture distinct char with set\n # Remove found char from initial string\n \n # Big O: O(n)\n while len(s) > 0:\n\n # Big O: O(n log n) Space: O(n)\n smallest = sorted(set(s))\n # Big O: O(s) - reduced set\n for small in smallest:\n result.append(small)\n s.remove(small)\n \n # Big O: O(n log n) Space: O(n)\n largest = sorted(set(s), reverse = True)\n # Big O: O(s) - reduced set\n for large in largest:\n result.append(large)\n s.remove(large)\n \n return ''.join(result)\n \n # Summary: Big O(n)^2 Space: O(n)", "slug": "increasing-decreasing-string", "post_title": "[Python 3] Using Set and Sort with commentary", "user": "dentedghost", "upvotes": 11, "views": 966, "problem_title": "increasing decreasing string", "number": 1370, "acceptance": 0.774, "difficulty": "Easy", "__index_level_0__": 20582, "question": "You are given a string s. Reorder the string using the following algorithm:\nPick the smallest character from s and append it to the result.\nPick the smallest character from s which is greater than the last appended character to the result and append it.\nRepeat step 2 until you cannot pick more characters.\nPick the largest character from s and append it to the result.\nPick the largest character from s which is smaller than the last appended character to the result and append it.\nRepeat step 5 until you cannot pick more characters.\nRepeat the steps from 1 to 6 until you pick all characters from s.\nIn each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.\nReturn the result string after sorting s with this algorithm.\n Example 1:\nInput: s = \"aaaabbbbcccc\"\nOutput: \"abccbaabccba\"\nExplanation: After steps 1, 2 and 3 of the first iteration, result = \"abc\"\nAfter steps 4, 5 and 6 of the first iteration, result = \"abccba\"\nFirst iteration is done. Now s = \"aabbcc\" and we go back to step 1\nAfter steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\nAfter steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"\nExample 2:\nInput: s = \"rat\"\nOutput: \"art\"\nExplanation: The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.\n Constraints:\n1 <= s.length <= 500\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/discuss/1125562/Python3-bitmask", "python_solutions": "class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n ans = mask = 0 \n seen = {0: -1}\n for i, c in enumerate(s):\n if c in \"aeiou\": \n mask ^= 1 << (\"aeiou\".find(c))\n if mask in seen: ans = max(ans, i - seen[mask])\n seen.setdefault(mask, i)\n return ans", "slug": "find-the-longest-substring-containing-vowels-in-even-counts", "post_title": "[Python3] bitmask", "user": "ye15", "upvotes": 4, "views": 148, "problem_title": "find the longest substring containing vowels in even counts", "number": 1371, "acceptance": 0.629, "difficulty": "Medium", "__index_level_0__": 20609, "question": "Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.\n Example 1:\nInput: s = \"eleetminicoworoep\"\nOutput: 13\nExplanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\nExample 2:\nInput: s = \"leetcodeisgreat\"\nOutput: 5\nExplanation: The longest substring is \"leetc\" which contains two e's.\nExample 3:\nInput: s = \"bcbcbc\"\nOutput: 6\nExplanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n Constraints:\n1 <= s.length <= 5 x 10^5\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/discuss/2559539/Python3-Iterative-DFS-Using-Stack-99-time-91-space-O(N)-time-O(N)-space", "python_solutions": "class Solution:\n def longestZigZag(self, root: Optional[TreeNode]) -> int:\n \n LEFT = 0\n RIGHT = 1\n \n stack = []\n if root.left:\n stack.append((root.left, LEFT, 1))\n if root.right:\n stack.append((root.right, RIGHT, 1))\n \n longest = 0\n while stack:\n node, direction, count = stack.pop()\n \n longest = max(longest, count)\n if direction == LEFT:\n if node.left:\n stack.append((node.left, LEFT, 1))\n if node.right:\n stack.append((node.right, RIGHT, count+1))\n else:\n if node.right:\n stack.append((node.right, RIGHT, 1))\n if node.left:\n stack.append((node.left, LEFT, count+1))\n return longest", "slug": "longest-zigzag-path-in-a-binary-tree", "post_title": "[Python3] Iterative DFS Using Stack - 99% time 91% space, - O(N) time O(N) space", "user": "rt500", "upvotes": 0, "views": 35, "problem_title": "longest zigzag path in a binary tree", "number": 1372, "acceptance": 0.598, "difficulty": "Medium", "__index_level_0__": 20615, "question": "You are given the root of a binary tree.\nA ZigZag path for a binary tree is defined as follow:\nChoose any node in the binary tree and a direction (right or left).\nIf the current direction is right, move to the right child of the current node; otherwise, move to the left child.\nChange the direction from right to left or from left to right.\nRepeat the second and third steps until you can't move in the tree.\nZigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\nReturn the longest ZigZag path contained in that tree.\n Example 1:\nInput: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1]\nOutput: 3\nExplanation: Longest ZigZag path in blue nodes (right -> left -> right).\nExample 2:\nInput: root = [1,1,1,null,1,null,null,1,1,null,1]\nOutput: 4\nExplanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\nExample 3:\nInput: root = [1]\nOutput: 0\n Constraints:\nThe number of nodes in the tree is in the range [1, 5 * 104].\n1 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-sum-bst-in-binary-tree/discuss/1377976/Python-O(n)-short-readable-solution", "python_solutions": "class Solution:\n def maxSumBST(self, root: TreeNode) -> int:\n tot = -math.inf\n\n def dfs(node):\n nonlocal tot\n if not node:\n return 0, math.inf, -math.inf \n l_res, l_min, l_max = dfs(node.left)\n r_res, r_min, r_max = dfs(node.right)\n\t\t\t# if maintains BST property\n if l_max str:\n a=\"a\"\n b=\"b\"\n if n%2==0:\n return (((n-1)*a)+b)\n return (n*a)", "slug": "generate-a-string-with-characters-that-have-odd-counts", "post_title": "Easy code in python with explanation.", "user": "souravsingpardeshi", "upvotes": 2, "views": 183, "problem_title": "generate a string with characters that have odd counts", "number": 1374, "acceptance": 0.7759999999999999, "difficulty": "Easy", "__index_level_0__": 20630, "question": "Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.\nThe returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. \n Example 1:\nInput: n = 4\nOutput: \"pppz\"\nExplanation: \"pppz\" is a valid string since the character 'p' occurs three times and the character 'z' occurs once. Note that there are many other valid strings such as \"ohhh\" and \"love\".\nExample 2:\nInput: n = 2\nOutput: \"xy\"\nExplanation: \"xy\" is a valid string since the characters 'x' and 'y' occur once. Note that there are many other valid strings such as \"ag\" and \"ur\".\nExample 3:\nInput: n = 7\nOutput: \"holasss\"\n Constraints:\n1 <= n <= 500" }, { "post_href": "https://leetcode.com/problems/number-of-times-binary-string-is-prefix-aligned/discuss/1330283/Python3-solution-O(n)-time-and-O(1)-space-complexity", "python_solutions": "class Solution:\n def numTimesAllBlue(self, light: List[int]) -> int:\n max = count = 0\n for i in range(len(light)):\n if max < light[i]:\n max = light[i]\n if max == i + 1:\n count += 1\n return count", "slug": "number-of-times-binary-string-is-prefix-aligned", "post_title": "Python3 solution O(n) time and O(1) space complexity", "user": "EklavyaJoshi", "upvotes": 4, "views": 312, "problem_title": "number of times binary string is prefix aligned", "number": 1375, "acceptance": 0.659, "difficulty": "Medium", "__index_level_0__": 20652, "question": "You have a 1-indexed binary string of length n where all the bits are 0 initially. We will flip all the bits of this binary string (i.e., change them from 0 to 1) one by one. You are given a 1-indexed integer array flips where flips[i] indicates that the bit at index i will be flipped in the ith step.\nA binary string is prefix-aligned if, after the ith step, all the bits in the inclusive range [1, i] are ones and all the other bits are zeros.\nReturn the number of times the binary string is prefix-aligned during the flipping process.\n Example 1:\nInput: flips = [3,2,4,1,5]\nOutput: 2\nExplanation: The binary string is initially \"00000\".\nAfter applying step 1: The string becomes \"00100\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"01100\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"01110\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"11110\", which is prefix-aligned.\nAfter applying step 5: The string becomes \"11111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 2 times, so we return 2.\nExample 2:\nInput: flips = [4,1,2,3]\nOutput: 1\nExplanation: The binary string is initially \"0000\".\nAfter applying step 1: The string becomes \"0001\", which is not prefix-aligned.\nAfter applying step 2: The string becomes \"1001\", which is not prefix-aligned.\nAfter applying step 3: The string becomes \"1101\", which is not prefix-aligned.\nAfter applying step 4: The string becomes \"1111\", which is prefix-aligned.\nWe can see that the string was prefix-aligned 1 time, so we return 1.\n Constraints:\nn == flips.length\n1 <= n <= 5 * 104\nflips is a permutation of the integers in the range [1, n]." }, { "post_href": "https://leetcode.com/problems/time-needed-to-inform-all-employees/discuss/1206574/Python3-Path-compression-(Clean-code-beats-99)", "python_solutions": "class Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n def find(i):\n if manager[i] != -1:\n informTime[i] += find(manager[i])\n manager[i] = -1\n return informTime[i]\n return max(map(find, range(n)))", "slug": "time-needed-to-inform-all-employees", "post_title": "[Python3] Path compression (Clean code, beats 99%)", "user": "SPark9625", "upvotes": 10, "views": 351, "problem_title": "time needed to inform all employees", "number": 1376, "acceptance": 0.584, "difficulty": "Medium", "__index_level_0__": 20658, "question": "A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.\nEach employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.\nThe head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.\nThe i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).\nReturn the number of minutes needed to inform all the employees about the urgent news.\n Example 1:\nInput: n = 1, headID = 0, manager = [-1], informTime = [0]\nOutput: 0\nExplanation: The head of the company is the only employee in the company.\nExample 2:\nInput: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\nOutput: 1\nExplanation: The head of the company with id = 2 is the direct manager of all the employees in the company and needs 1 minute to inform them all.\nThe tree structure of the employees in the company is shown.\n Constraints:\n1 <= n <= 105\n0 <= headID < n\nmanager.length == n\n0 <= manager[i] < n\nmanager[headID] == -1\ninformTime.length == n\n0 <= informTime[i] <= 1000\ninformTime[i] == 0 if employee i has no subordinates.\nIt is guaranteed that all the employees can be informed." }, { "post_href": "https://leetcode.com/problems/frog-position-after-t-seconds/discuss/1092590/Python-basic-DFS-from-a-new-grad", "python_solutions": "class Solution:\n\n\tdef frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n\t\tif target==1:\n\t\t\tif t>=1 and len(edges)>=1:\n\t\t\t\treturn 0\n\t\tadj = collections.defaultdict(list)\n\t\tfor i in edges:\n\t\t\tadj[min(i[0],i[1])].append(max(i[1],i[0]))\n\n\t\tdef traversal(curr, target,t):\n\t\t\tif curr==target:\n\t\t\t\tif t==0 or len(adj[curr])==0:\n\t\t\t\t\treturn 1\n\t\t\t\treturn 0\n\t\t\tif t==0:\n\t\t\t\treturn 0\n\t\t\tfor child in adj[curr]:\n\t\t\t\tprob = traversal(child, target, t-1)/len(adj[curr])\n\t\t\t\tif prob>0: \n\t\t\t\t\treturn prob\n\t\t\treturn 0\n\t\treturn traversal(1,target,t)", "slug": "frog-position-after-t-seconds", "post_title": "Python basic DFS from a new grad", "user": "yb233", "upvotes": 1, "views": 142, "problem_title": "frog position after t seconds", "number": 1377, "acceptance": 0.361, "difficulty": "Hard", "__index_level_0__": 20681, "question": "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.\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.\nReturn the probability that after t seconds the frog is on the vertex target. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\nOutput: 0.16666666666666666 \nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. \nExample 2:\nInput: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\nOutput: 0.3333333333333333\nExplanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. \n Constraints:\n1 <= n <= 100\nedges.length == n - 1\nedges[i].length == 2\n1 <= ai, bi <= n\n1 <= t <= 50\n1 <= target <= n" }, { "post_href": "https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/discuss/2046151/Python-Simple-2-approaches-Recursion(3-liner)-and-Morris", "python_solutions": "class Solution: \n def getTargetCopy(self, node1: TreeNode, node2: TreeNode, target: TreeNode) -> TreeNode: \n if not node1 or target == node1: # if node1 is null, node2 will also be null\n return node2\n \n return self.getTargetCopy(node1.left, node2.left, target) or self.getTargetCopy(node1.right, node2.right, target)", "slug": "find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree", "post_title": "Python Simple 2 approaches - Recursion(3 liner) and Morris", "user": "constantine786", "upvotes": 20, "views": 1900, "problem_title": "find a corresponding node of a binary tree in a clone of that tree", "number": 1379, "acceptance": 0.87, "difficulty": "Easy", "__index_level_0__": 20688, "question": "Given two binary trees original and cloned and given a reference to a node target in the original tree.\nThe cloned tree is a copy of the original tree.\nReturn a reference to the same node in the cloned tree.\nNote that you are not allowed to change any of the two trees or the target node and the answer must be a reference to a node in the cloned tree.\n Example 1:\nInput: tree = [7,4,3,null,null,6,19], target = 3\nOutput: 3\nExplanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.\nExample 2:\nInput: tree = [7], target = 7\nOutput: 7\nExample 3:\nInput: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\nOutput: 4\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\nThe values of the nodes of the tree are unique.\ntarget node is a node from the original tree and is not null.\n Follow up: Could you solve the problem if repeated values on the tree are allowed?" }, { "post_href": "https://leetcode.com/problems/lucky-numbers-in-a-matrix/discuss/539748/Python3-store-row-min-and-column-max", "python_solutions": "class Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n rmin = [min(x) for x in matrix]\n cmax = [max(x) for x in zip(*matrix)]\n return [matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[0])) if rmin[i] == cmax[j]]", "slug": "lucky-numbers-in-a-matrix", "post_title": "[Python3] store row min & column max", "user": "ye15", "upvotes": 9, "views": 1500, "problem_title": "lucky numbers in a matrix", "number": 1380, "acceptance": 0.705, "difficulty": "Easy", "__index_level_0__": 20716, "question": "Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.\nA lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column.\n Example 1:\nInput: matrix = [[3,7,8],[9,11,13],[15,16,17]]\nOutput: [15]\nExplanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.\nExample 2:\nInput: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\nOutput: [12]\nExplanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.\nExample 3:\nInput: matrix = [[7,8],[1,2]]\nOutput: [7]\nExplanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= n, m <= 50\n1 <= matrix[i][j] <= 105.\nAll elements in the matrix are distinct." }, { "post_href": "https://leetcode.com/problems/balance-a-binary-search-tree/discuss/539780/Python3-collect-values-and-reconstruct-bst-recursively", "python_solutions": "class Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n \n def dfs(node):\n \"\"\"inorder depth-first traverse bst\"\"\"\n if not node: return \n dfs(node.left)\n value.append(node.val)\n dfs(node.right)\n \n value = [] #collect values\n dfs(root)\n \n def tree(lo, hi): \n if lo > hi: return None\n mid = (lo + hi)//2\n ans = TreeNode(value[mid])\n ans.left = tree(lo, mid-1)\n ans.right = tree(mid+1, hi)\n return ans\n \n return tree(0, len(value)-1)", "slug": "balance-a-binary-search-tree", "post_title": "[Python3] collect values & reconstruct bst recursively", "user": "ye15", "upvotes": 6, "views": 363, "problem_title": "balance a binary search tree", "number": 1382, "acceptance": 0.807, "difficulty": "Medium", "__index_level_0__": 20751, "question": "Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them.\nA binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.\n Example 1:\nInput: root = [1,null,2,null,3,null,4,null,null]\nOutput: [2,1,3,null,null,null,4]\nExplanation: This is not the only correct answer, [3,1,4,null,2] is also correct.\nExample 2:\nInput: root = [2,1,3]\nOutput: [2,1,3]\n Constraints:\nThe number of nodes in the tree is in the range [1, 104].\n1 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-performance-of-a-team/discuss/741822/Met-this-problem-in-my-interview!!!-(Python3-greedy-with-heap)", "python_solutions": "class Solution:\n def maxPerformance_simple(self, n, speed, efficiency):\n \n people = sorted(zip(speed, efficiency), key=lambda x: -x[1])\n \n result, sum_speed = 0, 0\n \n for s, e in people:\n sum_speed += s\n result = max(result, sum_speed * e)\n \n return result # % 1000000007", "slug": "maximum-performance-of-a-team", "post_title": "Met this problem in my interview!!! (Python3 greedy with heap)", "user": "dashidhy", "upvotes": 58, "views": 2500, "problem_title": "maximum performance of a team", "number": 1383, "acceptance": 0.489, "difficulty": "Hard", "__index_level_0__": 20764, "question": "You are given two integers n and k and two integer arrays speed and efficiency both of length n. There are n engineers numbered from 1 to n. speed[i] and efficiency[i] represent the speed and efficiency of the ith engineer respectively.\nChoose at most k different engineers out of the n engineers to form a team with the maximum performance.\nThe performance of a team is the sum of its engineers' speeds multiplied by the minimum efficiency among its engineers.\nReturn the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.\n Example 1:\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\nOutput: 60\nExplanation: \nWe have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\nExample 2:\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\nOutput: 68\nExplanation:\nThis is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\nExample 3:\nInput: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\nOutput: 72\n Constraints:\n1 <= k <= n <= 105\nspeed.length == n\nefficiency.length == n\n1 <= speed[i] <= 105\n1 <= efficiency[i] <= 108" }, { "post_href": "https://leetcode.com/problems/find-the-distance-value-between-two-arrays/discuss/2015283/python-3-oror-simple-binary-search-solution", "python_solutions": "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n n = len(arr2)\n arr2.sort()\n res = 0\n \n for num in arr1:\n low, high = 0, n - 1\n while low <= high:\n mid = (low + high) // 2\n if abs(num - arr2[mid]) <= d:\n break\n elif num < arr2[mid]:\n high = mid - 1\n else:\n low = mid + 1\n else:\n res += 1\n \n return res", "slug": "find-the-distance-value-between-two-arrays", "post_title": "python 3 || simple binary search solution", "user": "dereky4", "upvotes": 4, "views": 298, "problem_title": "find the distance value between two arrays", "number": 1385, "acceptance": 0.654, "difficulty": "Easy", "__index_level_0__": 20782, "question": "Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.\nThe distance value is defined as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <= d.\n Example 1:\nInput: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\nOutput: 2\nExplanation: \nFor arr1[0]=4 we have: \n|4-10|=6 > d=2 \n|4-9|=5 > d=2 \n|4-1|=3 > d=2 \n|4-8|=4 > d=2 \nFor arr1[1]=5 we have: \n|5-10|=5 > d=2 \n|5-9|=4 > d=2 \n|5-1|=4 > d=2 \n|5-8|=3 > d=2\nFor arr1[2]=8 we have:\n|8-10|=2 <= d=2\n|8-9|=1 <= d=2\n|8-1|=7 > d=2\n|8-8|=0 <= d=2\nExample 2:\nInput: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\nOutput: 2\nExample 3:\nInput: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\nOutput: 1\n Constraints:\n1 <= arr1.length, arr2.length <= 500\n-1000 <= arr1[i], arr2[j] <= 1000\n0 <= d <= 100" }, { "post_href": "https://leetcode.com/problems/cinema-seat-allocation/discuss/1124736/Python3-bitmask", "python_solutions": "class Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n seats = {}\n for i, j in reservedSeats: \n if i not in seats: seats[i] = 0\n seats[i] |= 1 << j-1\n \n ans = 2 * (n - len(seats))\n for v in seats.values(): \n if not int(\"0111111110\", 2) & v: ans += 2\n elif not int(\"0111100000\", 2) & v: ans += 1\n elif not int(\"0001111000\", 2) & v: ans += 1\n elif not int(\"0000011110\", 2) & v: ans += 1\n return ans", "slug": "cinema-seat-allocation", "post_title": "[Python3] bitmask", "user": "ye15", "upvotes": 3, "views": 256, "problem_title": "cinema seat allocation", "number": 1386, "acceptance": 0.409, "difficulty": "Medium", "__index_level_0__": 20818, "question": "A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.\nGiven the array reservedSeats containing the numbers of seats already reserved, for example, reservedSeats[i] = [3,8] means the seat located in row 3 and labelled with 8 is already reserved.\nReturn the maximum number of four-person groups you can assign on the cinema seats. A four-person group occupies four adjacent seats in one single row. Seats across an aisle (such as [3,3] and [3,4]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.\n Example 1:\nInput: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\nOutput: 4\nExplanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.\nExample 2:\nInput: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\nOutput: 2\nExample 3:\nInput: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\nOutput: 4\n Constraints:\n1 <= n <= 10^9\n1 <= reservedSeats.length <= min(10*n, 10^4)\nreservedSeats[i].length == 2\n1 <= reservedSeats[i][0] <= n\n1 <= reservedSeats[i][1] <= 10\nAll reservedSeats[i] are distinct." }, { "post_href": "https://leetcode.com/problems/sort-integers-by-the-power-value/discuss/1597631/Python-using-sorted-function", "python_solutions": "class Solution:\n def getpower(self,num):\n p=0\n while(num!=1):\n if num%2==0:\n num=num//2\n \n else:\n num=(3*num)+1\n p+=1\n \n return p\n \n def getKth(self, lo: int, hi: int, k: int) -> int:\n \n temp=sorted(range(lo,hi+1),key=lambda x:self.getpower(x))\n return temp[k-1]\n\t\t```", "slug": "sort-integers-by-the-power-value", "post_title": "Python using sorted function", "user": "PrimeOp", "upvotes": 1, "views": 118, "problem_title": "sort integers by the power value", "number": 1387, "acceptance": 0.7, "difficulty": "Medium", "__index_level_0__": 20825, "question": "The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:\nif x is even then x = x / 2\nif x is odd then x = 3 * x + 1\nFor example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).\nGiven three integers lo, hi and k. The task is to sort all integers in the interval [lo, hi] by the power value in ascending order, if two or more integers have the same power value sort them by ascending order.\nReturn the kth integer in the range [lo, hi] sorted by the power value.\nNotice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform into 1 using these steps and that the power of x is will fit in a 32-bit signed integer.\n Example 1:\nInput: lo = 12, hi = 15, k = 2\nOutput: 13\nExplanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\nThe power of 13 is 9\nThe power of 14 is 17\nThe power of 15 is 17\nThe interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\nNotice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.\nExample 2:\nInput: lo = 7, hi = 11, k = 4\nOutput: 7\nExplanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\nThe interval sorted by power is [8, 10, 11, 7, 9].\nThe fourth number in the sorted array is 7.\n Constraints:\n1 <= lo <= hi <= 1000\n1 <= k <= hi - lo + 1" }, { "post_href": "https://leetcode.com/problems/pizza-with-3n-slices/discuss/1124752/Python3-top-down-dp", "python_solutions": "class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n \n @cache\n def fn(i, k, first): \n \"\"\"Return max sum of k pieces from slices[i:].\"\"\"\n if k == 0: return 0 \n if i >= len(slices) or first and i == len(slices)-1: return -inf \n if i == 0: return max(fn(i+1, k, False), slices[i] + fn(i+2, k-1, True))\n return max(fn(i+1, k, first), slices[i] + fn(i+2, k-1, first))\n \n return fn(0, len(slices)//3, None)", "slug": "pizza-with-3n-slices", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 236, "problem_title": "pizza with 3n slices", "number": 1388, "acceptance": 0.501, "difficulty": "Hard", "__index_level_0__": 20852, "question": "There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\nYou will pick any pizza slice.\nYour friend Alice will pick the next slice in the anti-clockwise direction of your pick.\nYour friend Bob will pick the next slice in the clockwise direction of your pick.\nRepeat until there are no more slices of pizzas.\nGiven an integer array slices that represent the sizes of the pizza slices in a clockwise direction, return the maximum possible sum of slice sizes that you can pick.\n Example 1:\nInput: slices = [1,2,3,4,5,6]\nOutput: 10\nExplanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\nExample 2:\nInput: slices = [8,9,8,6,1,1]\nOutput: 16\nExplanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n Constraints:\n3 * n == slices.length\n1 <= slices.length <= 500\n1 <= slices[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/create-target-array-in-the-given-order/discuss/1163965/Python3-Simple-Solution", "python_solutions": "class Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n ans = []\n \n for i in range(len(nums)):\n ans.insert(index[i] , nums[i])\n \n return ans", "slug": "create-target-array-in-the-given-order", "post_title": "[Python3] Simple Solution", "user": "VoidCupboard", "upvotes": 5, "views": 252, "problem_title": "create target array in the given order", "number": 1389, "acceptance": 0.8590000000000001, "difficulty": "Easy", "__index_level_0__": 20857, "question": "Given two arrays of integers nums and index. Your task is to create target array under the following rules:\nInitially target array is empty.\nFrom left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.\nRepeat the previous step until there are no elements to read in nums and index.\nReturn the target array.\nIt is guaranteed that the insertion operations will be valid.\n Example 1:\nInput: nums = [0,1,2,3,4], index = [0,1,2,2,1]\nOutput: [0,4,1,3,2]\nExplanation:\nnums index target\n0 0 [0]\n1 1 [0,1]\n2 2 [0,1,2]\n3 2 [0,1,3,2]\n4 1 [0,4,1,3,2]\nExample 2:\nInput: nums = [1,2,3,4,0], index = [0,1,2,3,0]\nOutput: [0,1,2,3,4]\nExplanation:\nnums index target\n1 0 [1]\n2 1 [1,2]\n3 2 [1,2,3]\n4 3 [1,2,3,4]\n0 0 [0,1,2,3,4]\nExample 3:\nInput: nums = [1], index = [0]\nOutput: [1]\n Constraints:\n1 <= nums.length, index.length <= 100\nnums.length == index.length\n0 <= nums[i] <= 100\n0 <= index[i] <= i" }, { "post_href": "https://leetcode.com/problems/four-divisors/discuss/547308/Python3-Short-Easy-Solution", "python_solutions": "class Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n res = 0\n for num in nums:\n divisor = set() \n for i in range(1, floor(sqrt(num)) + 1):\n if num % i == 0:\n divisor.add(num//i)\n divisor.add(i)\n if len(divisor) > 4: \n break\n \n if len(divisor) == 4:\n res += sum(divisor)\n return res", "slug": "four-divisors", "post_title": "[Python3] Short Easy Solution", "user": "localhostghost", "upvotes": 22, "views": 2500, "problem_title": "four divisors", "number": 1390, "acceptance": 0.413, "difficulty": "Medium", "__index_level_0__": 20910, "question": "Given an integer array nums, return the sum of divisors of the integers in that array that have exactly four divisors. If there is no such integer in the array, return 0.\n Example 1:\nInput: nums = [21,4,7]\nOutput: 32\nExplanation: \n21 has 4 divisors: 1, 3, 7, 21\n4 has 3 divisors: 1, 2, 4\n7 has 2 divisors: 1, 7\nThe answer is the sum of divisors of 21 only.\nExample 2:\nInput: nums = [21,21]\nOutput: 64\nExample 3:\nInput: nums = [1,2,3,4,5]\nOutput: 0\n Constraints:\n1 <= nums.length <= 104\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/check-if-there-is-a-valid-path-in-a-grid/discuss/635713/Python3-dfs-solution-Check-if-There-is-a-Valid-Path-in-a-Grid", "python_solutions": "class Solution:\n directions = [[-1, 0], [0, 1], [1, 0], [0, -1]]\n streetDirections = {\n 1: [1, 3],\n 2: [0, 2],\n 3: [2, 3],\n 4: [1, 2],\n 5: [0, 3],\n 6: [0, 1]\n }\n def hasValidPath(self, grid: List[List[int]]) -> bool:\n m, n = len(grid), len(grid[0])\n def dfs(i: int, j: int, oppositeDirection: int) -> None:\n if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] < 0:\n return\n v = grid[i][j]\n sd = Solution.streetDirections[v]\n direction = (oppositeDirection + 2) % 4\n if direction not in sd:\n return\n grid[i][j] = -v\n for d in sd:\n delta = Solution.directions[d]\n dfs(i+delta[0], j+delta[1], d)\n dfs(0, 0, 0)\n dfs(0, 0, 3)\n return grid[m-1][n-1] < 0", "slug": "check-if-there-is-a-valid-path-in-a-grid", "post_title": "Python3 dfs solution - Check if There is a Valid Path in a Grid", "user": "r0bertz", "upvotes": 2, "views": 391, "problem_title": "check if there is a valid path in a grid", "number": 1391, "acceptance": 0.472, "difficulty": "Medium", "__index_level_0__": 20912, "question": "You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:\n1 which means a street connecting the left cell and the right cell.\n2 which means a street connecting the upper cell and the lower cell.\n3 which means a street connecting the left cell and the lower cell.\n4 which means a street connecting the right cell and the lower cell.\n5 which means a street connecting the left cell and the upper cell.\n6 which means a street connecting the right cell and the upper cell.\nYou will initially start at the street of the upper-left cell (0, 0). A valid path in the grid is a path that starts from the upper left cell (0, 0) and ends at the bottom-right cell (m - 1, n - 1). The path should only follow the streets.\nNotice that you are not allowed to change any street.\nReturn true if there is a valid path in the grid or false otherwise.\n Example 1:\nInput: grid = [[2,4,3],[6,5,2]]\nOutput: true\nExplanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).\nExample 2:\nInput: grid = [[1,2,1],[1,2,1]]\nOutput: false\nExplanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)\nExample 3:\nInput: grid = [[1,1,2]]\nOutput: false\nExplanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 300\n1 <= grid[i][j] <= 6" }, { "post_href": "https://leetcode.com/problems/longest-happy-prefix/discuss/2814375/Dynamic-programming-solution", "python_solutions": "class Solution:\n def longestPrefix(self, s: str) -> str:\n n = [0] + [None] * (len(s) - 1)\n\n for i in range(1, len(s)):\n k = n[i - 1] # trying length k + 1\n while (k > 0) and (s[i] != s[k]):\n k = n[k - 1]\n if s[i] == s[k]:\n k += 1\n n[i] = k\n happy_border = n[-1]\n return s[:happy_border]", "slug": "longest-happy-prefix", "post_title": "Dynamic programming solution", "user": "aknyazev87", "upvotes": 1, "views": 24, "problem_title": "longest happy prefix", "number": 1392, "acceptance": 0.45, "difficulty": "Hard", "__index_level_0__": 20919, "question": "A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).\nGiven a string s, return the longest happy prefix of s. Return an empty string \"\" if no such prefix exists.\n Example 1:\nInput: s = \"level\"\nOutput: \"l\"\nExplanation: s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".\nExample 2:\nInput: s = \"ababab\"\nOutput: \"abab\"\nExplanation: \"abab\" is the largest prefix which is also suffix. They can overlap in the original string.\n Constraints:\n1 <= s.length <= 105\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/find-lucky-integer-in-an-array/discuss/2103066/PYTHON-or-Simple-python-solution", "python_solutions": "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n \n charMap = {}\n \n for i in arr:\n charMap[i] = 1 + charMap.get(i, 0)\n \n res = []\n \n for i in charMap:\n if charMap[i] == i:\n res.append(i)\n \n res = sorted(res) \n \n if len(res) > 0:\n return res[-1]\n \n return -1", "slug": "find-lucky-integer-in-an-array", "post_title": "PYTHON | Simple python solution", "user": "shreeruparel", "upvotes": 1, "views": 145, "problem_title": "find lucky integer in an array", "number": 1394, "acceptance": 0.636, "difficulty": "Easy", "__index_level_0__": 20928, "question": "Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.\nReturn the largest lucky integer in the array. If there is no lucky integer return -1.\n Example 1:\nInput: arr = [2,2,3,4]\nOutput: 2\nExplanation: The only lucky number in the array is 2 because frequency[2] == 2.\nExample 2:\nInput: arr = [1,2,2,3,3,3]\nOutput: 3\nExplanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\nExample 3:\nInput: arr = [2,2,2,3,3]\nOutput: -1\nExplanation: There are no lucky numbers in the array.\n Constraints:\n1 <= arr.length <= 500\n1 <= arr[i] <= 500" }, { "post_href": "https://leetcode.com/problems/count-number-of-teams/discuss/1465532/Python-or-O(n2)-or-Slow-but-very-easy-to-understand-or-Explanation", "python_solutions": "class Solution:\n def numTeams(self, rating: List[int]) -> int:\n \n dp = [[1, 0, 0] for i in range(len(rating))]\n \n for i in range(1, len(rating)):\n for j in range(i):\n if rating[i] > rating[j]:\n dp[i][1] += dp[j][0]\n dp[i][2] += dp[j][1]\n \n a = sum(dp[i][2] for i in range(len(dp)))\n #print(a)\n\n dp = [[1, 0, 0] for i in range(len(rating))]\n \n for i in range(1, len(rating)):\n for j in range(i):\n if rating[i] < rating[j]:\n dp[i][1] += dp[j][0]\n dp[i][2] += dp[j][1]\n \n b = sum(dp[i][2] for i in range(len(dp)))\n \n return a + b", "slug": "count-number-of-teams", "post_title": "Python | O(n^2) | Slow but very easy to understand | Explanation", "user": "detective_dp", "upvotes": 5, "views": 595, "problem_title": "count number of teams", "number": 1395, "acceptance": 0.68, "difficulty": "Medium", "__index_level_0__": 20963, "question": "There are n soldiers standing in a line. Each soldier is assigned a unique rating value.\nYou have to form a team of 3 soldiers amongst them under the following rules:\nChoose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).\nA team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).\nReturn the number of teams you can form given the conditions. (soldiers can be part of multiple teams).\n Example 1:\nInput: rating = [2,5,3,4,1]\nOutput: 3\nExplanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). \nExample 2:\nInput: rating = [2,1,3]\nOutput: 0\nExplanation: We can't form any team given the conditions.\nExample 3:\nInput: rating = [1,2,3,4]\nOutput: 4\n Constraints:\nn == rating.length\n3 <= n <= 1000\n1 <= rating[i] <= 105\nAll the integers in rating are unique." }, { "post_href": "https://leetcode.com/problems/find-all-good-strings/discuss/1133347/Python3-dp-and-kmp-...-finally", "python_solutions": "class Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n lps = [0]\n k = 0 \n for i in range(1, len(evil)): \n while k and evil[k] != evil[i]: k = lps[k-1]\n if evil[k] == evil[i]: k += 1\n lps.append(k)\n \n @cache\n def fn(i, k, lower, upper): \n \"\"\"Return number of good strings at position i and k prefix match.\"\"\"\n if k == len(evil): return 0 # boundary condition \n if i == n: return 1 \n lo = ascii_lowercase.index(s1[i]) if lower else 0\n hi = ascii_lowercase.index(s2[i]) if upper else 25\n \n ans = 0\n for x in range(lo, hi+1): \n kk = k \n while kk and evil[kk] != ascii_lowercase[x]: \n kk = lps[kk-1]\n if evil[kk] == ascii_lowercase[x]: kk += 1\n ans += fn(i+1, kk, lower and x == lo, upper and x == hi)\n return ans \n \n return fn(0, 0, True, True) % 1_000_000_007", "slug": "find-all-good-strings", "post_title": "[Python3] dp & kmp ... finally", "user": "ye15", "upvotes": 3, "views": 351, "problem_title": "find all good strings", "number": 1397, "acceptance": 0.422, "difficulty": "Hard", "__index_level_0__": 20973, "question": "Given the strings s1 and s2 of size n and the string evil, return the number of good strings.\nA good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.\n Example 1:\nInput: n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\nOutput: 51 \nExplanation: There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\". \nExample 2:\nInput: n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\nOutput: 0 \nExplanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.\nExample 3:\nInput: n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\nOutput: 2\n Constraints:\ns1.length == n\ns2.length == n\ns1 <= s2\n1 <= n <= 500\n1 <= evil.length <= 50\nAll strings consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/count-largest-group/discuss/660765/Python-DP-O(N)-99100", "python_solutions": "class Solution:\n\n def countLargestGroup(self, n: int) -> int:\n dp = {0: 0}\n counts = [0] * (4 * 9)\n for i in range(1, n + 1):\n quotient, reminder = divmod(i, 10)\n dp[i] = reminder + dp[quotient]\n counts[dp[i] - 1] += 1\n\n return counts.count(max(counts))", "slug": "count-largest-group", "post_title": "Python DP O(N) 99%/100%", "user": "xshoan", "upvotes": 43, "views": 2000, "problem_title": "count largest group", "number": 1399, "acceptance": 0.672, "difficulty": "Easy", "__index_level_0__": 20975, "question": "You are given an integer n.\nEach number from 1 to n is grouped according to the sum of its digits.\nReturn the number of groups that have the largest size.\n Example 1:\nInput: n = 13\nOutput: 4\nExplanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:\n[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].\nThere are 4 groups with largest size.\nExample 2:\nInput: n = 2\nOutput: 2\nExplanation: There are 2 groups [1], [2] of size 1.\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/construct-k-palindrome-strings/discuss/1806250/Python-Solution", "python_solutions": "class Solution:\n def canConstruct(self, s: str, k: int) -> bool:\n if k > len(s):\n return False\n dic = {}\n \n for i in s:\n if i not in dic:\n dic[i] = 1\n else:\n dic[i] += 1\n c = 0 \n for i in dic.values():\n if i % 2 == 1:\n c += 1\n \n if c > k:\n return False\n return True", "slug": "construct-k-palindrome-strings", "post_title": "Python Solution", "user": "MS1301", "upvotes": 1, "views": 91, "problem_title": "construct k palindrome strings", "number": 1400, "acceptance": 0.632, "difficulty": "Medium", "__index_level_0__": 20995, "question": "Given a string s and an integer k, return true if you can use all the characters in s to construct k palindrome strings or false otherwise.\n Example 1:\nInput: s = \"annabelle\", k = 2\nOutput: true\nExplanation: You can construct two palindromes using all characters in s.\nSome possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"\nExample 2:\nInput: s = \"leetcode\", k = 3\nOutput: false\nExplanation: It is impossible to construct 3 palindromes using all the characters of s.\nExample 3:\nInput: s = \"true\", k = 4\nOutput: true\nExplanation: The only possible solution is to put each character in a separate string.\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters.\n1 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/circle-and-rectangle-overlapping/discuss/639682/Python3-two-solutions-Circle-and-Rectangle-Overlapping", "python_solutions": "class Solution:\n def checkOverlap(self, radius: int, x_center: int, y_center: int, x1: int, y1: int, x2: int, y2: int) -> bool:\n x = 0 if x1 <= x_center <= x2 else min(abs(x1-x_center), abs(x2-x_center))\n y = 0 if y1 <= y_center <= y2 else min(abs(y1-y_center), abs(y2-y_center))\n return x**2 + y**2 <= radius**2", "slug": "circle-and-rectangle-overlapping", "post_title": "Python3 two solutions - Circle and Rectangle Overlapping", "user": "r0bertz", "upvotes": 2, "views": 386, "problem_title": "circle and rectangle overlapping", "number": 1401, "acceptance": 0.442, "difficulty": "Medium", "__index_level_0__": 21001, "question": "You are given a circle represented as (radius, xCenter, yCenter) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle.\nReturn true if the circle and rectangle are overlapped otherwise return false. In other words, check if there is any point (xi, yi) that belongs to the circle and the rectangle at the same time.\n Example 1:\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\nOutput: true\nExplanation: Circle and rectangle share the point (1,0).\nExample 2:\nInput: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\nOutput: false\nExample 3:\nInput: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\nOutput: true\n Constraints:\n1 <= radius <= 2000\n-104 <= xCenter, yCenter <= 104\n-104 <= x1 < x2 <= 104\n-104 <= y1 < y2 <= 104" }, { "post_href": "https://leetcode.com/problems/reducing-dishes/discuss/2152786/python-3-oror-simple-sorting-solution", "python_solutions": "class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort(reverse=True)\n maxSatisfaction = dishSum = 0\n\n for dish in satisfaction:\n dishSum += dish\n if dishSum <= 0:\n break\n maxSatisfaction += dishSum\n \n return maxSatisfaction", "slug": "reducing-dishes", "post_title": "python 3 || simple sorting solution", "user": "dereky4", "upvotes": 1, "views": 102, "problem_title": "reducing dishes", "number": 1402, "acceptance": 0.72, "difficulty": "Hard", "__index_level_0__": 21005, "question": "A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.\nLike-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].\nReturn the maximum sum of like-time coefficient that the chef can obtain after preparing some amount of dishes.\nDishes can be prepared in any order and the chef can discard some dishes to get this maximum value.\n Example 1:\nInput: satisfaction = [-1,-8,0,5,-9]\nOutput: 14\nExplanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).\nEach dish is prepared in one unit of time.\nExample 2:\nInput: satisfaction = [4,3,2]\nOutput: 20\nExplanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)\nExample 3:\nInput: satisfaction = [-1,-4,-5]\nOutput: 0\nExplanation: People do not like the dishes. No dish is prepared.\n Constraints:\nn == satisfaction.length\n1 <= n <= 500\n-1000 <= satisfaction[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/discuss/1041468/Python3-simple-solution", "python_solutions": "class Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n nums.sort()\n l = []\n while sum(l) <= sum(nums):\n l.append(nums.pop())\n return l", "slug": "minimum-subsequence-in-non-increasing-order", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 9, "views": 297, "problem_title": "minimum subsequence in non increasing order", "number": 1403, "acceptance": 0.721, "difficulty": "Easy", "__index_level_0__": 21020, "question": "Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. \nIf there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. \nNote that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.\n Example 1:\nInput: nums = [4,3,10,9,8]\nOutput: [10,9] \nExplanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements. \nExample 2:\nInput: nums = [4,4,7,6,7]\nOutput: [7,7,6] \nExplanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to be returned in non-increasing order. \n Constraints:\n1 <= nums.length <= 500\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/discuss/2809472/Python3-Solution-or-One-Line", "python_solutions": "class Solution:\n def numSteps(self, s):\n return len(s) + s.rstrip('0').count('0') + 2 * (s.count('1') != 1) - 1", "slug": "number-of-steps-to-reduce-a-number-in-binary-representation-to-one", "post_title": "\u2714 Python3 Solution | One Line", "user": "satyam2001", "upvotes": 1, "views": 98, "problem_title": "number of steps to reduce a number in binary representation to one", "number": 1404, "acceptance": 0.522, "difficulty": "Medium", "__index_level_0__": 21056, "question": "Given the binary representation of an integer as a string s, return the number of steps to reduce it to 1 under the following rules:\nIf the current number is even, you have to divide it by 2.\nIf the current number is odd, you have to add 1 to it.\nIt is guaranteed that you can always reach one for all test cases.\n Example 1:\nInput: s = \"1101\"\nOutput: 6\nExplanation: \"1101\" corressponds to number 13 in their decimal representation.\nStep 1) 13 is odd, add 1 and obtain 14. \nStep 2) 14 is even, divide by 2 and obtain 7.\nStep 3) 7 is odd, add 1 and obtain 8.\nStep 4) 8 is even, divide by 2 and obtain 4. \nStep 5) 4 is even, divide by 2 and obtain 2. \nStep 6) 2 is even, divide by 2 and obtain 1. \nExample 2:\nInput: s = \"10\"\nOutput: 1\nExplanation: \"10\" corressponds to number 2 in their decimal representation.\nStep 1) 2 is even, divide by 2 and obtain 1. \nExample 3:\nInput: s = \"1\"\nOutput: 0\n Constraints:\n1 <= s.length <= 500\ns consists of characters '0' or '1'\ns[0] == '1'" }, { "post_href": "https://leetcode.com/problems/longest-happy-string/discuss/1226968/Python-9-line-greedy-solution-by-using-Counter", "python_solutions": "class Solution:\n def longestDiverseString(self, a: int, b: int, c: int) -> str:\n count = collections.Counter({'a':a, 'b':b, 'c':c})\n res = ['#']\n while True:\n (a1, _), (a2, _) = count.most_common(2)\n \n if a1 == res[-1] == res[-2]:\n a1 = a2\n \n if not count[a1]:\n break\n \n res.append(a1)\n count[a1] -= 1 \n \n return ''.join(res[1:])", "slug": "longest-happy-string", "post_title": "[Python] 9-line greedy solution by using Counter", "user": "licpotis", "upvotes": 5, "views": 524, "problem_title": "longest happy string", "number": 1405, "acceptance": 0.574, "difficulty": "Medium", "__index_level_0__": 21069, "question": "A string s is called happy if it satisfies the following conditions:\ns only contains the letters 'a', 'b', and 'c'.\ns does not contain any of \"aaa\", \"bbb\", or \"ccc\" as a substring.\ns contains at most a occurrences of the letter 'a'.\ns contains at most b occurrences of the letter 'b'.\ns contains at most c occurrences of the letter 'c'.\nGiven three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string \"\".\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: a = 1, b = 1, c = 7\nOutput: \"ccaccbcc\"\nExplanation: \"ccbccacc\" would also be a correct answer.\nExample 2:\nInput: a = 7, b = 1, c = 0\nOutput: \"aabaa\"\nExplanation: It is the only correct answer in this case.\n Constraints:\n0 <= a, b, c <= 100\na + b + c > 0" }, { "post_href": "https://leetcode.com/problems/stone-game-iii/discuss/815655/Python3-beats-93-DP", "python_solutions": "class Solution(object):\n def stoneGameIII(self, stoneValue):\n \"\"\"\n :type stoneValue: List[int]\n :rtype: str\n \"\"\"\n \n dp = [0 for _ in range(len(stoneValue))]\n if len(dp) >= 1:\n dp[-1] = stoneValue[-1]\n if len(dp) >= 2:\n dp[-2] = max(stoneValue[-1] + stoneValue[-2], stoneValue[-2] - dp[-1])\n if len(dp) >= 3:\n dp[-3] = max(stoneValue[-3] + stoneValue[-1] + stoneValue[-2], stoneValue[-3] - dp[-2], stoneValue[-3] + stoneValue[-2] - dp[-1])\n \n for i in range(len(stoneValue) - 4, -1, -1):\n \n dp[i] = max([sum(stoneValue[i: i + j]) - dp[i + j] for j in range(1, 4)])\n \n if dp[0] > 0:\n return \"Alice\"\n if dp[0] == 0:\n return \"Tie\"\n return \"Bob\"", "slug": "stone-game-iii", "post_title": "Python3 beats 93% DP", "user": "ethuoaiesec", "upvotes": 4, "views": 166, "problem_title": "stone game iii", "number": 1406, "acceptance": 0.596, "difficulty": "Hard", "__index_level_0__": 21082, "question": "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.\nAlice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.\nThe score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.\nThe objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\nAssume Alice and Bob play optimally.\nReturn \"Alice\" if Alice will win, \"Bob\" if Bob will win, or \"Tie\" if they will end the game with the same score.\n Example 1:\nInput: stoneValue = [1,2,3,7]\nOutput: \"Bob\"\nExplanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\nExample 2:\nInput: stoneValue = [1,2,3,-9]\nOutput: \"Alice\"\nExplanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\nIf Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose.\nIf Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose.\nRemember that both play optimally so here Alice will choose the scenario that makes her win.\nExample 3:\nInput: stoneValue = [1,2,3,6]\nOutput: \"Tie\"\nExplanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n Constraints:\n1 <= stoneValue.length <= 5 * 104\n-1000 <= stoneValue[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/string-matching-in-an-array/discuss/575147/Clean-Python-3-suffix-trie-O(NlogN-%2B-N-*-S2)", "python_solutions": "class Solution:\n def stringMatching(self, words: List[str]) -> List[str]:\n def add(word: str):\n node = trie\n for c in word:\n node = node.setdefault(c, {})\n\n def get(word: str) -> bool:\n node = trie\n for c in word:\n if (node := node.get(c)) is None: return False\n return True\n\n words.sort(key=len, reverse=True)\n trie, result = {}, []\n for word in words:\n if get(word): result.append(word)\n for i in range(len(word)):\n add(word[i:])\n return result", "slug": "string-matching-in-an-array", "post_title": "Clean Python 3, suffix trie O(NlogN + N * S^2)", "user": "lenchen1112", "upvotes": 48, "views": 5500, "problem_title": "string matching in an array", "number": 1408, "acceptance": 0.639, "difficulty": "Easy", "__index_level_0__": 21089, "question": "Given an array of string words, return all strings in words that is a substring of another word. You can return the answer in any order.\nA substring is a contiguous sequence of characters within a string\n Example 1:\nInput: words = [\"mass\",\"as\",\"hero\",\"superhero\"]\nOutput: [\"as\",\"hero\"]\nExplanation: \"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n[\"hero\",\"as\"] is also a valid answer.\nExample 2:\nInput: words = [\"leetcode\",\"et\",\"code\"]\nOutput: [\"et\",\"code\"]\nExplanation: \"et\", \"code\" are substring of \"leetcode\".\nExample 3:\nInput: words = [\"blue\",\"green\",\"bu\"]\nOutput: []\nExplanation: No string of words is substring of another string.\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 30\nwords[i] contains only lowercase English letters.\nAll the strings of words are unique." }, { "post_href": "https://leetcode.com/problems/queries-on-a-permutation-with-key/discuss/1702309/Understandable-code-for-beginners-in-python!!!", "python_solutions": "class Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n permuteArr=[i for i in range(1,m+1)]\n query_len=len(queries)\n answer=[]\n left,right=[],[]\n for query in range(query_len):\n index=permuteArr.index(queries[query])\n answer.append(index)\n left=permuteArr[:index]\n right=permuteArr[index+1:]\n permuteArr=[permuteArr[index]]+left+right\n return answer", "slug": "queries-on-a-permutation-with-key", "post_title": "Understandable code for beginners in python!!!", "user": "kabiland", "upvotes": 1, "views": 46, "problem_title": "queries on a permutation with key", "number": 1409, "acceptance": 0.833, "difficulty": "Medium", "__index_level_0__": 21128, "question": "Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:\nIn the beginning, you have the permutation P=[1,2,3,...,m].\nFor the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].\nReturn an array containing the result for the given queries.\n Example 1:\nInput: queries = [3,1,2,1], m = 5\nOutput: [2,1,2,1] \nExplanation: The queries are processed as follow: \nFor i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. \nFor i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. \nFor i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. \nFor i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. \nTherefore, the array containing the result is [2,1,2,1]. \nExample 2:\nInput: queries = [4,1,2,2], m = 4\nOutput: [3,1,2,0]\nExample 3:\nInput: queries = [7,5,5,8,3], m = 8\nOutput: [6,5,0,7,5]\n Constraints:\n1 <= m <= 10^3\n1 <= queries.length <= m\n1 <= queries[i] <= m" }, { "post_href": "https://leetcode.com/problems/html-entity-parser/discuss/575248/Python-sol-by-replace-and-regex.-85%2B-w-Hint", "python_solutions": "class Solution:\n def entityParser(self, text: str) -> str:\n \n html_symbol = [ '&quot;', '&apos;', '&gt;', '&lt;', '&frasl;', '&amp;']\n formal_symbol = [ '\"', \"'\", '>', '<', '/', '&']\n \n for html_sym, formal_sym in zip(html_symbol, formal_symbol):\n text = text.replace( html_sym , formal_sym )\n \n return text", "slug": "html-entity-parser", "post_title": "Python sol by replace and regex. 85%+ [w/ Hint ]", "user": "brianchiang_tw", "upvotes": 11, "views": 740, "problem_title": "html entity parser", "number": 1410, "acceptance": 0.52, "difficulty": "Medium", "__index_level_0__": 21141, "question": "HTML entity parser is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.\nThe special characters and their entities for HTML are:\nQuotation Mark: the entity is " and symbol character is \".\nSingle Quote Mark: the entity is ' and symbol character is '.\nAmpersand: the entity is & and symbol character is &.\nGreater Than Sign: the entity is > and symbol character is >.\nLess Than Sign: the entity is < and symbol character is <.\nSlash: the entity is ⁄ and symbol character is /.\nGiven the input text string to the HTML parser, you have to implement the entity parser.\nReturn the text after replacing the entities by the special characters.\n Example 1:\nInput: text = \"& is an HTML entity but &ambassador; is not.\"\nOutput: \"& is an HTML entity but &ambassador; is not.\"\nExplanation: The parser will replace the & entity by &\nExample 2:\nInput: text = \"and I quote: "..."\"\nOutput: \"and I quote: \\\"...\\\"\"\n Constraints:\n1 <= text.length <= 105\nThe string may contain any possible characters out of all the 256 ASCII characters." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-paint-n-3-grid/discuss/1648004/dynamic-programming-32ms-beats-99.44-in-Python", "python_solutions": "class Solution:\n def numOfWays(self, n: int) -> int:\n mod = 10 ** 9 + 7\n two_color, three_color = 6, 6\n for _ in range(n - 1):\n two_color, three_color = (two_color * 3 + three_color * 2) % mod, (two_color * 2 + three_color * 2) % mod\n return (two_color + three_color) % mod", "slug": "number-of-ways-to-paint-n-3-grid", "post_title": "dynamic programming, 32ms, beats 99.44% in Python", "user": "kryuki", "upvotes": 2, "views": 205, "problem_title": "number of ways to paint n \u00d7 3 grid", "number": 1411, "acceptance": 0.623, "difficulty": "Hard", "__index_level_0__": 21149, "question": "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).\nGiven n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.\n Example 1:\nInput: n = 1\nOutput: 12\nExplanation: There are 12 possible way to paint the grid as shown.\nExample 2:\nInput: n = 5000\nOutput: 30228214\n Constraints:\nn == grid.length\n1 <= n <= 5000" }, { "post_href": "https://leetcode.com/problems/minimum-value-to-get-positive-step-by-step-sum/discuss/1431774/2-Lines-Easy-Python-Solution", "python_solutions": "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n \n for i in range(1, len(nums)): nums[i] = nums[i] + nums[i - 1]\n \n return 1 if min(nums) >= 1 else abs(min(nums)) + 1", "slug": "minimum-value-to-get-positive-step-by-step-sum", "post_title": "2 Lines Easy Python Solution", "user": "caffreyu", "upvotes": 5, "views": 305, "problem_title": "minimum value to get positive step by step sum", "number": 1413, "acceptance": 0.68, "difficulty": "Easy", "__index_level_0__": 21154, "question": "Given an array of integers nums, you start with an initial positive value startValue.\nIn each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).\nReturn the minimum positive value of startValue such that the step by step sum is never less than 1.\n Example 1:\nInput: nums = [-3,2,-3,4,2]\nOutput: 5\nExplanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\nstep by step sum\nstartValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2\nExample 2:\nInput: nums = [1,2]\nOutput: 1\nExplanation: Minimum start value should be positive. \nExample 3:\nInput: nums = [1,-2,-3]\nOutput: 5\n Constraints:\n1 <= nums.length <= 100\n-100 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/discuss/1341772/Python3-easy-solution-using-recursion", "python_solutions": "class Solution:\n def findMinFibonacciNumbers(self, n: int) -> int:\n def check(z):\n key = [1,1]\n while key[-1] + key[-2] <= z:\n key.append(key[-1]+key[-2])\n print(key,z)\n if z in key:\n return 1\n return 1 + check(z-key[-1])\n return check(n)", "slug": "find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k", "post_title": "Python3 easy solution using recursion", "user": "EklavyaJoshi", "upvotes": 1, "views": 333, "problem_title": "find the minimum number of fibonacci numbers whose sum is k", "number": 1414, "acceptance": 0.654, "difficulty": "Medium", "__index_level_0__": 21193, "question": "Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.\nThe Fibonacci numbers are defined as:\nF1 = 1\nF2 = 1\nFn = Fn-1 + Fn-2 for n > 2.\nIt is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.\n Example 1:\nInput: k = 7\nOutput: 2 \nExplanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \nFor k = 7 we can use 2 + 5 = 7.\nExample 2:\nInput: k = 10\nOutput: 2 \nExplanation: For k = 10 we can use 2 + 8 = 10.\nExample 3:\nInput: k = 19\nOutput: 3 \nExplanation: For k = 19 we can use 1 + 5 + 13 = 19.\n Constraints:\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/1420200/Python3-or-Ez-for-loop-solves-ALL!-With-detailed-comments-and-graphical-examples", "python_solutions": "class Solution:\n def getHappyString(self, n: int, k: int) -> str:\n \n char = [\"a\", \"b\", \"c\"] \n \n # Edge case, n = 1\n if n == 1: return char[k - 1] if k <= 3 else \"\"\n \n # There will be $part$ number of strings starting with each character (a, b, c)\n part = 2 ** (n - 1)\n \n # If k is too large\n if k > part * 3: return \"\"\n \n res = []\n \n # Edge case is k = n * i, where i is an integer in range [1, 3]\n res.append(char[k // part if k % part != 0 else k // part - 1])\n k = k % part if k % part != 0 else part\n \n for i in range(n - 2, -1, -1):\n char = [\"a\", \"b\", \"c\"] \n char.remove(res[-1]) # Make sure the adjacent characters will be different\n \n if len(res) + 1 == n: # Edge case, assigning the last element\n if k == 1: res.append(char[0])\n elif k == 2: res.append(char[-1])\n elif k > 2 ** i: # Go to the right side\n res.append(char[-1])\n k -= 2 ** i \n else: res.append(char[0]) # Go to the left side\n \n return \"\".join(res)", "slug": "the-k-th-lexicographical-string-of-all-happy-strings-of-length-n", "post_title": "Python3 | Ez for loop solves ALL! With detailed comments and graphical examples", "user": "caffreyu", "upvotes": 2, "views": 73, "problem_title": "the k th lexicographical string of all happy strings of length n", "number": 1415, "acceptance": 0.721, "difficulty": "Medium", "__index_level_0__": 21202, "question": "A happy string is a string that:\nconsists only of letters of the set ['a', 'b', 'c'].\ns[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).\nFor example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings.\nGiven two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.\nReturn the kth string of this list or return an empty string if there are less than k happy strings of length n.\n Example 1:\nInput: n = 1, k = 3\nOutput: \"c\"\nExplanation: The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".\nExample 2:\nInput: n = 1, k = 4\nOutput: \"\"\nExplanation: There are only 3 happy strings of length 1.\nExample 3:\nInput: n = 3, k = 9\nOutput: \"cab\"\nExplanation: There are 12 different happy string of length 3 [\"aba\", \"abc\", \"aca\", \"acb\", \"bab\", \"bac\", \"bca\", \"bcb\", \"cab\", \"cac\", \"cba\", \"cbc\"]. You will find the 9th string = \"cab\"\n Constraints:\n1 <= n <= 10\n1 <= k <= 100" }, { "post_href": "https://leetcode.com/problems/restore-the-array/discuss/1165871/python-or-simple-dp", "python_solutions": "class Solution(object):\n def numberOfArrays(self, s, k):\n n=len(s)\n new=[0]*n\n new[0]=1\n m=len(str(k))\n for i in range(1,n):\n for j in range(max(0,i-m+1),i+1):\n if s[j]!=\"0\" and int(s[j:i+1])<=k:\n if j==0:\n new[i]=1\n else:\n new[i]+=new[j-1]\n #print(new)\n \n return new[-1]%(10**9+7)", "slug": "restore-the-array", "post_title": "python | simple dp", "user": "heisenbarg", "upvotes": 1, "views": 185, "problem_title": "restore the array", "number": 1416, "acceptance": 0.3879999999999999, "difficulty": "Hard", "__index_level_0__": 21218, "question": "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 s and all we know is that all integers in the array were in the range [1, k] and there are no leading zeros in the array.\nGiven the string s and the integer k, return the number of the possible arrays that can be printed as s using the mentioned program. Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\nInput: s = \"1000\", k = 10000\nOutput: 1\nExplanation: The only possible array is [1000]\nExample 2:\nInput: s = \"1000\", k = 10\nOutput: 0\nExplanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\nExample 3:\nInput: s = \"1317\", k = 2000\nOutput: 8\nExplanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n Constraints:\n1 <= s.length <= 105\ns consists of only digits and does not contain leading zeros.\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/reformat-the-string/discuss/1863653/Python3-Solution", "python_solutions": "class Solution:\n def reformat(self, s: str) -> str:\n nums, chars = [], []\n [(chars, nums)[char.isdigit()].append(str(char)) for char in s]\n nums_len, chars_len = len(nums), len(chars)\n if 2 > nums_len - chars_len > -2:\n a, b = ((chars, nums), (nums, chars))[nums_len > chars_len]\n return reduce(lambda x, y: x + y[0] + y[1], itertools.zip_longest(a, b, fillvalue=''), '')\n return ''", "slug": "reformat-the-string", "post_title": "Python3 Solution", "user": "hgalytoby", "upvotes": 1, "views": 62, "problem_title": "reformat the string", "number": 1417, "acceptance": 0.556, "difficulty": "Easy", "__index_level_0__": 21220, "question": "You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).\nYou have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.\nReturn the reformatted string or return an empty string if it is impossible to reformat the string.\n Example 1:\nInput: s = \"a0b1c2\"\nOutput: \"0a1b2c\"\nExplanation: No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.\nExample 2:\nInput: s = \"leetcode\"\nOutput: \"\"\nExplanation: \"leetcode\" has only characters so we cannot separate them by digits.\nExample 3:\nInput: s = \"1229857369\"\nOutput: \"\"\nExplanation: \"1229857369\" has only digits so we cannot separate them by characters.\n Constraints:\n1 <= s.length <= 500\ns consists of only lowercase English letters and/or digits." }, { "post_href": "https://leetcode.com/problems/display-table-of-food-orders-in-a-restaurant/discuss/1236252/Python3-Brute-Force-Solution", "python_solutions": "class Solution:\n def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n \n order = defaultdict(lambda : {})\n \n foods = set()\n \n ids = []\n \n for i , t , name in orders:\n t = int(t)\n if(name in order[t]):\n order[t][name] += 1\n else:\n order[t][name] = 1\n if(int(t) not in ids):\n ids.append(int(t))\n \n foods.add(name)\n \n ids.sort()\n \n foods = list(foods)\n \n foods.sort()\n \n tables = [['Table'] + foods]\n \n k = 0\n \n order = dict(sorted(order.items() , key=lambda x: x[0]))\n \n for _ , j in order.items():\n ans = [str(ids[k])]\n for i in foods:\n if(i in j):\n ans.append(str(j[i]))\n else:\n ans.append(\"0\")\n \n tables.append(ans)\n \n k += 1\n \n return tables", "slug": "display-table-of-food-orders-in-a-restaurant", "post_title": "[Python3] Brute Force Solution", "user": "VoidCupboard", "upvotes": 3, "views": 163, "problem_title": "display table of food orders in a restaurant", "number": 1418, "acceptance": 0.738, "difficulty": "Medium", "__index_level_0__": 21241, "question": "Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.\nReturn the restaurant's \u201cdisplay table\u201d. The \u201cdisplay table\u201d is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is \u201cTable\u201d, followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order.\n Example 1:\nInput: orders = [[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]\nOutput: [[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"],[\"3\",\"0\",\"2\",\"1\",\"0\"],[\"5\",\"0\",\"1\",\"0\",\"1\"],[\"10\",\"1\",\"0\",\"0\",\"0\"]] \nExplanation:\nThe displaying table looks like:\nTable,Beef Burrito,Ceviche,Fried Chicken,Water\n3 ,0 ,2 ,1 ,0\n5 ,0 ,1 ,0 ,1\n10 ,1 ,0 ,0 ,0\nFor the table 3: David orders \"Ceviche\" and \"Fried Chicken\", and Rous orders \"Ceviche\".\nFor the table 5: Carla orders \"Water\" and \"Ceviche\".\nFor the table 10: Corina orders \"Beef Burrito\". \nExample 2:\nInput: orders = [[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]\nOutput: [[\"Table\",\"Canadian Waffles\",\"Fried Chicken\"],[\"1\",\"2\",\"0\"],[\"12\",\"0\",\"3\"]] \nExplanation: \nFor the table 1: Adam and Brianna order \"Canadian Waffles\".\nFor the table 12: James, Ratesh and Amadeus order \"Fried Chicken\".\nExample 3:\nInput: orders = [[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]\nOutput: [[\"Table\",\"Bean Burrito\",\"Beef Burrito\",\"Soda\"],[\"2\",\"1\",\"1\",\"1\"]]\n Constraints:\n1 <= orders.length <= 5 * 10^4\norders[i].length == 3\n1 <= customerNamei.length, foodItemi.length <= 20\ncustomerNamei and foodItemi consist of lowercase and uppercase English letters and the space character.\ntableNumberi is a valid integer between 1 and 500." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-frogs-croaking/discuss/1200924/Python-3-or-Greedy-Simulation-Clean-code-or-Explanantion", "python_solutions": "class Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n cnt, s = collections.defaultdict(int), 'croak' \n ans, cur, d = 0, 0, {c:i for i, c in enumerate(s)} # d: mapping for letter & its index\n for letter in croakOfFrogs: # iterate over the string\n if letter not in s: return -1 # if any letter other than \"croak\" is met, then invalid\n cnt[letter] += 1 # increase cnt for letter\n if letter == 'c': cur += 1 # 'c' is met, increase current ongoing croak `cur`\n elif cnt[s[d[letter]-1]] <= 0: return -1 # if previous character fall below to 0, return -1\n else: cnt[s[d[letter]-1]] -= 1 # otherwise, decrease cnt for previous character\n ans = max(ans, cur) # update answer using `cur`\n if letter == 'k': # when 'k' is met, decrease cnt and cur\n cnt[letter] -= 1\n cur -= 1\n return ans if not cur else -1 # return ans if current ongoing \"croak\" is 0", "slug": "minimum-number-of-frogs-croaking", "post_title": "Python 3 | Greedy, Simulation, Clean code | Explanantion", "user": "idontknoooo", "upvotes": 6, "views": 384, "problem_title": "minimum number of frogs croaking", "number": 1419, "acceptance": 0.501, "difficulty": "Medium", "__index_level_0__": 21250, "question": "You are given the string croakOfFrogs, which represents a combination of the string \"croak\" from different frogs, that is, multiple frogs can croak at the same time, so multiple \"croak\" are mixed.\nReturn the minimum number of different frogs to finish all the croaks in the given string.\nA valid \"croak\" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid \"croak\" return -1.\n Example 1:\nInput: croakOfFrogs = \"croakcroak\"\nOutput: 1 \nExplanation: One frog yelling \"croak\" twice.\nExample 2:\nInput: croakOfFrogs = \"crcoakroak\"\nOutput: 2 \nExplanation: The minimum number of frogs is two. \nThe first frog could yell \"crcoakroak\".\nThe second frog could yell later \"crcoakroak\".\nExample 3:\nInput: croakOfFrogs = \"croakcrook\"\nOutput: -1\nExplanation: The given string is an invalid combination of \"croak\" from different frogs.\n Constraints:\n1 <= croakOfFrogs.length <= 105\ncroakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'." }, { "post_href": "https://leetcode.com/problems/build-array-where-you-can-find-the-maximum-exactly-k-comparisons/discuss/2785539/Python-DP-cleaner-than-most-answers", "python_solutions": "class Solution:\n def numOfArrays(self, n: int, m: int, K: int) -> int:\n MOD = 10 ** 9 + 7\n # f[i][j][k] cumulative sum, first i elements, current max less than or equal to j, k more maximum to fill\n f = [[[0 for _ in range(K + 1)] for _ in range(m + 1)] for _ in range(n + 1)]\n for j in range(m + 1):\n f[0][j][K] = 1\n\n for i in range(n + 1):\n for j in range(1, m + 1):\n for k in range(K):\n # prev value a[i] <= pref high a[i] = j refresh high\n f[i][j][k] = (f[i][j - 1][k] + j * (f[i - 1][j][k] - f[i - 1][j - 1][k]) + f[i - 1][j - 1][k + 1]) % MOD\n \n return f[n][m][0]", "slug": "build-array-where-you-can-find-the-maximum-exactly-k-comparisons", "post_title": "[Python] DP cleaner than most answers", "user": "chaosrw", "upvotes": 0, "views": 4, "problem_title": "build array where you can find the maximum exactly k comparisons", "number": 1420, "acceptance": 0.635, "difficulty": "Hard", "__index_level_0__": 21256, "question": "You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:\nYou should build the array arr which has the following properties:\narr has exactly n integers.\n1 <= arr[i] <= m where (0 <= i < n).\nAfter applying the mentioned algorithm to arr, the value search_cost is equal to k.\nReturn the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.\n Example 1:\nInput: n = 2, m = 3, k = 1\nOutput: 6\nExplanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\nExample 2:\nInput: n = 5, m = 2, k = 3\nOutput: 0\nExplanation: There are no possible arrays that satisfy the mentioned conditions.\nExample 3:\nInput: n = 9, m = 1, k = 1\nOutput: 1\nExplanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n Constraints:\n1 <= n <= 50\n1 <= m <= 100\n0 <= k <= n" }, { "post_href": "https://leetcode.com/problems/maximum-score-after-splitting-a-string/discuss/597944/Python3-linear-scan", "python_solutions": "class Solution:\n def maxScore(self, s: str) -> int:\n zeros = ones = 0\n ans = float(\"-inf\")\n \n for i in range(len(s)-1):\n if s[i] == \"0\": zeros += 1\n else: ones -= 1\n ans = max(ans, zeros + ones)\n \n return ans - ones + (1 if s[-1] == \"1\" else 0)", "slug": "maximum-score-after-splitting-a-string", "post_title": "[Python3] linear scan", "user": "ye15", "upvotes": 5, "views": 482, "problem_title": "maximum score after splitting a string", "number": 1422, "acceptance": 0.578, "difficulty": "Easy", "__index_level_0__": 21260, "question": "Given a string s of zeros and ones, return the maximum score after splitting the string into two non-empty substrings (i.e. left substring and right substring).\nThe score after splitting a string is the number of zeros in the left substring plus the number of ones in the right substring.\n Example 1:\nInput: s = \"011101\"\nOutput: 5 \nExplanation: \nAll possible ways of splitting s into two non-empty substrings are:\nleft = \"0\" and right = \"11101\", score = 1 + 4 = 5 \nleft = \"01\" and right = \"1101\", score = 1 + 3 = 4 \nleft = \"011\" and right = \"101\", score = 1 + 2 = 3 \nleft = \"0111\" and right = \"01\", score = 1 + 1 = 2 \nleft = \"01110\" and right = \"1\", score = 2 + 1 = 3\nExample 2:\nInput: s = \"00111\"\nOutput: 5\nExplanation: When left = \"00\" and right = \"111\", we get the maximum score = 2 + 3 = 5\nExample 3:\nInput: s = \"1111\"\nOutput: 3\n Constraints:\n2 <= s.length <= 500\nThe string s consists of characters '0' and '1' only." }, { "post_href": "https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/discuss/2197728/Python3-O(n)-Clean-and-Simple-Sliding-Window-Solution", "python_solutions": "class Solution:\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n n = len(cardPoints)\n total = sum(cardPoints)\n \n remaining_length = n - k\n subarray_sum = sum(cardPoints[:remaining_length])\n \n min_sum = subarray_sum\n for i in range(remaining_length, n):\n # Update the sliding window sum to the subarray ending at index i\n subarray_sum += cardPoints[i]\n subarray_sum -= cardPoints[i - remaining_length]\n # Update min_sum to track the overall minimum sum so far\n min_sum = min(min_sum, subarray_sum)\n return total - min_sum", "slug": "maximum-points-you-can-obtain-from-cards", "post_title": "[Python3] O(n) - Clean and Simple Sliding Window Solution", "user": "TLDRAlgos", "upvotes": 38, "views": 2200, "problem_title": "maximum points you can obtain from cards", "number": 1423, "acceptance": 0.523, "difficulty": "Medium", "__index_level_0__": 21278, "question": "There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.\nIn one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.\nYour score is the sum of the points of the cards you have taken.\nGiven the integer array cardPoints and the integer k, return the maximum score you can obtain.\n Example 1:\nInput: cardPoints = [1,2,3,4,5,6,1], k = 3\nOutput: 12\nExplanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\nExample 2:\nInput: cardPoints = [2,2,2], k = 2\nOutput: 4\nExplanation: Regardless of which two cards you take, your score will always be 4.\nExample 3:\nInput: cardPoints = [9,7,7,9,7,7,9], k = 7\nOutput: 55\nExplanation: You have to take all the cards. Your score is the sum of points of all cards.\n Constraints:\n1 <= cardPoints.length <= 105\n1 <= cardPoints[i] <= 104\n1 <= k <= cardPoints.length" }, { "post_href": "https://leetcode.com/problems/diagonal-traverse-ii/discuss/1866412/Python-easy-to-read-and-understand-or-hashmap", "python_solutions": "class Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n d = collections.defaultdict(list)\n \n for i in range(len(nums)):\n for j in range(len(nums[i])):\n d[(i+j)].append(nums[i][j])\n \n \n ans = []\n for key in d:\n ans += d[key][::-1]\n \n return ans", "slug": "diagonal-traverse-ii", "post_title": "Python easy to read and understand | hashmap", "user": "sanial2001", "upvotes": 0, "views": 58, "problem_title": "diagonal traverse ii", "number": 1424, "acceptance": 0.504, "difficulty": "Medium", "__index_level_0__": 21330, "question": "Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.\n Example 1:\nInput: nums = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [1,4,2,7,5,3,8,6,9]\nExample 2:\nInput: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\nOutput: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i].length <= 105\n1 <= sum(nums[i].length) <= 105\n1 <= nums[i][j] <= 105" }, { "post_href": "https://leetcode.com/problems/constrained-subsequence-sum/discuss/2672473/Python-or-Deque", "python_solutions": "class Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [0]*n\n q = deque()\n\n for i, num in enumerate(nums):\n if i > k and q[0] == dp[i-k-1]:\n q.popleft()\n dp[i] = max(q[0] if q else 0, 0)+num\n\n while q and q[-1] < dp[i]:\n q.pop()\n q.append(dp[i])\n return max(dp)", "slug": "constrained-subsequence-sum", "post_title": "Python | Deque", "user": "jainsiddharth99", "upvotes": 0, "views": 6, "problem_title": "constrained subsequence sum", "number": 1425, "acceptance": 0.474, "difficulty": "Hard", "__index_level_0__": 21332, "question": "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.\nA subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n Example 1:\nInput: nums = [10,2,-10,5,20], k = 2\nOutput: 37\nExplanation: The subsequence is [10, 2, 5, 20].\nExample 2:\nInput: nums = [-1,-2,-3], k = 1\nOutput: -1\nExplanation: The subsequence must be non-empty, so we choose the largest number.\nExample 3:\nInput: nums = [10,-2,-10,-5,20], k = 2\nOutput: 23\nExplanation: The subsequence is [10, -2, -5, 20].\n Constraints:\n1 <= k <= nums.length <= 105\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/discuss/2269844/Python-3-ONE-LINER", "python_solutions": "class Solution:\n def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:\n return [x+extraCandies >= max(candies) for x in candies]", "slug": "kids-with-the-greatest-number-of-candies", "post_title": "Python 3 [ONE LINER]", "user": "omkarxpatel", "upvotes": 6, "views": 143, "problem_title": "kids with the greatest number of candies", "number": 1431, "acceptance": 0.875, "difficulty": "Easy", "__index_level_0__": 21339, "question": "There are n kids with candies. You are given an integer array candies, where each candies[i] represents the number of candies the ith kid has, and an integer extraCandies, denoting the number of extra candies that you have.\nReturn a boolean array result of length n, where result[i] is true if, after giving the ith kid all the extraCandies, they will have the greatest number of candies among all the kids, or false otherwise.\nNote that multiple kids can have the greatest number of candies.\n Example 1:\nInput: candies = [2,3,5,1,3], extraCandies = 3\nOutput: [true,true,true,false,true] \nExplanation: If you give all extraCandies to:\n- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\nExample 2:\nInput: candies = [4,2,1,1,2], extraCandies = 1\nOutput: [true,false,false,false,false] \nExplanation: There is only 1 extra candy.\nKid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.\nExample 3:\nInput: candies = [12,1,12], extraCandies = 10\nOutput: [true,false,true]\n Constraints:\nn == candies.length\n2 <= n <= 100\n1 <= candies[i] <= 100\n1 <= extraCandies <= 50" }, { "post_href": "https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/discuss/608687/Python3-scan-through-digits", "python_solutions": "class Solution:\n def maxDiff(self, num: int) -> int:\n num = str(num)\n \n i = next((i for i in range(len(num)) if num[i] != \"9\"), -1) #first non-9 digit\n hi = int(num.replace(num[i], \"9\"))\n \n if num[0] != \"1\": lo = int(num.replace(num[0], \"1\"))\n else: \n i = next((i for i in range(len(num)) if num[i] not in \"01\"), -1)\n lo = int(num.replace(num[i], \"0\") if i > 0 else num)\n \n return hi - lo", "slug": "max-difference-you-can-get-from-changing-an-integer", "post_title": "[Python3] scan through digits", "user": "ye15", "upvotes": 4, "views": 151, "problem_title": "max difference you can get from changing an integer", "number": 1432, "acceptance": 0.429, "difficulty": "Medium", "__index_level_0__": 21387, "question": "You are given an integer num. You will apply the following steps exactly two times:\nPick a digit x (0 <= x <= 9).\nPick another digit y (0 <= y <= 9). The digit y can be equal to x.\nReplace all the occurrences of x in the decimal representation of num by y.\nThe new integer cannot have any leading zeros, also the new integer cannot be 0.\nLet a and b be the results of applying the operations to num the first and second times, respectively.\nReturn the max difference between a and b.\n Example 1:\nInput: num = 555\nOutput: 888\nExplanation: The first time pick x = 5 and y = 9 and store the new integer in a.\nThe second time pick x = 5 and y = 1 and store the new integer in b.\nWe have now a = 999 and b = 111 and max difference = 888\nExample 2:\nInput: num = 9\nOutput: 8\nExplanation: The first time pick x = 9 and y = 9 and store the new integer in a.\nThe second time pick x = 9 and y = 1 and store the new integer in b.\nWe have now a = 9 and b = 1 and max difference = 8\n Constraints:\n1 <= num <= 108" }, { "post_href": "https://leetcode.com/problems/check-if-a-string-can-break-another-string/discuss/1415509/ONLY-CODE-N-log-N-sort-and-compare-%3A)-clean-3-liner-and-then-1-liner", "python_solutions": "class Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n return all(a<=b for a,b in zip(min(sorted(s1),sorted(s2)),max(sorted(s1),sorted(s2))))```", "slug": "check-if-a-string-can-break-another-string", "post_title": "[ONLY CODE] N log N sort and compare :) clean 3 liner and then 1 liner", "user": "yozaam", "upvotes": 1, "views": 60, "problem_title": "check if a string can break another string", "number": 1433, "acceptance": 0.6890000000000001, "difficulty": "Medium", "__index_level_0__": 21392, "question": "Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.\nA string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.\n Example 1:\nInput: s1 = \"abc\", s2 = \"xya\"\nOutput: true\nExplanation: \"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".\nExample 2:\nInput: s1 = \"abe\", s2 = \"acd\"\nOutput: false \nExplanation: All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.\nExample 3:\nInput: s1 = \"leetcodee\", s2 = \"interview\"\nOutput: true\n Constraints:\ns1.length == n\ns2.length == n\n1 <= n <= 10^5\nAll strings consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/discuss/608721/Python-dp-with-bit-mask-memorization", "python_solutions": "class Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n n = len(hats)\n h2p = collections.defaultdict(list)\n for p, hs in enumerate(hats):\n for h in hs:\n h2p[h].append(p)\n full_mask = (1 << n) - 1\n mod = 10**9 + 7\n @functools.lru_cache(maxsize=None)\n def count(h, mask):\n\t\t # everyone wears a hat\n if mask == full_mask:\n return 1\n\t\t\t# ran out of hats\n if h == 41:\n return 0\n\t\t\t# skip the current hat h\n ans = count(h + 1, mask)\n for p in h2p[h]:\n\t\t\t # if person p already has a hat\n if mask & (1 << p):\n continue\n\t\t\t\t# let person p wear hat h\n ans += count(h + 1, mask | (1 << p))\n ans %= mod\n return ans\n\t\t# start from the first hat and no one wearing any hat\n return count(1, 0)", "slug": "number-of-ways-to-wear-different-hats-to-each-other", "post_title": "Python dp with bit mask memorization", "user": "ChelseaChenC", "upvotes": 2, "views": 246, "problem_title": "number of ways to wear different hats to each other", "number": 1434, "acceptance": 0.429, "difficulty": "Hard", "__index_level_0__": 21407, "question": "There are n people and 40 types of hats labeled from 1 to 40.\nGiven a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.\nReturn the number of ways that the n people wear different hats to each other.\nSince the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: hats = [[3,4],[4,5],[5]]\nOutput: 1\nExplanation: There is only one way to choose hats given the conditions. \nFirst person choose hat 3, Second person choose hat 4 and last one hat 5.\nExample 2:\nInput: hats = [[3,5,1],[3,5]]\nOutput: 4\nExplanation: There are 4 ways to choose hats:\n(3,5), (5,3), (1,3) and (1,5)\nExample 3:\nInput: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\nOutput: 24\nExplanation: Each person can choose hats labeled from 1 to 4.\nNumber of Permutations of (1,2,3,4) = 24.\n Constraints:\nn == hats.length\n1 <= n <= 10\n1 <= hats[i].length <= 40\n1 <= hats[i][j] <= 40\nhats[i] contains a list of unique integers." }, { "post_href": "https://leetcode.com/problems/destination-city/discuss/1664716/98-faster-easy-python-solution-based-on-question-no.-997", "python_solutions": "class Solution:\n def destCity(self, paths: List[List[str]]) -> str:\n lst=[]\n arr=[]\n for i in paths:\n lst.append(i[0])\n arr.append(i[1])\n ptr=set(lst)\n ptr2=set(arr)\n return list(ptr2-ptr)[0]", "slug": "destination-city", "post_title": "98% faster easy python solution based on question no. 997", "user": "amannarayansingh10", "upvotes": 9, "views": 437, "problem_title": "destination city", "number": 1436, "acceptance": 0.7759999999999999, "difficulty": "Easy", "__index_level_0__": 21411, "question": "You are given the array paths, where paths[i] = [cityAi, cityBi] means there exists a direct path going from cityAi to cityBi. Return the destination city, that is, the city without any path outgoing to another city.\nIt is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.\n Example 1:\nInput: paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\nOutput: \"Sao Paulo\" \nExplanation: Starting at \"London\" city you will reach \"Sao Paulo\" city which is the destination city. Your trip consist of: \"London\" -> \"New York\" -> \"Lima\" -> \"Sao Paulo\".\nExample 2:\nInput: paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\nOutput: \"A\"\nExplanation: All possible trips are: \n\"D\" -> \"B\" -> \"C\" -> \"A\". \n\"B\" -> \"C\" -> \"A\". \n\"C\" -> \"A\". \n\"A\". \nClearly the destination city is \"A\".\nExample 3:\nInput: paths = [[\"A\",\"Z\"]]\nOutput: \"Z\"\n Constraints:\n1 <= paths.length <= 100\npaths[i].length == 2\n1 <= cityAi.length, cityBi.length <= 10\ncityAi != cityBi\nAll strings consist of lowercase and uppercase English letters and the space character." }, { "post_href": "https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/discuss/609823/Python-O(n)-Easy-(For-Loop-List-Comprehension)", "python_solutions": "class Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n indices = [i for i, x in enumerate(nums) if x == 1]\n if not indices:\n return True\n for i in range(1, len(indices)):\n if indices[i] - indices[i-1] < k + 1:\n return False\n return True", "slug": "check-if-all-1s-are-at-least-length-k-places-away", "post_title": "Python O(n) Easy (For Loop, List Comprehension)", "user": "sonaksh", "upvotes": 2, "views": 180, "problem_title": "check if all 1s are at least length k places away", "number": 1437, "acceptance": 0.591, "difficulty": "Easy", "__index_level_0__": 21442, "question": "Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.\n Example 1:\nInput: nums = [1,0,0,0,1,0,0,1], k = 2\nOutput: true\nExplanation: Each of the 1s are at least 2 places away from each other.\nExample 2:\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: false\nExplanation: The second 1 and third 1 are only one apart from each other.\n Constraints:\n1 <= nums.length <= 105\n0 <= k <= nums.length\nnums[i] is 0 or 1" }, { "post_href": "https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/discuss/2798749/nlogn-solution-by-this-dude", "python_solutions": "class Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n #[8,2,4,3,6,11] limit = 5\n\n #if the new number is greater than max this becomes new max,\n #if new number is less than min this becomes new min\n #if max - min exceeds limit, pop the left most element -> if the left most element was max or min, recompute max - min and see if it goes limit\n\n q = []\n min_heap = []\n max_heap = []\n max_ans = 1\n popped_index = set()\n\n for i,v in enumerate(nums):\n\n q.append((v,i))\n # max_ans = max(max_ans,len(q))\n heapq.heappush(min_heap,(v,i))\n heapq.heappush(max_heap,(v*-1,i))\n while(max_heap[0][0]*-1 - min_heap[0][0] > limit):\n temp = q.pop(0)\n popped_ele = temp[0]\n popped_index.add(temp[1])\n\n while(min_heap[0][1] in popped_index):\n heapq.heappop(min_heap)\n \n while(max_heap[0][1] in popped_index):\n heapq.heappop(max_heap)\n\n if len(q) > max_ans:\n max_ans = len(q)\n\n return max_ans", "slug": "longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit", "post_title": "nlogn solution by this dude", "user": "ariboi27", "upvotes": 0, "views": 6, "problem_title": "longest continuous subarray with absolute diff less than or equal to limit", "number": 1438, "acceptance": 0.481, "difficulty": "Medium", "__index_level_0__": 21464, "question": "Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.\n Example 1:\nInput: nums = [8,2,4,7], limit = 4\nOutput: 2 \nExplanation: All subarrays are: \n[8] with maximum absolute diff |8-8| = 0 <= 4.\n[8,2] with maximum absolute diff |8-2| = 6 > 4. \n[8,2,4] with maximum absolute diff |8-2| = 6 > 4.\n[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.\n[2] with maximum absolute diff |2-2| = 0 <= 4.\n[2,4] with maximum absolute diff |2-4| = 2 <= 4.\n[2,4,7] with maximum absolute diff |2-7| = 5 > 4.\n[4] with maximum absolute diff |4-4| = 0 <= 4.\n[4,7] with maximum absolute diff |4-7| = 3 <= 4.\n[7] with maximum absolute diff |7-7| = 0 <= 4. \nTherefore, the size of the longest subarray is 2.\nExample 2:\nInput: nums = [10,1,2,4,7,2], limit = 5\nOutput: 4 \nExplanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.\nExample 3:\nInput: nums = [4,2,2,2,4,4,2,2], limit = 0\nOutput: 3\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109\n0 <= limit <= 109" }, { "post_href": "https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/1928887/Python3-or-O(m-*-knlogkn)", "python_solutions": "class Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n row=len(mat)\n col=len(mat[0])\n temp=[i for i in mat[0]]\n for i in range(1,row):\n currSum=[]\n for j in range(col):\n for it in range(len(temp)):\n currSum.append(temp[it]+mat[i][j])\n currSum.sort()\n temp.clear()\n maxSize=min(k,len(currSum))\n for size in range(maxSize):\n temp.append(currSum[size])\n return temp[k-1]", "slug": "find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows", "post_title": "[Python3] | O(m * knlogkn)", "user": "swapnilsingh421", "upvotes": 2, "views": 66, "problem_title": "find the kth smallest sum of a matrix with sorted rows", "number": 1439, "acceptance": 0.614, "difficulty": "Hard", "__index_level_0__": 21467, "question": "You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.\nYou are allowed to choose exactly one element from each row to form an array.\nReturn the kth smallest array sum among all possible arrays.\n Example 1:\nInput: mat = [[1,3,11],[2,4,6]], k = 5\nOutput: 7\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.\nExample 2:\nInput: mat = [[1,3,11],[2,4,6]], k = 9\nOutput: 17\nExample 3:\nInput: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\nOutput: 9\nExplanation: Choosing one element from each row, the first k smallest sum are:\n[1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. \n Constraints:\nm == mat.length\nn == mat.length[i]\n1 <= m, n <= 40\n1 <= mat[i][j] <= 5000\n1 <= k <= min(200, nm)\nmat[i] is a non-decreasing array." }, { "post_href": "https://leetcode.com/problems/build-an-array-with-stack-operations/discuss/1291707/Easy-Python-Solution(96.97)", "python_solutions": "class Solution:\n def buildArray(self, target: List[int], n: int) -> List[str]:\n stack=[]\n for i in range(1,n+1):\n if(i in target):\n stack.append(\"Push\")\n else:\n stack.append(\"Push\")\n stack.append(\"Pop\")\n if(i==(target[-1])):\n break\n return stack", "slug": "build-an-array-with-stack-operations", "post_title": "Easy Python Solution(96.97%)", "user": "Sneh17029", "upvotes": 6, "views": 407, "problem_title": "build an array with stack operations", "number": 1441, "acceptance": 0.7140000000000001, "difficulty": "Medium", "__index_level_0__": 21468, "question": "You are given an integer array target and an integer n.\nYou have an empty stack with the two following operations:\n\"Push\": pushes an integer to the top of the stack.\n\"Pop\": removes the integer on the top of the stack.\nYou also have a stream of the integers in the range [1, n].\nUse the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:\nIf the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.\nIf the stack is not empty, pop the integer at the top of the stack.\nIf, at any moment, the elements in the stack (from the bottom to the top) are equal to target, do not read new integers from the stream and do not do more operations on the stack.\nReturn the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.\n Example 1:\nInput: target = [1,3], n = 3\nOutput: [\"Push\",\"Push\",\"Pop\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nPop the integer on the top of the stack. s = [1].\nRead 3 from the stream and push it to the stack. s = [1,3].\nExample 2:\nInput: target = [1,2,3], n = 3\nOutput: [\"Push\",\"Push\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nRead 3 from the stream and push it to the stack. s = [1,2,3].\nExample 3:\nInput: target = [1,2], n = 4\nOutput: [\"Push\",\"Push\"]\nExplanation: Initially the stack s is empty. The last element is the top of the stack.\nRead 1 from the stream and push it to the stack. s = [1].\nRead 2 from the stream and push it to the stack. s = [1,2].\nSince the stack (from the bottom to the top) is equal to target, we stop the stack operations.\nThe answers that read integer 3 from the stream are not accepted.\n Constraints:\n1 <= target.length <= 100\n1 <= n <= 100\n1 <= target[i] <= n\ntarget is strictly increasing." }, { "post_href": "https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/discuss/1271870/Python-O(n)-hash-table", "python_solutions": "class Solution:\n def countTriplets(self, arr: List[int]) -> int:\n import collections\n if len(arr) < 2:\n return 0\n xors = arr[0]\n cnt = collections.Counter()\n cnt_sums = collections.Counter() \n result = 0\n cnt[xors] = 1\n cnt_sums[xors] = 0\n for k in range(1, len(arr)):\n xors ^= arr[k]\n if xors == 0:\n result += k\n result += (k - 1)*cnt[xors] - cnt_sums[xors]\n cnt_sums[xors] += k\n cnt[xors] += 1\n \n return result", "slug": "count-triplets-that-can-form-two-arrays-of-equal-xor", "post_title": "Python O(n) hash table", "user": "CiFFiRO", "upvotes": 1, "views": 164, "problem_title": "count triplets that can form two arrays of equal xor", "number": 1442, "acceptance": 0.7559999999999999, "difficulty": "Medium", "__index_level_0__": 21501, "question": "Given an array of integers arr.\nWe want to select three indices i, j and k where (0 <= i < j <= k < arr.length).\nLet's define a and b as follows:\na = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]\nb = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]\nNote that ^ denotes the bitwise-xor operation.\nReturn the number of triplets (i, j and k) Where a == b.\n Example 1:\nInput: arr = [2,3,1,6,7]\nOutput: 4\nExplanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)\nExample 2:\nInput: arr = [1,1,1,1,1]\nOutput: 10\n Constraints:\n1 <= arr.length <= 300\n1 <= arr[i] <= 108" }, { "post_href": "https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/discuss/1460342/Python-Recursive-DFS-Solution-with-detailed-explanation-in-comments", "python_solutions": "class Solution:\n def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:\n self.res = 0\n d = collections.defaultdict(list)\n \n for e in edges: # construct the graph\n d[e[0]].append(e[1])\n d[e[1]].append(e[0])\n \n seen = set() # initialise seen set for visited nodes\n seen.add(0) # add root to visited\n \n def dfs(key):\n # we initialize the go_thru state as 0, meaning we do not go through this node from root\n # there are two cases where we would set go_thru == 1: \n #(1) when this is the apple node, so we must visit it and go back up\n #(2) when this node has apple nodes as descendants below, we must go down and come back\n go_thru = 0 \n if hasApple[key]: # case 1\n go_thru = 1\n \n for i in d[key]:\n if i not in seen:\n seen.add(i)\n a = dfs(i) \n if a: # case 2, note that having just one path with an apple node below would require us to go through our current node, \n\t\t\t\t\t\t # i.e we don't need both the paths to have apples\n go_thru = 1\n \n if key != 0: # since 0 is already the root, there is no way we can go through 0 to a node above\n self.res += 2 * go_thru # passing one node means forward and backward, so 1 * 2 for going through, 0 * 2 for not\n return go_thru\n \n dfs(0)\n return self.res", "slug": "minimum-time-to-collect-all-apples-in-a-tree", "post_title": "[Python] Recursive DFS Solution with detailed explanation in comments", "user": "lukefall425", "upvotes": 1, "views": 192, "problem_title": "minimum time to collect all apples in a tree", "number": 1443, "acceptance": 0.56, "difficulty": "Medium", "__index_level_0__": 21508, "question": "Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.\nThe edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.\n Example 1:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\nOutput: 8 \nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \nExample 2:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\nOutput: 6\nExplanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \nExample 3:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\nOutput: 0\n Constraints:\n1 <= n <= 105\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai < bi <= n - 1\nhasApple.length == n" }, { "post_href": "https://leetcode.com/problems/number-of-ways-of-cutting-a-pizza/discuss/2677389/Python3-or-Space-Optimized-Bottom-Up-DP-or-O(k-*-r-*-c-*-(r-%2B-c))-Time-O(r-*-c)-Space", "python_solutions": "class Solution:\n def ways(self, pizza: List[str], k: int) -> int:\n rows, cols = len(pizza), len(pizza[0])\n \n # first, need way to query if a section contains an apple given a top left (r1, c1) and bottom right (r2, c2)\n # we can do this in constant time by keeping track of the number of apples above and to the left of any given cell\n apples = [[0] * cols for _ in range(rows)]\n for row in range(rows):\n apples_left = 0\n for col in range(cols):\n if pizza[row][col] == 'A':\n apples_left += 1\n apples[row][col] = apples[row-1][col] + apples_left\n \n # query if there is an apple in this rectangle using the prefix sums\n def has_apple(r1, c1, r2 = rows-1, c2 = cols-1) -> bool:\n if r1 > r2 or c1 > c2:\n return False\n tot = apples[r2][c2]\n left_sub = apples[r2][c1-1] if c1 > 0 else 0\n up_sub = apples[r1-1][c2] if r1 > 0 else 0\n upleft_sub = apples[r1-1][c1-1] if r1 > 0 < c1 else 0\n in_rect = tot - left_sub - up_sub + upleft_sub\n return in_rect > 0\n \n # memory optimized dp, keep track of only one matrix of rows x cols\n # bc we only need to access the values at the previous number of cuts\n dp = [[1 if has_apple(r, c) else 0 for c in range(cols + 1)] for r in range(rows + 1)]\n \n for cuts in range(1, k):\n new_dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n for row in range(rows-1, -1, -1):\n for col in range(cols-1, -1, -1):\n \n for r2 in range(row, rows):\n if has_apple(row, col, r2):\n new_dp[row][col] += dp[r2+1][col]\n \n for c2 in range(col, cols):\n if has_apple(row, col, rows-1, c2):\n new_dp[row][col] += dp[row][c2+1]\n dp = new_dp\n \n return dp[0][0] % (10**9 + 7)", "slug": "number-of-ways-of-cutting-a-pizza", "post_title": "Python3 | Space Optimized Bottom-Up DP | O(k * r * c * (r + c)) Time, O(r * c) Space", "user": "ryangrayson", "upvotes": 3, "views": 293, "problem_title": "number of ways of cutting a pizza", "number": 1444, "acceptance": 0.579, "difficulty": "Hard", "__index_level_0__": 21515, "question": "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. \nFor each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.\nReturn the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.\n Example 1:\nInput: pizza = [\"A..\",\"AAA\",\"...\"], k = 3\nOutput: 3 \nExplanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.\nExample 2:\nInput: pizza = [\"A..\",\"AA.\",\"...\"], k = 3\nOutput: 1\nExample 3:\nInput: pizza = [\"A..\",\"A..\",\"...\"], k = 1\nOutput: 1\n Constraints:\n1 <= rows, cols <= 50\nrows == pizza.length\ncols == pizza[i].length\n1 <= k <= 10\npizza consists of characters 'A' and '.' only." }, { "post_href": "https://leetcode.com/problems/consecutive-characters/discuss/637217/Python-O(n)-by-linear-scan.-w-Comment", "python_solutions": "class Solution:\n def maxPower(self, s: str) -> int:\n \n # the minimum value for consecutive is 1\n local_max, global_max = 1, 1\n \n # dummy char for initialization\n prev = '#'\n for char in s:\n \n if char == prev:\n \n # keeps consecutive, update local max\n local_max += 1\n \n # update global max length with latest one\n global_max = max( global_max, local_max )\n \n else:\n \n # lastest consective chars stops, reset local max\n local_max = 1\n \n # update previous char as current char for next iteration\n prev = char\n \n \n return global_max", "slug": "consecutive-characters", "post_title": "Python O(n) by linear scan. [w/ Comment]", "user": "brianchiang_tw", "upvotes": 7, "views": 1100, "problem_title": "consecutive characters", "number": 1446, "acceptance": 0.616, "difficulty": "Easy", "__index_level_0__": 21519, "question": "The power of the string is the maximum length of a non-empty substring that contains only one unique character.\nGiven a string s, return the power of s.\n Example 1:\nInput: s = \"leetcode\"\nOutput: 2\nExplanation: The substring \"ee\" is of length 2 with the character 'e' only.\nExample 2:\nInput: s = \"abbcccddddeeeeedcba\"\nOutput: 5\nExplanation: The substring \"eeeee\" is of length 5 with the character 'e' only.\n Constraints:\n1 <= s.length <= 500\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/simplified-fractions/discuss/1336226/Python3-solution-using-set", "python_solutions": "class Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n if n == 1:\n return []\n else:\n numerator = list(range(1,n))\n denominator = list(range(2,n+1))\n res = set()\n values = set()\n for i in numerator:\n for j in denominator:\n if i < j and i/j not in values:\n res.add(f'{i}/{j}')\n values.add(i/j)\n return res", "slug": "simplified-fractions", "post_title": "Python3 solution using set", "user": "EklavyaJoshi", "upvotes": 3, "views": 102, "problem_title": "simplified fractions", "number": 1447, "acceptance": 0.648, "difficulty": "Medium", "__index_level_0__": 21556, "question": "Given an integer n, return a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator is less-than-or-equal-to n. You can return the answer in any order.\n Example 1:\nInput: n = 2\nOutput: [\"1/2\"]\nExplanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\nExample 2:\nInput: n = 3\nOutput: [\"1/2\",\"1/3\",\"2/3\"]\nExample 3:\nInput: n = 4\nOutput: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\nExplanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\n Constraints:\n1 <= n <= 100" }, { "post_href": "https://leetcode.com/problems/count-good-nodes-in-binary-tree/discuss/2511520/C%2B%2B-or-PYTHON-oror-EXPLAINED-oror", "python_solutions": "class Solution:\n def goodNodes(self, root: TreeNode) -> int:\n def solve(root,val):\n if root:\n k = solve(root.left, max(val,root.val)) + solve(root.right, max(val,root.val))\n if root.val >= val:\n k+=1\n return k\n return 0\n return solve(root,root.val)", "slug": "count-good-nodes-in-binary-tree", "post_title": "\ud83e\udd47 C++ | PYTHON || EXPLAINED || ; ]", "user": "karan_8082", "upvotes": 43, "views": 2600, "problem_title": "count good nodes in binary tree", "number": 1448, "acceptance": 0.746, "difficulty": "Medium", "__index_level_0__": 21566, "question": "Given a binary tree root, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X.\nReturn the number of good nodes in the binary tree.\n Example 1:\nInput: root = [3,1,4,3,null,1,5]\nOutput: 4\nExplanation: Nodes in blue are good.\nRoot Node (3) is always a good node.\nNode 4 -> (3,4) is the maximum value in the path starting from the root.\nNode 5 -> (3,4,5) is the maximum value in the path\nNode 3 -> (3,1,3) is the maximum value in the path.\nExample 2:\nInput: root = [3,3,null,4,2]\nOutput: 3\nExplanation: Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.\nExample 3:\nInput: root = [1]\nOutput: 1\nExplanation: Root is considered as good.\n Constraints:\nThe number of nodes in the binary tree is in the range [1, 10^5].\nEach node's value is between [-10^4, 10^4]." }, { "post_href": "https://leetcode.com/problems/form-largest-integer-with-digits-that-add-up-to-target/discuss/1113027/Python3-top-down-dp", "python_solutions": "class Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n \n @cache\n def fn(x): \n \"\"\"Return max integer given target x.\"\"\"\n if x == 0: return 0\n if x < 0: return -inf \n return max(fn(x - c) * 10 + i + 1 for i, c in enumerate(cost))\n \n return str(max(0, fn(target)))", "slug": "form-largest-integer-with-digits-that-add-up-to-target", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 1, "views": 117, "problem_title": "form largest integer with digits that add up to target", "number": 1449, "acceptance": 0.472, "difficulty": "Hard", "__index_level_0__": 21606, "question": "Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:\nThe cost of painting a digit (i + 1) is given by cost[i] (0-indexed).\nThe total cost used must be equal to target.\nThe integer does not have 0 digits.\nSince the answer may be very large, return it as a string. If there is no way to paint any integer given the condition, return \"0\".\n Example 1:\nInput: cost = [4,3,2,5,6,7,2,5,5], target = 9\nOutput: \"7772\"\nExplanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\nDigit cost\n 1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5\nExample 2:\nInput: cost = [7,6,5,5,5,6,8,7,8], target = 12\nOutput: \"85\"\nExplanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\nExample 3:\nInput: cost = [2,4,6,2,4,6,4,4,4], target = 5\nOutput: \"0\"\nExplanation: It is impossible to paint any integer with total cost equal to target.\n Constraints:\ncost.length == 9\n1 <= cost[i], target <= 5000" }, { "post_href": "https://leetcode.com/problems/number-of-students-doing-homework-at-a-given-time/discuss/1817462/Python-Simple-Solution-or-Zip-and-Iterate-86-37ms", "python_solutions": "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n count = 0 # If a value meets the criteria, one will be added here.\n\n for x, y in zip(startTime, endTime): # Zipping the two lists to allow us to iterate over them using x,y as our variables.\n if x <= queryTime <= y: # Checking if the queryTime number is between startTime and endTime, adding one to count if it is.\n count += 1\n return count # Returning the value in count", "slug": "number-of-students-doing-homework-at-a-given-time", "post_title": "Python Simple Solution | Zip & Iterate - 86% 37ms", "user": "IvanTsukei", "upvotes": 4, "views": 110, "problem_title": "number of students doing homework at a given time", "number": 1450, "acceptance": 0.759, "difficulty": "Easy", "__index_level_0__": 21607, "question": "Given two integer arrays startTime and endTime and given an integer queryTime.\nThe ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].\nReturn the number of students doing their homework at time queryTime. More formally, return the number of students where queryTime lays in the interval [startTime[i], endTime[i]] inclusive.\n Example 1:\nInput: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\nOutput: 1\nExplanation: We have 3 students where:\nThe first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\nThe second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\nThe third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.\nExample 2:\nInput: startTime = [4], endTime = [4], queryTime = 4\nOutput: 1\nExplanation: The only student was doing their homework at the queryTime.\n Constraints:\nstartTime.length == endTime.length\n1 <= startTime.length <= 100\n1 <= startTime[i] <= endTime[i] <= 1000\n1 <= queryTime <= 1000" }, { "post_href": "https://leetcode.com/problems/rearrange-words-in-a-sentence/discuss/636348/Python3-one-line", "python_solutions": "class Solution:\n def arrangeWords(self, text: str) -> str:\n return \" \".join(sorted(text.split(), key=len)).capitalize()", "slug": "rearrange-words-in-a-sentence", "post_title": "[Python3] one line", "user": "ye15", "upvotes": 40, "views": 2600, "problem_title": "rearrange words in a sentence", "number": 1451, "acceptance": 0.626, "difficulty": "Medium", "__index_level_0__": 21649, "question": "Given a sentence text (A sentence is a string of space-separated words) in the following format:\nFirst letter is in upper case.\nEach word in text are separated by a single space.\nYour task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order.\nReturn the new text following the format shown above.\n Example 1:\nInput: text = \"Leetcode is cool\"\nOutput: \"Is cool leetcode\"\nExplanation: There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\nOutput is ordered by length and the new first word starts with capital letter.\nExample 2:\nInput: text = \"Keep calm and code on\"\nOutput: \"On and keep calm code\"\nExplanation: Output is ordered as follows:\n\"On\" 2 letters.\n\"and\" 3 letters.\n\"keep\" 4 letters in case of tie order by position in original text.\n\"calm\" 4 letters.\n\"code\" 4 letters.\nExample 3:\nInput: text = \"To be or not to be\"\nOutput: \"To be or to be not\"\n Constraints:\ntext begins with a capital letter and then contains lowercase letters and single space between words.\n1 <= text.length <= 10^5" }, { "post_href": "https://leetcode.com/problems/people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list/discuss/2827639/Python-or-Dictionary-%2B-Bitwise-operation", "python_solutions": "class Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n\n n = len(favoriteCompanies)\n comp = []\n for f in favoriteCompanies:\n comp += f\n comp = list(set(comp))\n \n dictBit = {comp[i] : 1 << i for i in range(len(comp))}\n\n def getBit(cList):\n output = 0\n for c in cList:\n output |= dictBit[c]\n return output\n bitFav = [getBit(favoriteCompanies[i]) for i in range(n)]\n\n output = []\n for i in range(n):\n isGood = True\n for j in range(n):\n if(i != j and bitFav[i] & bitFav[j] == bitFav[i]):\n isGood = False\n break\n if(isGood):\n output.append(i)\n \n return output", "slug": "people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list", "post_title": "Python | Dictionary + Bitwise operation", "user": "CosmosYu", "upvotes": 0, "views": 3, "problem_title": "people whose list of favorite companies is not a subset of another list", "number": 1452, "acceptance": 0.568, "difficulty": "Medium", "__index_level_0__": 21674, "question": "Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).\nReturn the indices of people whose list of favorite companies is not a subset of any other list of favorites companies. You must return the indices in increasing order.\n Example 1:\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\nOutput: [0,1,4] \nExplanation: \nPerson with index=2 has favoriteCompanies[2]=[\"google\",\"facebook\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] corresponding to the person with index 0. \nPerson with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \nOther lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].\nExample 2:\nInput: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\nOutput: [0,1] \nExplanation: In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].\nExample 3:\nInput: favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\nOutput: [0,1,2,3]\n Constraints:\n1 <= favoriteCompanies.length <= 100\n1 <= favoriteCompanies[i].length <= 500\n1 <= favoriteCompanies[i][j].length <= 20\nAll strings in favoriteCompanies[i] are distinct.\nAll lists of favorite companies are distinct, that is, If we sort alphabetically each list then favoriteCompanies[i] != favoriteCompanies[j].\nAll strings consist of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/discuss/636439/Python3-angular-sweep-O(N2-logN)", "python_solutions": "class Solution:\n def numPoints(self, points: List[List[int]], r: int) -> int:\n ans = 1\n for x, y in points: \n angles = []\n for x1, y1 in points: \n if (x1 != x or y1 != y) and (d:=sqrt((x1-x)**2 + (y1-y)**2)) <= 2*r: \n angle = atan2(y1-y, x1-x)\n delta = acos(d/(2*r))\n angles.append((angle-delta, +1)) #entry\n angles.append((angle+delta, -1)) #exit\n angles.sort(key=lambda x: (x[0], -x[1]))\n val = 1\n for _, entry in angles: \n ans = max(ans, val := val+entry)\n return ans", "slug": "maximum-number-of-darts-inside-of-a-circular-dartboard", "post_title": "[Python3] angular sweep O(N^2 logN)", "user": "ye15", "upvotes": 38, "views": 1400, "problem_title": "maximum number of darts inside of a circular dartboard", "number": 1453, "acceptance": 0.369, "difficulty": "Hard", "__index_level_0__": 21677, "question": "Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [xi, yi] is the position of the ith dart that Alice threw on the wall.\nBob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lie on the dartboard.\nGiven the integer r, return the maximum number of darts that can lie on the dartboard.\n Example 1:\nInput: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\nOutput: 4\nExplanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\nExample 2:\nInput: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\nOutput: 5\nExplanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n Constraints:\n1 <= darts.length <= 100\ndarts[i].length == 2\n-104 <= xi, yi <= 104\nAll the darts are unique\n1 <= r <= 5000" }, { "post_href": "https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/discuss/1170901/Python3-Simple-And-Readable-Solution-With-Explanation", "python_solutions": "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n for i , j in enumerate(sentence.split()):\n if(j.startswith(searchWord)):\n return i + 1\n \n return -1", "slug": "check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence", "post_title": "[Python3] Simple And Readable Solution With Explanation", "user": "VoidCupboard", "upvotes": 3, "views": 67, "problem_title": "check if a word occurs as a prefix of any word in a sentence", "number": 1455, "acceptance": 0.642, "difficulty": "Easy", "__index_level_0__": 21679, "question": "Given a sentence that consists of some words separated by a single space, and a searchWord, check if searchWord is a prefix of any word in sentence.\nReturn the index of the word in sentence (1-indexed) where searchWord is a prefix of this word. If searchWord is a prefix of more than one word, return the index of the first word (minimum index). If there is no such word return -1.\nA prefix of a string s is any leading contiguous substring of s.\n Example 1:\nInput: sentence = \"i love eating burger\", searchWord = \"burg\"\nOutput: 4\nExplanation: \"burg\" is prefix of \"burger\" which is the 4th word in the sentence.\nExample 2:\nInput: sentence = \"this problem is an easy problem\", searchWord = \"pro\"\nOutput: 2\nExplanation: \"pro\" is prefix of \"problem\" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.\nExample 3:\nInput: sentence = \"i am tired\", searchWord = \"you\"\nOutput: -1\nExplanation: \"you\" is not a prefix of any word in the sentence.\n Constraints:\n1 <= sentence.length <= 100\n1 <= searchWord.length <= 10\nsentence consists of lowercase English letters and spaces.\nsearchWord consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-vowels-in-a-substring-of-given-length/discuss/1504290/Python3-simple-soluton", "python_solutions": "class Solution:\n def maxVowels(self, s: str, k: int) -> int:\n x = 0\n for i in range(k):\n if s[i] in ('a', 'e', 'i', 'o', 'u'):\n x += 1\n ans = x\n for i in range(k,len(s)):\n if s[i] in ('a', 'e', 'i', 'o', 'u'):\n x += 1\n if s[i-k] in ('a', 'e', 'i', 'o', 'u'):\n x -= 1\n ans = max(ans,x)\n return ans", "slug": "maximum-number-of-vowels-in-a-substring-of-given-length", "post_title": "Python3 simple soluton", "user": "EklavyaJoshi", "upvotes": 2, "views": 89, "problem_title": "maximum number of vowels in a substring of given length", "number": 1456, "acceptance": 0.581, "difficulty": "Medium", "__index_level_0__": 21705, "question": "Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.\nVowel letters in English are 'a', 'e', 'i', 'o', and 'u'.\n Example 1:\nInput: s = \"abciiidef\", k = 3\nOutput: 3\nExplanation: The substring \"iii\" contains 3 vowel letters.\nExample 2:\nInput: s = \"aeiou\", k = 2\nOutput: 2\nExplanation: Any substring of length 2 contains 2 vowels.\nExample 3:\nInput: s = \"leetcode\", k = 3\nOutput: 2\nExplanation: \"lee\", \"eet\" and \"ode\" contain 2 vowels.\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters.\n1 <= k <= s.length" }, { "post_href": "https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/discuss/2573237/LeetCode-The-Hard-Way-Explained-Line-By-Line", "python_solutions": "class Solution:\n def pseudoPalindromicPaths (self, root: Optional[TreeNode], cnt = 0) -> int:\n if not root: return 0\n cnt ^= 1 << (root.val - 1)\n if root.left is None and root.right is None:\n return 1 if cnt & (cnt - 1) == 0 else 0\n return self.pseudoPalindromicPaths(root.left, cnt) + self.pseudoPalindromicPaths(root.right, cnt)", "slug": "pseudo-palindromic-paths-in-a-binary-tree", "post_title": "\ud83d\udd25 [LeetCode The Hard Way] \ud83d\udd25 Explained Line By Line", "user": "wingkwong", "upvotes": 68, "views": 2600, "problem_title": "pseudo palindromic paths in a binary tree", "number": 1457, "acceptance": 0.68, "difficulty": "Medium", "__index_level_0__": 21725, "question": "Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome.\nReturn the number of pseudo-palindromic paths going from the root node to leaf nodes.\n Example 1:\nInput: root = [2,3,1,3,1,null,1]\nOutput: 2 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).\nExample 2:\nInput: root = [2,1,1,1,3,null,null,null,null,null,1]\nOutput: 1 \nExplanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).\nExample 3:\nInput: root = [9]\nOutput: 1\n Constraints:\nThe number of nodes in the tree is in the range [1, 105].\n1 <= Node.val <= 9" }, { "post_href": "https://leetcode.com/problems/max-dot-product-of-two-subsequences/discuss/2613290/Python-Solution-or-DP-or-LCS", "python_solutions": "class Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n n=len(nums1)\n m=len(nums2)\n \n dp=[[0]*(m+1) for i in range(n+1)]\n for i in range(m+1):\n dp[0][i]=-1e9\n for i in range(n+1):\n dp[i][0]=-1e9\n \n for i in range(1, n+1):\n for j in range(1, m+1):\n val=nums1[i-1]*nums2[j-1]+max(0, dp[i-1][j-1])\n dp[i][j]=max(val, max(dp[i-1][j], dp[i][j-1]))\n return dp[n][m]", "slug": "max-dot-product-of-two-subsequences", "post_title": "Python Solution | DP | LCS", "user": "Siddharth_singh", "upvotes": 0, "views": 8, "problem_title": "max dot product of two subsequences", "number": 1458, "acceptance": 0.4629999999999999, "difficulty": "Hard", "__index_level_0__": 21749, "question": "Given two arrays nums1 and nums2.\nReturn the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.\nA subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).\n Example 1:\nInput: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\nOutput: 18\nExplanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\nTheir dot product is (2*3 + (-2)*(-6)) = 18.\nExample 2:\nInput: nums1 = [3,-2], nums2 = [2,-6,7]\nOutput: 21\nExplanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\nTheir dot product is (3*7) = 21.\nExample 3:\nInput: nums1 = [-1,-1], nums2 = [1,1]\nOutput: -1\nExplanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\nTheir dot product is -1.\n Constraints:\n1 <= nums1.length, nums2.length <= 500\n-1000 <= nums1[i], nums2[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/make-two-arrays-equal-by-reversing-subarrays/discuss/2730962/Easy-solution-using-dictionary-in-python", "python_solutions": "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n n, m = len(target), len(arr)\n if m > n:\n return False\n t = Counter(target)\n a = Counter(arr)\n for k, v in a.items():\n if k in t and v == t[k]:\n continue\n else:\n return False\n return True", "slug": "make-two-arrays-equal-by-reversing-subarrays", "post_title": "Easy solution using dictionary in python", "user": "ankurbhambri", "upvotes": 7, "views": 89, "problem_title": "make two arrays equal by reversing subarrays", "number": 1460, "acceptance": 0.722, "difficulty": "Easy", "__index_level_0__": 21751, "question": "You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.\nReturn true if you can make arr equal to target or false otherwise.\n Example 1:\nInput: target = [1,2,3,4], arr = [2,4,1,3]\nOutput: true\nExplanation: You can follow the next steps to convert arr to target:\n1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]\n2- Reverse subarray [4,2], arr becomes [1,2,4,3]\n3- Reverse subarray [4,3], arr becomes [1,2,3,4]\nThere are multiple ways to convert arr to target, this is not the only way to do so.\nExample 2:\nInput: target = [7], arr = [7]\nOutput: true\nExplanation: arr is equal to target without any reverses.\nExample 3:\nInput: target = [3,7,9], arr = [3,7,11]\nOutput: false\nExplanation: arr does not have value 9 and it can never be converted to target.\n Constraints:\ntarget.length == arr.length\n1 <= target.length <= 1000\n1 <= target[i] <= 1000\n1 <= arr[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/check-if-a-string-contains-all-binary-codes-of-size-k/discuss/2092441/Python-oror-2-Easy-oror-One-liner-with-explanation", "python_solutions": "class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool: \n return len({s[i:i+k] for i in range(len(s)-k+1)}) == 2 ** k", "slug": "check-if-a-string-contains-all-binary-codes-of-size-k", "post_title": "\u2705 Python || 2 Easy || One liner with explanation", "user": "constantine786", "upvotes": 26, "views": 1900, "problem_title": "check if a string contains all binary codes of size k", "number": 1461, "acceptance": 0.568, "difficulty": "Medium", "__index_level_0__": 21782, "question": "Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.\n Example 1:\nInput: s = \"00110110\", k = 2\nOutput: true\nExplanation: The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\nExample 2:\nInput: s = \"0110\", k = 1\nOutput: true\nExplanation: The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring. \nExample 3:\nInput: s = \"0110\", k = 2\nOutput: false\nExplanation: The binary code \"00\" is of length 2 and does not exist in the array.\n Constraints:\n1 <= s.length <= 5 * 105\ns[i] is either '0' or '1'.\n1 <= k <= 20" }, { "post_href": "https://leetcode.com/problems/course-schedule-iv/discuss/2337629/Python3-or-Solved-Using-Ancestors-of-every-DAG-Graph-Node-approach(Kahn's-Algo-BFS)", "python_solutions": "class Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n #Let m = len(prereqs) and z = len(queries)\n #Time: O(m + n + n*n + z) -> O(n^2)\n #Space: O(n*n + n + n*n + n + z) -> O(n^2)\n \n \n #process the prerequisites and build an adjacency list graph\n #where edges go from prerequisite to the course that depends on the prereq!\n n = numCourses\n #Adjacency List graph!\n adj = [set() for _ in range(n)]\n #indegrees array!\n indegrees = [0] * n\n #tell us every ith node's set of ancestors or all prereqs to take ith course!\n ancestors = [set() for _ in range(n)]\n #iterate through prereqs and update indegrees array as well as the adj list!\n for i in range(len(prerequisites)):\n prereq, main = prerequisites[i][0], prerequisites[i][1]\n adj[prereq].add(main)\n indegrees[main] += 1\n \n queue = deque()\n #iterate through the indegrees array and add all courses that have no \n #ancestors(no prerequisites to take it!)\n for a in range(len(indegrees)):\n #ath course can be taken without any prereqs -> first to be processed in\n #the Kahn's BFS algo!\n if(indegrees[a] == 0):\n queue.append(a)\n #proceed with Kahn's algo!\n while queue:\n cur_course = queue.pop()\n neighbors = adj[cur_course]\n for neighbor in neighbors:\n #neighbor has one less incoming edge!\n indegrees[neighbor] -= 1\n #current course is a prerequisite to every neighboring node!\n ancestors[neighbor].add(cur_course)\n #but also, all prereqs of cur_course is also indirectly a prereq\n #to each and every neighboring courses!\n ancestors[neighbor].update(ancestors[cur_course])\n #if neighboring node suddenly becomes can take with no prereqs,\n #add it to the queue!\n if(indegrees[neighbor] == 0):\n queue.append(neighbor)\n #once the algorithm ends, our ancestors array will have info regarding\n #prerequisites in order to take every course from 0 to n-1!\n output = []\n for query in queries:\n prereq2, main2 = query[0], query[1]\n all_prereqs = ancestors[main2]\n #check if prereq2 is an ancestor or required prereq course to take main2!\n if(prereq2 in all_prereqs):\n output.append(True)\n continue\n else:\n output.append(False)\n \n \n return output", "slug": "course-schedule-iv", "post_title": "Python3 | Solved Using Ancestors of every DAG Graph Node approach(Kahn's Algo BFS)", "user": "JOON1234", "upvotes": 1, "views": 28, "problem_title": "course schedule iv", "number": 1462, "acceptance": 0.489, "difficulty": "Medium", "__index_level_0__": 21813, "question": "There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.\nFor example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.\nPrerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.\nYou are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.\nReturn a boolean array answer, where answer[j] is the answer to the jth query.\n Example 1:\nInput: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\nOutput: [false,true]\nExplanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\nCourse 0 is not a prerequisite of course 1, but the opposite is true.\nExample 2:\nInput: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\nOutput: [false,false]\nExplanation: There are no prerequisites, and each course is independent.\nExample 3:\nInput: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\nOutput: [true,true]\n Constraints:\n2 <= numCourses <= 100\n0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)\nprerequisites[i].length == 2\n0 <= ai, bi <= n - 1\nai != bi\nAll the pairs [ai, bi] are unique.\nThe prerequisites graph has no cycles.\n1 <= queries.length <= 104\n0 <= ui, vi <= n - 1\nui != vi" }, { "post_href": "https://leetcode.com/problems/cherry-pickup-ii/discuss/1674033/Python3-DYNAMIC-PROGRAMMING-(*)-Explained", "python_solutions": "class Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n rows, cols = len(grid), len(grid[0])\n \n dp = [[[0]*(cols + 2) for _ in range(cols + 2)] for _ in range(rows + 1)]\n \n def get_next_max(row, col_r1, col_r2):\n res = 0\n for next_col_r1 in (col_r1 - 1, col_r1, col_r1 + 1):\n for next_col_r2 in (col_r2 - 1, col_r2, col_r2 + 1):\n res = max(res, dp[row + 1][next_col_r1 + 1][next_col_r2 + 1])\n\n return res\n \n for row in reversed(range(rows)):\n for col_r1 in range(min(cols, row + 2)):\n for col_r2 in range(max(0, cols - row - 1), cols):\n\n reward = grid[row][col_r1] + grid[row][col_r2]\n if col_r1 == col_r2:\n reward /= 2\n \n dp[row][col_r1 + 1][col_r2 + 1] = reward + get_next_max(row, col_r1, col_r2)\n \n return dp[0][1][cols]", "slug": "cherry-pickup-ii", "post_title": "\u2764 [Python3] DYNAMIC PROGRAMMING (*\u00b4\u2207\uff40)\uff89, Explained", "user": "artod", "upvotes": 14, "views": 506, "problem_title": "cherry pickup ii", "number": 1463, "acceptance": 0.701, "difficulty": "Hard", "__index_level_0__": 21816, "question": "You are given a rows x cols matrix grid representing a field of cherries where grid[i][j] represents the number of cherries that you can collect from the (i, j) cell.\nYou have two robots that can collect cherries for you:\nRobot #1 is located at the top-left corner (0, 0), and\nRobot #2 is located at the top-right corner (0, cols - 1).\nReturn the maximum number of cherries collection using both robots by following the rules below:\nFrom a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).\nWhen any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.\nWhen both robots stay in the same cell, only one takes the cherries.\nBoth robots cannot move outside of the grid at any moment.\nBoth robots should reach the bottom row in grid.\n Example 1:\nInput: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\nOutput: 24\nExplanation: Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\nCherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\nTotal of cherries: 12 + 12 = 24.\nExample 2:\nInput: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\nOutput: 28\nExplanation: Path of robot #1 and #2 are described in color green and blue respectively.\nCherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\nCherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\nTotal of cherries: 17 + 11 = 28.\n Constraints:\nrows == grid.length\ncols == grid[i].length\n2 <= rows, cols <= 70\n0 <= grid[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/discuss/1975858/Python-3-greater-Using-heap", "python_solutions": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n # approach 1: find 2 max numbers in 2 loops. T = O(n). S = O(1)\n\t\t# approach 2: sort and then get the last 2 max elements. T = O(n lg n). S = O(1)\n\t\t# approach 3: build min heap of size 2. T = O(n lg n). S = O(1)\n\t\t# python gives only min heap feature. heaq.heappush(list, item). heapq.heappop(list)\n \n heap = [-1]\n for num in nums:\n if num > heap[0]:\n if len(heap) == 2:\n heapq.heappop(heap)\n heapq.heappush(heap, num)\n \n return (heap[0]-1) * (heap[1]-1)", "slug": "maximum-product-of-two-elements-in-an-array", "post_title": "Python 3 -> Using heap", "user": "mybuddy29", "upvotes": 3, "views": 195, "problem_title": "maximum product of two elements in an array", "number": 1464, "acceptance": 0.794, "difficulty": "Easy", "__index_level_0__": 21834, "question": "Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).\n Example 1:\nInput: nums = [3,4,5,2]\nOutput: 12 \nExplanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. \nExample 2:\nInput: nums = [1,5,4,5]\nOutput: 16\nExplanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.\nExample 3:\nInput: nums = [3,7]\nOutput: 12\n Constraints:\n2 <= nums.length <= 500\n1 <= nums[i] <= 10^3" }, { "post_href": "https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/discuss/2227297/Python-easy-solution", "python_solutions": "class Solution:\n def maxArea(self, h: int, w: int, hc: List[int], vc: List[int]) -> int:\n \n hc.sort()\n vc.sort()\n \n maxh = hc[0]\n maxv = vc[0]\n \n for i in range(1, len(hc)):\n maxh = max(maxh, hc[i] - hc[i-1])\n maxh = max(maxh, h - hc[-1])\n \n for i in range(1, len(vc)):\n maxv = max(maxv, vc[i] - vc[i-1])\n maxv = max(maxv, w - vc[-1])\n \n return maxh*maxv % (10**9 + 7)", "slug": "maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts", "post_title": "Python easy solution", "user": "lokeshsenthilkumar", "upvotes": 3, "views": 81, "problem_title": "maximum area of a piece of cake after horizontal and vertical cuts", "number": 1465, "acceptance": 0.409, "difficulty": "Medium", "__index_level_0__": 21882, "question": "You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:\nhorizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and\nverticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.\nReturn the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 109 + 7.\n Example 1:\nInput: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\nOutput: 4 \nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.\nExample 2:\nInput: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\nOutput: 6\nExplanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.\nExample 3:\nInput: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\nOutput: 9\n Constraints:\n2 <= h, w <= 109\n1 <= horizontalCuts.length <= min(h - 1, 105)\n1 <= verticalCuts.length <= min(w - 1, 105)\n1 <= horizontalCuts[i] < h\n1 <= verticalCuts[i] < w\nAll the elements in horizontalCuts are distinct.\nAll the elements in verticalCuts are distinct." }, { "post_href": "https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/1071235/Pythonor-Easy-and-fast-or-Beats-99", "python_solutions": "class Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n cmap = {0}\n count = 0\n dq = deque(connections)\n while dq:\n u, v = dq.popleft()\n if v in cmap:\n cmap.add(u)\n elif u in cmap:\n cmap.add(v)\n count += 1\n else:\n dq.append([u, v])\n return count", "slug": "reorder-routes-to-make-all-paths-lead-to-the-city-zero", "post_title": "Python| Easy and fast | Beats 99%", "user": "SlavaHerasymov", "upvotes": 8, "views": 406, "problem_title": "reorder routes to make all paths lead to the city zero", "number": 1466, "acceptance": 0.618, "difficulty": "Medium", "__index_level_0__": 21926, "question": "" }, { "post_href": "https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/discuss/1214891/Python3-top-down-dp", "python_solutions": "class Solution:\n def getProbability(self, balls: List[int]) -> float:\n n = sum(balls)//2\n \n @cache \n def fn(i, s0, s1, c0, c1):\n \"\"\"Return number of ways to distribute boxes successfully (w/o considering relative order).\"\"\"\n if s0 > n or s1 > n: return 0 # impossible \n if i == len(balls): return int(c0 == c1)\n ans = 0 \n for x in range(balls[i]+1): \n ans += fn(i+1, s0+x, s1+balls[i]-x, c0+(x > 0), c1+(x < balls[i])) * comb(balls[i], x)\n return ans\n \n return fn(0, 0, 0, 0, 0) / comb(2*n, n)", "slug": "probability-of-a-two-boxes-having-the-same-number-of-distinct-balls", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 0, "views": 130, "problem_title": "probability of a two boxes having the same number of distinct balls", "number": 1467, "acceptance": 0.611, "difficulty": "Hard", "__index_level_0__": 21939, "question": "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.\nAll the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).\nPlease note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).\nReturn the probability that the two boxes have the same number of distinct balls. Answers within 10-5 of the actual value will be accepted as correct.\n Example 1:\nInput: balls = [1,1]\nOutput: 1.00000\nExplanation: Only 2 ways to divide the balls equally:\n- A ball of color 1 to box 1 and a ball of color 2 to box 2\n- A ball of color 2 to box 1 and a ball of color 1 to box 2\nIn both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1\nExample 2:\nInput: balls = [2,1,1]\nOutput: 0.66667\nExplanation: We have the set of balls [1, 1, 2, 3]\nThis set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equal probability (i.e. 1/12):\n[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]\nAfter that, we add the first two balls to the first box and the second two balls to the second box.\nWe can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\nProbability is 8/12 = 0.66667\nExample 3:\nInput: balls = [1,2,1,2]\nOutput: 0.60000\nExplanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\nProbability = 108 / 180 = 0.6\n Constraints:\n1 <= balls.length <= 8\n1 <= balls[i] <= 6\nsum(balls) is even." }, { "post_href": "https://leetcode.com/problems/shuffle-the-array/discuss/941189/Simple-Python-Solution", "python_solutions": "class Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n l=[]\n for i in range(n):\n l.append(nums[i])\n\t\t\tl.append(nums[n+i])\n return l", "slug": "shuffle-the-array", "post_title": "Simple Python Solution", "user": "lokeshsenthilkumar", "upvotes": 10, "views": 947, "problem_title": "shuffle the array", "number": 1470, "acceptance": 0.885, "difficulty": "Easy", "__index_level_0__": 21940, "question": "Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\nReturn the array in the form [x1,y1,x2,y2,...,xn,yn].\n Example 1:\nInput: nums = [2,5,1,3,4,7], n = 3\nOutput: [2,3,5,4,1,7] \nExplanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\nExample 2:\nInput: nums = [1,2,3,4,4,3,2,1], n = 4\nOutput: [1,4,2,3,3,2,4,1]\nExample 3:\nInput: nums = [1,1,2,2], n = 2\nOutput: [1,2,1,2]\n Constraints:\n1 <= n <= 500\nnums.length == 2n\n1 <= nums[i] <= 10^3" }, { "post_href": "https://leetcode.com/problems/the-k-strongest-values-in-an-array/discuss/2516738/easy-python-solution", "python_solutions": "class Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n new_arr = []\n arr.sort()\n med = arr[int((len(arr) - 1)//2)]\n for num in arr : \n new_arr.append([int(abs(num - med)), num])\n \n new_arr = sorted(new_arr, key = lambda x : (x[0], x[1]))\n \n output, counter = [], 0\n for i in reversed(range(len(new_arr))) : \n output.append(new_arr[i][1])\n counter += 1 \n if counter == k : \n return output \n \n return output", "slug": "the-k-strongest-values-in-an-array", "post_title": "easy python solution", "user": "sghorai", "upvotes": 0, "views": 15, "problem_title": "the k strongest values in an array", "number": 1471, "acceptance": 0.602, "difficulty": "Medium", "__index_level_0__": 21987, "question": "Given an array of integers arr and an integer k.\nA value arr[i] is said to be stronger than a value arr[j] if |arr[i] - m| > |arr[j] - m| where m is the median of the array.\nIf |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].\nReturn a list of the strongest k values in the array. return the answer in any arbitrary order.\nMedian is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position ((n - 1) / 2) in the sorted list (0-indexed).\nFor arr = [6, -3, 7, 2, 11], n = 5 and the median is obtained by sorting the array arr = [-3, 2, 6, 7, 11] and the median is arr[m] where m = ((5 - 1) / 2) = 2. The median is 6.\nFor arr = [-7, 22, 17,\u20093], n = 4 and the median is obtained by sorting the array arr = [-7, 3, 17, 22] and the median is arr[m] where m = ((4 - 1) / 2) = 1. The median is 3.\n Example 1:\nInput: arr = [1,2,3,4,5], k = 2\nOutput: [5,1]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also accepted answer.\nPlease note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.\nExample 2:\nInput: arr = [1,1,3,5,5], k = 2\nOutput: [5,5]\nExplanation: Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].\nExample 3:\nInput: arr = [6,7,11,7,6,8], k = 5\nOutput: [11,8,6,6,7]\nExplanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\nAny permutation of [11,8,6,6,7] is accepted.\n Constraints:\n1 <= arr.length <= 105\n-105 <= arr[i] <= 105\n1 <= k <= arr.length" }, { "post_href": "https://leetcode.com/problems/paint-house-iii/discuss/1397505/Explained-Commented-Top-Down-greater-Bottom-Up-greater-Space-Optimized-Bottom-Up", "python_solutions": "class Solution:\n def minCost1(self, houses: List[int], cost: List[List[int]], R: int, C: int, target: int) -> int:\n # think as if we are traveling downward\n # at any point, if switch our column then (target--)\n \n @functools.cache\n def dp(x,y,k): # O(100*20*100) time space\n if x == R:\n return 0 if k == 0 else math.inf\n elif k <= 0: \n return math.inf\n \n # if this house is already colored, dont recolor!!\n if houses[x] > 0 and houses[x] != y+1: return math.inf\n \n cur_cost = 0 if houses[x] == y+1 else cost[x][y] \n \n # now try all columns! O(20) time\n res = math.inf\n for c in range(C):\n if c == y:\n res = min(res, cur_cost + dp(x+1,c,k))\n else:\n res = min(res, cur_cost + dp(x+1,c,k-1))\n # print('dp',x,y,k,'=',res)\n return res\n \n ans = min(dp(0,y,target) for y in range(C))\n \n return -1 if ans == math.inf else ans", "slug": "paint-house-iii", "post_title": "Explained Commented Top Down -> Bottom Up -> Space Optimized Bottom Up", "user": "yozaam", "upvotes": 3, "views": 257, "problem_title": "paint house iii", "number": 1473, "acceptance": 0.619, "difficulty": "Hard", "__index_level_0__": 21994, "question": "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.\nA neighborhood is a maximal group of continuous houses that are painted with the same color.\nFor example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].\nGiven an array houses, an m x n matrix cost and an integer target where:\nhouses[i]: is the color of the house i, and 0 if the house is not painted yet.\ncost[i][j]: is the cost of paint the house i with the color j + 1.\nReturn the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.\n Example 1:\nInput: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 9\nExplanation: Paint houses of this way [1,2,2,1,1]\nThis array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\nCost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\nExample 2:\nInput: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\nOutput: 11\nExplanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\nThis array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \nCost of paint the first and last house (10 + 1) = 11.\nExample 3:\nInput: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\nOutput: -1\nExplanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n Constraints:\nm == houses.length == cost.length\nn == cost[i].length\n1 <= m <= 100\n1 <= n <= 20\n1 <= target <= m\n0 <= houses[i] <= n\n1 <= cost[i][j] <= 104" }, { "post_href": "https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/discuss/685429/PythonPython3-Final-Prices-with-a-Special-Discount-in-a-Shop", "python_solutions": "class Solution:\n def finalPrices(self, prices: List[int]) -> List[int]:\n len_prices = len(prices)\n i = 0\n while i <= len_prices-2:\n for j in range(i+1, len(prices)):\n if prices[i] >= prices[j] and j > i:\n prices[i] = prices[i] - prices[j]\n break\n \n i += 1\n \n return prices", "slug": "final-prices-with-a-special-discount-in-a-shop", "post_title": "[Python/Python3] Final Prices with a Special Discount in a Shop", "user": "newborncoder", "upvotes": 4, "views": 541, "problem_title": "final prices with a special discount in a shop", "number": 1475, "acceptance": 0.755, "difficulty": "Easy", "__index_level_0__": 22005, "question": "You are given an integer array prices where prices[i] is the price of the ith item in a shop.\nThere is a special discount for items in the shop. If you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i]. Otherwise, you will not receive any discount at all.\nReturn an integer array answer where answer[i] is the final price you will pay for the ith item of the shop, considering the special discount.\n Example 1:\nInput: prices = [8,4,6,2,3]\nOutput: [4,2,4,2,3]\nExplanation: \nFor item 0 with price[0]=8 you will receive a discount equivalent to prices[1]=4, therefore, the final price you will pay is 8 - 4 = 4.\nFor item 1 with price[1]=4 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 4 - 2 = 2.\nFor item 2 with price[2]=6 you will receive a discount equivalent to prices[3]=2, therefore, the final price you will pay is 6 - 2 = 4.\nFor items 3 and 4 you will not receive any discount at all.\nExample 2:\nInput: prices = [1,2,3,4,5]\nOutput: [1,2,3,4,5]\nExplanation: In this case, for all items, you will not receive any discount at all.\nExample 3:\nInput: prices = [10,1,1,6]\nOutput: [9,0,1,6]\n Constraints:\n1 <= prices.length <= 500\n1 <= prices[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/discuss/1987219/Python-Sliding-Window-O(n)-with-detail-comments.", "python_solutions": "class Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n l, windowSum, res = 0, 0, float('inf')\n min_till = [float('inf')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n for r, num in enumerate(arr): # r:right pointer and index of num in arr\n windowSum += num\n while windowSum > target: \n\t\t\t# when the sum of current window is larger then target, shrink the left end of the window one by one until windowSum <= target\n windowSum -= arr[l]\n l += 1\n\t\t\t# the case when we found a new target sub-array, i.e. current window\n if windowSum == target:\n\t\t\t # length of current window\n curLen = r - l + 1\n\t\t\t\t# min_till[l - 1]: the subarray with min len up till the previous position of left end of the current window: \n\t\t\t\t# avoid overlap with cur window\n\t\t\t\t# new_sum_of_two_subarray = length of current window + the previous min length of target subarray without overlapping\n\t\t\t\t# , if < res, update res.\n res = min(res, curLen + min_till[l - 1])\n\t\t\t\t# Everytime we found a target window, update the min_till of current right end of the window, \n\t\t\t\t# for future use when sum up to new length of sum_of_two_subarray and update the res.\n min_till[r] = min(curLen, min_till[r - 1])\n else:\n\t\t\t# If windowSum < target: window with current arr[r] as right end does not have any target subarry, \n\t\t\t# the min_till[r] doesn't get any new minimum update, i.e it equals to previous min_till at index r - 1. \n min_till[r] = min_till[r - 1]\n return res if res < float('inf') else -1\n\t\nTime = O(n): when sliding the window, left and right pointers traverse the array once.\nSpace = O(n): we use one additional list min_till[] to record min length of target subarray till index i.", "slug": "find-two-non-overlapping-sub-arrays-each-with-target-sum", "post_title": "Python - Sliding Window - O(n) with detail comments.", "user": "changyou1009", "upvotes": 5, "views": 323, "problem_title": "find two non overlapping sub arrays each with target sum", "number": 1477, "acceptance": 0.37, "difficulty": "Medium", "__index_level_0__": 22034, "question": "You are given an array of integers arr and an integer target.\nYou have to find two non-overlapping sub-arrays of arr each with a sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.\nReturn the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.\n Example 1:\nInput: arr = [3,2,2,4,3], target = 3\nOutput: 2\nExplanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.\nExample 2:\nInput: arr = [7,3,4,7], target = 7\nOutput: 2\nExplanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.\nExample 3:\nInput: arr = [4,3,2,6,2,3,4], target = 6\nOutput: -1\nExplanation: We have only one sub-array of sum = 6.\n Constraints:\n1 <= arr.length <= 105\n1 <= arr[i] <= 1000\n1 <= target <= 108" }, { "post_href": "https://leetcode.com/problems/allocate-mailboxes/discuss/1496112/Beginner-Friendly-oror-Easy-to-understand-oror-DP-solution", "python_solutions": "class Solution:\ndef minDistance(self, houses: List[int], k: int) -> int:\n \n n = len(houses)\n houses.sort()\n cost = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n):\n for j in range(i+1,n):\n mid_house = houses[(i+j)//2]\n for t in range(i,j+1):\n cost[i][j]+= abs(mid_house-houses[t])\n \n @lru_cache(None)\n def dp(k,ind):\n if k==0 and ind==n: return 0\n if k==0 or ind==n: return float('inf')\n res = float('inf')\n for j in range(ind,n):\n c = cost[ind][j]\n res = min(res, c + dp(k-1,j+1))\n \n return res\n \n return dp(k,0)", "slug": "allocate-mailboxes", "post_title": "\ud83d\udccc\ud83d\udccc Beginner-Friendly || Easy-to-understand || DP solution \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 3, "views": 379, "problem_title": "allocate mailboxes", "number": 1478, "acceptance": 0.556, "difficulty": "Hard", "__index_level_0__": 22041, "question": "Given the array houses where houses[i] is the location of the ith house along a street and an integer k, allocate k mailboxes in the street.\nReturn the minimum total distance between each house and its nearest mailbox.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\nInput: houses = [1,4,8,10,20], k = 3\nOutput: 5\nExplanation: Allocate mailboxes in position 3, 9 and 20.\nMinimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \nExample 2:\nInput: houses = [2,3,5,12,18], k = 2\nOutput: 9\nExplanation: Allocate mailboxes in position 3 and 14.\nMinimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n Constraints:\n1 <= k <= houses.length <= 100\n1 <= houses[i] <= 104\nAll the integers of houses are unique." }, { "post_href": "https://leetcode.com/problems/running-sum-of-1d-array/discuss/2306599/Easy-to-understand-Python-solution", "python_solutions": "class Solution(object):\n def runningSum(self, nums):\n result = []\n current_sum = 0\n for i in range(0, len(nums)):\n result.append(current_sum + nums[i])\n current_sum = result[i]\n return result", "slug": "running-sum-of-1d-array", "post_title": "Easy to understand Python solution", "user": "Balance-Coffee", "upvotes": 13, "views": 324, "problem_title": "running sum of 1d array", "number": 1480, "acceptance": 0.892, "difficulty": "Easy", "__index_level_0__": 22044, "question": "Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]\u2026nums[i]).\nReturn the running sum of nums.\n Example 1:\nInput: nums = [1,2,3,4]\nOutput: [1,3,6,10]\nExplanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].\nExample 2:\nInput: nums = [1,1,1,1,1]\nOutput: [1,2,3,4,5]\nExplanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].\nExample 3:\nInput: nums = [3,1,2,10,1]\nOutput: [3,4,6,16,17]\n Constraints:\n1 <= nums.length <= 1000\n-10^6 <= nums[i] <= 10^6" }, { "post_href": "https://leetcode.com/problems/least-number-of-unique-integers-after-k-removals/discuss/1269930/Beats-99-runtime-oror-98-memory-oror-python-oror-easy", "python_solutions": "class Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\n count = Counter(arr)\n ans = len(count)\n for i in sorted(count.values()):\n k -= i\n if k < 0:\n break\n ans -= 1\n return ans", "slug": "least-number-of-unique-integers-after-k-removals", "post_title": "Beats 99% runtime || 98% memory || python || easy", "user": "chikushen99", "upvotes": 11, "views": 1000, "problem_title": "least number of unique integers after k removals", "number": 1481, "acceptance": 0.569, "difficulty": "Medium", "__index_level_0__": 22096, "question": "Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.\n Example 1:\nInput: arr = [5,5,4], k = 1\nOutput: 1\nExplanation: Remove the single 4, only 5 is left.\nExample 2:\nInput: arr = [4,3,1,1,3,3,2], k = 3\nOutput: 2\nExplanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\n Constraints:\n1 <= arr.length <= 10^5\n1 <= arr[i] <= 10^9\n0 <= k <= arr.length" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-days-to-make-m-bouquets/discuss/707611/Python-Binary-Search-or-Mathematical-function-definition-(75-Speed)", "python_solutions": "class Solution:\n def checker(self,arr, d, m, k) -> bool:\n '''\n d -> days\n m -> bouquets\n k -> adjacent flowers\n \n return bool\n '''\n arr = [10**9] + arr + [10**9] #appending array with maximum values\n idx = []\n for i in range(len(arr)):\n if arr[i] > d:\n idx.append(i)\n cnt = 0\n for i in range(len(idx)-1):\n # how many bouquet can we make out of an interval of valid flowers \n cnt += (idx[i+1] - idx[i] - 1) // k\n \n # return if count >= m\n return cnt >= m\n\n def minDays(self, arr: List[int], m: int, k: int) -> int:\n if m*k > len(arr):\n return -1\n lo, hi = 1, max(arr)\n \n while(hi >= lo):\n mid = (hi+lo)//2\n if(self.checker(arr, mid, m, k) == True):\n hi = mid\n else:\n lo = mid+1\n if(hi == lo): break\n \n if self.checker(arr, lo, m, k):\n return lo\n else:\n return hi", "slug": "minimum-number-of-days-to-make-m-bouquets", "post_title": "[Python] Binary Search | Mathematical function definition (75% Speed)", "user": "uds5501", "upvotes": 3, "views": 223, "problem_title": "minimum number of days to make m bouquets", "number": 1482, "acceptance": 0.557, "difficulty": "Medium", "__index_level_0__": 22104, "question": "You are given an integer array bloomDay, an integer m and an integer k.\nYou want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.\nThe garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.\nReturn the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return -1.\n Example 1:\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 1\nOutput: 3\nExplanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\nWe need 3 bouquets each should contain 1 flower.\nAfter day 1: [x, _, _, _, _] // we can only make one bouquet.\nAfter day 2: [x, _, _, _, x] // we can only make two bouquets.\nAfter day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.\nExample 2:\nInput: bloomDay = [1,10,3,10,2], m = 3, k = 2\nOutput: -1\nExplanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.\nExample 3:\nInput: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\nOutput: 12\nExplanation: We need 2 bouquets each should have 3 flowers.\nHere is the garden after the 7 and 12 days:\nAfter day 7: [x, x, x, x, _, x, x]\nWe can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.\nAfter day 12: [x, x, x, x, x, x, x]\nIt is obvious that we can make two bouquets in different ways.\n Constraints:\nbloomDay.length == n\n1 <= n <= 105\n1 <= bloomDay[i] <= 109\n1 <= m <= 106\n1 <= k <= n" }, { "post_href": "https://leetcode.com/problems/xor-operation-in-an-array/discuss/942598/Simple-Python-Solutions", "python_solutions": "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n ans=0\n for i in range(n):\n ans^=start+(2*i)\n return ans", "slug": "xor-operation-in-an-array", "post_title": "Simple Python Solutions", "user": "lokeshsenthilkumar", "upvotes": 8, "views": 604, "problem_title": "xor operation in an array", "number": 1486, "acceptance": 0.8420000000000001, "difficulty": "Easy", "__index_level_0__": 22117, "question": "You are given an integer n and an integer start.\nDefine an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.\nReturn the bitwise XOR of all elements of nums.\n Example 1:\nInput: n = 5, start = 0\nOutput: 8\nExplanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\nWhere \"^\" corresponds to bitwise XOR operator.\nExample 2:\nInput: n = 4, start = 3\nOutput: 8\nExplanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.\n Constraints:\n1 <= n <= 1000\n0 <= start <= 1000\nn == nums.length" }, { "post_href": "https://leetcode.com/problems/making-file-names-unique/discuss/1646944/Very-simple-python3-solution-using-hashmap-and-comments", "python_solutions": "class Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # names : array of names\n # n : size of names\n \n # create folders at the i'th minute for each name = names[i]\n # If name was used previously, append a suffix \"(k)\" - note parenthesis - where k is the smallest pos int\n \n # return an array of strings where ans[i] is the actual saved variant of names[i]\n \n n = len(names)\n \n dictNames = {}\n ans = ['']*n\n \n # enumerate to grab index so we can return ans list in order\n for idx, name in enumerate(names):\n # check if we have seen this name before\n if name in dictNames:\n # if we have grab the next k using last successful low (k) suffix\n k = dictNames[name]\n # track the name we started so we can update the dict\n namestart = name\n # cycle through values of increasing k until we are not in a previously used name\n while name in dictNames:\n name = namestart + f\"({k})\"\n k += 1\n # update the name we started with to the new lowest value of k\n dictNames[namestart] = k\n # add the new name with k = 1 so if we see this name with the suffix\n dictNames[name] = 1\n else:\n # we havent seen this name so lets start with 1\n dictNames[name] = 1\n # build the solution\n ans[idx] = name\n return ans", "slug": "making-file-names-unique", "post_title": "Very simple python3 solution using hashmap and comments", "user": "jumpstarter", "upvotes": 3, "views": 307, "problem_title": "making file names unique", "number": 1487, "acceptance": 0.359, "difficulty": "Medium", "__index_level_0__": 22153, "question": "Given an array of strings names of size n. You will create n folders in your file system such that, at the ith minute, you will create a folder with the name names[i].\nSince two files cannot have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.\nReturn an array of strings of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.\n Example 1:\nInput: names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nOutput: [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\nExplanation: Let's see how the file system creates folder names:\n\"pes\" --> not assigned before, remains \"pes\"\n\"fifa\" --> not assigned before, remains \"fifa\"\n\"gta\" --> not assigned before, remains \"gta\"\n\"pes(2019)\" --> not assigned before, remains \"pes(2019)\"\nExample 2:\nInput: names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\nOutput: [\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\nExplanation: Let's see how the file system creates folder names:\n\"gta\" --> not assigned before, remains \"gta\"\n\"gta(1)\" --> not assigned before, remains \"gta(1)\"\n\"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n\"avalon\" --> not assigned before, remains \"avalon\"\nExample 3:\nInput: names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\nOutput: [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\nExplanation: When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".\n Constraints:\n1 <= names.length <= 5 * 104\n1 <= names[i].length <= 20\nnames[i] consists of lowercase English letters, digits, and/or round brackets." }, { "post_href": "https://leetcode.com/problems/avoid-flood-in-the-city/discuss/1842629/Python-easy-to-read-and-understand-or-heap", "python_solutions": "class Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n pq = []\n fill = set()\n d = collections.defaultdict(list)\n ans = []\n \n for i, rain in enumerate(rains):\n d[rain].append(i)\n \n for rain in rains:\n if rain > 0:\n if rain in fill:\n return []\n fill.add(rain)\n d[rain].pop(0)\n if d[rain]:\n heapq.heappush(pq, d[rain][0])\n ans.append(-1)\n else:\n if pq:\n ind = heapq.heappop(pq)\n ans.append(rains[ind])\n fill.remove(rains[ind])\n else:\n ans.append(1)\n \n return ans", "slug": "avoid-flood-in-the-city", "post_title": "Python easy to read and understand | heap", "user": "sanial2001", "upvotes": 0, "views": 193, "problem_title": "avoid flood in the city", "number": 1488, "acceptance": 0.261, "difficulty": "Medium", "__index_level_0__": 22158, "question": "Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake that is full of water, there will be a flood. Your goal is to avoid floods in any lake.\nGiven an integer array rains where:\nrains[i] > 0 means there will be rains over the rains[i] lake.\nrains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.\nReturn an array ans where:\nans.length == rains.length\nans[i] == -1 if rains[i] > 0.\nans[i] is the lake you choose to dry in the ith day if rains[i] == 0.\nIf there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.\nNotice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.\n Example 1:\nInput: rains = [1,2,3,4]\nOutput: [-1,-1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day full lakes are [1,2,3]\nAfter the fourth day full lakes are [1,2,3,4]\nThere's no day to dry any lake and there is no flood in any lake.\nExample 2:\nInput: rains = [1,2,0,0,2,1]\nOutput: [-1,-1,2,1,-1,-1]\nExplanation: After the first day full lakes are [1]\nAfter the second day full lakes are [1,2]\nAfter the third day, we dry lake 2. Full lakes are [1]\nAfter the fourth day, we dry lake 1. There is no full lakes.\nAfter the fifth day, full lakes are [2].\nAfter the sixth day, full lakes are [1,2].\nIt is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.\nExample 3:\nInput: rains = [1,2,0,1,2]\nOutput: []\nExplanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\nAfter that, it will rain over lakes [1,2]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.\n Constraints:\n1 <= rains.length <= 105\n0 <= rains[i] <= 109" }, { "post_href": "https://leetcode.com/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/discuss/702027/Python3-Prim's-algo", "python_solutions": "class Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n graph = dict()\n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n ref = self.mst(n, graph)\n critical, pseudo = [], []\n for i in range(len(edges)):\n if self.mst(n, graph, exclude=edges[i][:2]) > ref: critical.append(i)\n elif self.mst(n, graph, init=edges[i]) == ref: pseudo.append(i)\n return [critical, pseudo]\n \n \n def mst(self, n, graph, init=None, exclude=None):\n \"\"\"Return weight of MST of given graph using Prim's algo\"\"\"\n\n def visit(u): \n \"\"\"Mark node and put its edges to priority queue\"\"\"\n marked[u] = True\n for v, w in graph.get(u, []):\n if exclude and u in exclude and v in exclude: continue\n if not marked[v]: heappush(pq, (w, u, v))\n \n ans = 0\n marked = [False]*n\n pq = [] #min prioirty queue\n \n if init: \n u, v, w = init\n ans += w\n marked[u] = marked[v] = True\n visit(u) or visit(v)\n else:\n visit(0)\n\n while pq: \n w, u, v = heappop(pq)\n if marked[u] and marked[v]: continue\n ans += w\n if not marked[u]: visit(u)\n if not marked[v]: visit(v)\n \n return ans if all(marked) else inf", "slug": "find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree", "post_title": "[Python3] Prim's algo", "user": "ye15", "upvotes": 4, "views": 355, "problem_title": "find critical and pseudo critical edges in minimum spanning tree", "number": 1489, "acceptance": 0.526, "difficulty": "Hard", "__index_level_0__": 22160, "question": "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.\nFind all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.\nNote that you can return the indices of the edges in any order.\n Example 1:\nInput: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\nOutput: [[0,1],[2,3,4,5]]\nExplanation: The figure above describes the graph.\nThe following figure shows all the possible MSTs:\nNotice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\nThe edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\nExample 2:\nInput: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\nOutput: [[],[0,1,2,3]]\nExplanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n Constraints:\n2 <= n <= 100\n1 <= edges.length <= min(200, n * (n - 1) / 2)\nedges[i].length == 3\n0 <= ai < bi < n\n1 <= weighti <= 1000\nAll pairs (ai, bi) are distinct." }, { "post_href": "https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/discuss/2213970/Python3-one-pass-solution-beats-99.20-of-submissions", "python_solutions": "class Solution:\n def average(self, salary: List[int]) -> float:\n minimum = float(\"inf\")\n maximum = float(\"-inf\")\n \n i = 0\n sums = 0\n while i int:\n factors = []\n for i in range(1,n+1):\n if n % i == 0:\n factors.append(i)\n if k > len(factors):\n return -1\n else:\n return factors[k-1]", "slug": "the-kth-factor-of-n", "post_title": "Python3 simple solution using list", "user": "EklavyaJoshi", "upvotes": 1, "views": 139, "problem_title": "the kth factor of n", "number": 1492, "acceptance": 0.624, "difficulty": "Medium", "__index_level_0__": 22210, "question": "You are given two positive integers n and k. A factor of an integer n is defined as an integer i where n % i == 0.\nConsider a list of all factors of n sorted in ascending order, return the kth factor in this list or return -1 if n has less than k factors.\n Example 1:\nInput: n = 12, k = 3\nOutput: 3\nExplanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.\nExample 2:\nInput: n = 7, k = 2\nOutput: 7\nExplanation: Factors list is [1, 7], the 2nd factor is 7.\nExample 3:\nInput: n = 4, k = 4\nOutput: -1\nExplanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.\n Constraints:\n1 <= k <= n <= 1000\n Follow up:\nCould you solve this problem in less than O(n) complexity?" }, { "post_href": "https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/discuss/708121/Easy-Solution-without-DP-Simple-Pictorial-Explanation-or-Python-Solution.", "python_solutions": "class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n m=0\n l=len(nums)\n one=True\n for i in range(0,l):\n if nums[i]==0:\n one=False\n left=i-1\n right=i+1\n ones=0\n while left>=0:\n if nums[left]==1:\n ones=ones+1\n left=left-1\n else:\n break\n while rightm:\n m=ones\n if one:\n return l-1\n return m", "slug": "longest-subarray-of-1s-after-deleting-one-element", "post_title": "[Easy Solution without DP] Simple Pictorial Explanation | Python Solution.", "user": "lazerx", "upvotes": 12, "views": 1100, "problem_title": "longest subarray of 1s after deleting one element", "number": 1493, "acceptance": 0.602, "difficulty": "Medium", "__index_level_0__": 22239, "question": "Given a binary array nums, you should delete one element from it.\nReturn the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.\n Example 1:\nInput: nums = [1,1,0,1]\nOutput: 3\nExplanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\nExample 2:\nInput: nums = [0,1,1,1,0,1,1,0,1]\nOutput: 5\nExplanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\nExample 3:\nInput: nums = [1,1,1]\nOutput: 2\nExplanation: You must delete one element.\n Constraints:\n1 <= nums.length <= 105\nnums[i] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/parallel-courses-ii/discuss/1111255/Python3-dp", "python_solutions": "class Solution:\n def minNumberOfSemesters(self, n: int, dependencies: List[List[int]], k: int) -> int:\n pre = [0]*n # prerequisites \n for u, v in dependencies: \n pre[v-1] |= 1 << (u-1) \n \n @cache\n def fn(mask): \n \"\"\"Return min semesters to take remaining courses.\"\"\"\n if mask == (1 << n) - 1: return 0 # all courses taken \n can = [] # available courses \n for i in range(n): \n if not mask & 1 << i and mask & pre[i] == pre[i]: \n can.append(i)\n \n ans = inf\n for courses in combinations(can, min(k, len(can))): \n temp = mask | reduce(lambda x, y: x | 1 << y, courses, 0)\n ans = min(ans, 1 + fn(temp))\n return ans \n \n return fn(0)", "slug": "parallel-courses-ii", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 2, "views": 171, "problem_title": "parallel courses ii", "number": 1494, "acceptance": 0.311, "difficulty": "Hard", "__index_level_0__": 22268, "question": "You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei has to be taken before course nextCoursei. Also, you are given the integer k.\nIn one semester, you can take at most k courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.\nReturn the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.\n Example 1:\nInput: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2\nOutput: 3\nExplanation: The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3.\nIn the second semester, you can take course 1.\nIn the third semester, you can take course 4.\nExample 2:\nInput: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2\nOutput: 4\nExplanation: The figure above represents the given graph.\nIn the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.\nIn the second semester, you can take course 4.\nIn the third semester, you can take course 1.\nIn the fourth semester, you can take course 5.\n Constraints:\n1 <= n <= 15\n1 <= k <= n\n0 <= relations.length <= n * (n-1) / 2\nrelations[i].length == 2\n1 <= prevCoursei, nextCoursei <= n\nprevCoursei != nextCoursei\nAll the pairs [prevCoursei, nextCoursei] are unique.\nThe given graph is a directed acyclic graph." }, { "post_href": "https://leetcode.com/problems/path-crossing/discuss/1132447/Python3-simple-solution-faster-than-99-users", "python_solutions": "class Solution:\n def isPathCrossing(self, path: str) -> bool:\n l = [(0,0)]\n x,y = 0,0\n for i in path:\n if i == 'N':\n y += 1\n if i == 'S':\n y -= 1\n if i == 'E':\n x += 1\n if i == 'W':\n x -= 1\n if (x,y) in l:\n return True\n else:\n l.append((x,y))\n return False", "slug": "path-crossing", "post_title": "Python3 simple solution faster than 99% users", "user": "EklavyaJoshi", "upvotes": 4, "views": 252, "problem_title": "path crossing", "number": 1496, "acceptance": 0.5579999999999999, "difficulty": "Easy", "__index_level_0__": 22272, "question": "Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.\nReturn true if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited. Return false otherwise.\n Example 1:\nInput: path = \"NES\"\nOutput: false \nExplanation: Notice that the path doesn't cross any point more than once.\nExample 2:\nInput: path = \"NESWW\"\nOutput: true\nExplanation: Notice that the path visits the origin twice.\n Constraints:\n1 <= path.length <= 104\npath[i] is either 'N', 'S', 'E', or 'W'." }, { "post_href": "https://leetcode.com/problems/check-if-array-pairs-are-divisible-by-k/discuss/709252/Python3-3-line-frequency-table", "python_solutions": "class Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n freq = dict()\n for x in arr: freq[x%k] = 1 + freq.get(x%k, 0)\n return all(freq[x] == freq.get(xx:=(k-x)%k, 0) and (x != xx or freq[x]%2 == 0) for x in freq)", "slug": "check-if-array-pairs-are-divisible-by-k", "post_title": "[Python3] 3-line frequency table", "user": "ye15", "upvotes": 3, "views": 255, "problem_title": "check if array pairs are divisible by k", "number": 1497, "acceptance": 0.396, "difficulty": "Medium", "__index_level_0__": 22296, "question": "Given an array of integers arr of even length n and an integer k.\nWe want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.\nReturn true If you can find a way to do that or false otherwise.\n Example 1:\nInput: arr = [1,2,3,4,5,10,6,7,8,9], k = 5\nOutput: true\nExplanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).\nExample 2:\nInput: arr = [1,2,3,4,5,6], k = 7\nOutput: true\nExplanation: Pairs are (1,6),(2,5) and(3,4).\nExample 3:\nInput: arr = [1,2,3,4,5,6], k = 10\nOutput: false\nExplanation: You can try all possible pairs to see that there is no way to divide arr into 3 pairs each with sum divisible by 10.\n Constraints:\narr.length == n\n1 <= n <= 105\nn is even.\n-109 <= arr[i] <= 109\n1 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/number-of-subsequences-that-satisfy-the-given-sum-condition/discuss/1703899/python-easy-two-pointers-%2B-sorting-solution", "python_solutions": "class Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n n = len(nums)\n \n nums.sort()\n i, j = 0, n-1\n \n \n res = 0 \n NUM = 10**9+7\n while i <= j:\n if nums[i] + nums[j] > target:\n j -= 1\n elif nums[i] + nums[j] <= target:\n res += pow(2, j-i, NUM)\n i += 1\n #else: # nums[i] + nums[j] == target\n \n \n \n return res % NUM", "slug": "number-of-subsequences-that-satisfy-the-given-sum-condition", "post_title": "python easy two-pointers + sorting solution", "user": "byuns9334", "upvotes": 3, "views": 755, "problem_title": "number of subsequences that satisfy the given sum condition", "number": 1498, "acceptance": 0.381, "difficulty": "Medium", "__index_level_0__": 22302, "question": "You are given an array of integers nums and an integer target.\nReturn the number of non-empty subsequences of nums such that the sum of the minimum and maximum element on it is less or equal to target. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: nums = [3,5,6,7], target = 9\nOutput: 4\nExplanation: There are 4 subsequences that satisfy the condition.\n[3] -> Min value + max value <= target (3 + 3 <= 9)\n[3,5] -> (3 + 5 <= 9)\n[3,5,6] -> (3 + 6 <= 9)\n[3,6] -> (3 + 6 <= 9)\nExample 2:\nInput: nums = [3,3,6,8], target = 10\nOutput: 6\nExplanation: There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).\n[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]\nExample 3:\nInput: nums = [2,3,3,4,6,7], target = 12\nOutput: 61\nExplanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\nNumber of valid subsequences (63 - 2 = 61).\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 106\n1 <= target <= 106" }, { "post_href": "https://leetcode.com/problems/max-value-of-equation/discuss/709364/Python3-heap", "python_solutions": "class Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n ans = -inf\n hp = [] \n for xj, yj in points:\n while hp and xj - hp[0][1] > k: heappop(hp)\n if hp: \n ans = max(ans, xj + yj - hp[0][0])\n heappush(hp, (xj-yj, xj))\n return ans", "slug": "max-value-of-equation", "post_title": "[Python3] heap", "user": "ye15", "upvotes": 8, "views": 721, "problem_title": "max value of equation", "number": 1499, "acceptance": 0.4639999999999999, "difficulty": "Hard", "__index_level_0__": 22309, "question": "You are 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.\nReturn the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length.\nIt is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.\n Example 1:\nInput: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\nOutput: 4\nExplanation: 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.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.\nExample 2:\nInput: points = [[0,0],[3,0],[9,2]], k = 3\nOutput: 3\nExplanation: 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 Constraints:\n2 <= points.length <= 105\npoints[i].length == 2\n-108 <= xi, yi <= 108\n0 <= k <= 2 * 108\nxi < xj for all 1 <= i < j <= points.length\nxi form a strictly increasing sequence." }, { "post_href": "https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/discuss/720103/Python3-2-line-(sorting)", "python_solutions": "class Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n arr.sort()\n return len(set(arr[i-1] - arr[i] for i in range(1, len(arr)))) == 1", "slug": "can-make-arithmetic-progression-from-sequence", "post_title": "[Python3] 2-line (sorting)", "user": "ye15", "upvotes": 17, "views": 1100, "problem_title": "can make arithmetic progression from sequence", "number": 1502, "acceptance": 0.6809999999999999, "difficulty": "Easy", "__index_level_0__": 22311, "question": "A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.\nGiven an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.\n Example 1:\nInput: arr = [3,5,1]\nOutput: true\nExplanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.\nExample 2:\nInput: arr = [1,2,4]\nOutput: false\nExplanation: There is no way to reorder the elements to obtain an arithmetic progression.\n Constraints:\n2 <= arr.length <= 1000\n-106 <= arr[i] <= 106" }, { "post_href": "https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/discuss/720202/PythonPython3-Last-Moment-Before-All-Ants-Fall-Out-of-a-Plank", "python_solutions": "class Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n if left and not right:\n return max(left)\n if not left and right:\n return n - min(right)\n if not left and not right:\n return 0\n if left and right:\n return max(max(left), n - min(right))", "slug": "last-moment-before-all-ants-fall-out-of-a-plank", "post_title": "[Python/Python3] Last Moment Before All Ants Fall Out of a Plank", "user": "newborncoder", "upvotes": 1, "views": 87, "problem_title": "last moment before all ants fall out of a plank", "number": 1503, "acceptance": 0.5529999999999999, "difficulty": "Medium", "__index_level_0__": 22355, "question": "We have a wooden plank of the length n units. Some ants are walking on the plank, each ant moves with a speed of 1 unit per second. Some of the ants move to the left, the other move to the right.\nWhen two ants moving in two different directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time.\nWhen an ant reaches one end of the plank at a time t, it falls out of the plank immediately.\nGiven an integer n and two integer arrays left and right, the positions of the ants moving to the left and the right, return the moment when the last ant(s) fall out of the plank.\n Example 1:\nInput: n = 4, left = [4,3], right = [0,1]\nOutput: 4\nExplanation: In the image above:\n-The ant at index 0 is named A and going to the right.\n-The ant at index 1 is named B and going to the right.\n-The ant at index 3 is named C and going to the left.\n-The ant at index 4 is named D and going to the left.\nThe last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank).\nExample 2:\nInput: n = 7, left = [], right = [0,1,2,3,4,5,6,7]\nOutput: 7\nExplanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.\nExample 3:\nInput: n = 7, left = [0,1,2,3,4,5,6,7], right = []\nOutput: 7\nExplanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.\n Constraints:\n1 <= n <= 104\n0 <= left.length <= n + 1\n0 <= left[i] <= n\n0 <= right.length <= n + 1\n0 <= right[i] <= n\n1 <= left.length + right.length <= n + 1\nAll values of left and right are unique, and each value can appear only in one of the two arrays." }, { "post_href": "https://leetcode.com/problems/count-submatrices-with-all-ones/discuss/721999/Python3-O(MN)-histogram-model", "python_solutions": "class Solution:\n def numSubmat(self, mat: List[List[int]]) -> int:\n m, n = len(mat), len(mat[0])\n \n #precipitate mat to histogram \n for i in range(m):\n for j in range(n):\n if mat[i][j] and i > 0: \n mat[i][j] += mat[i-1][j] #histogram \n \n ans = 0\n for i in range(m):\n stack = [] #mono-stack of indices of non-decreasing height\n cnt = 0\n for j in range(n):\n while stack and mat[i][stack[-1]] > mat[i][j]: \n jj = stack.pop() #start\n kk = stack[-1] if stack else -1 #end\n cnt -= (mat[i][jj] - mat[i][j])*(jj - kk) #adjust to reflect lower height\n\n cnt += mat[i][j] #count submatrices bottom-right at (i, j)\n ans += cnt\n stack.append(j)\n\n return ans", "slug": "count-submatrices-with-all-ones", "post_title": "[Python3] O(MN) histogram model", "user": "ye15", "upvotes": 111, "views": 7600, "problem_title": "count submatrices with all ones", "number": 1504, "acceptance": 0.578, "difficulty": "Medium", "__index_level_0__": 22360, "question": "Given an m x n binary matrix mat, return the number of submatrices that have all ones.\n Example 1:\nInput: mat = [[1,0,1],[1,1,0],[1,1,0]]\nOutput: 13\nExplanation: \nThere are 6 rectangles of side 1x1.\nThere are 2 rectangles of side 1x2.\nThere are 3 rectangles of side 2x1.\nThere is 1 rectangle of side 2x2. \nThere is 1 rectangle of side 3x1.\nTotal number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.\nExample 2:\nInput: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\nOutput: 24\nExplanation: \nThere are 8 rectangles of side 1x1.\nThere are 5 rectangles of side 1x2.\nThere are 2 rectangles of side 1x3. \nThere are 4 rectangles of side 2x1.\nThere are 2 rectangles of side 2x2. \nThere are 2 rectangles of side 3x1. \nThere is 1 rectangle of side 3x2. \nTotal number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.\n Constraints:\n1 <= m, n <= 150\nmat[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/discuss/720123/Python3-brute-force", "python_solutions": "class Solution:\n def minInteger(self, num: str, k: int) -> str:\n n = len(num)\n if k >= n*(n-1)//2: return \"\".join(sorted(num)) #special case\n \n #find smallest elements within k swaps \n #and swap it to current position \n num = list(num)\n for i in range(n):\n if not k: break \n #find minimum within k swaps\n ii = i\n for j in range(i+1, min(n, i+k+1)): \n if num[ii] > num[j]: ii = j \n #swap the min to current position \n if ii != i: \n k -= ii-i\n for j in range(ii, i, -1):\n num[j-1], num[j] = num[j], num[j-1]\n return \"\".join(num)", "slug": "minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits", "post_title": "[Python3] brute force", "user": "ye15", "upvotes": 2, "views": 374, "problem_title": "minimum possible integer after at most k adjacent swaps on digits", "number": 1505, "acceptance": 0.3829999999999999, "difficulty": "Hard", "__index_level_0__": 22364, "question": "You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.\nReturn the minimum integer you can obtain also as a string.\n Example 1:\nInput: num = \"4321\", k = 4\nOutput: \"1342\"\nExplanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\nExample 2:\nInput: num = \"100\", k = 1\nOutput: \"010\"\nExplanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\nExample 3:\nInput: num = \"36789\", k = 1000\nOutput: \"36789\"\nExplanation: We can keep the number without any swaps.\n Constraints:\n1 <= num.length <= 3 * 104\nnum consists of only digits and does not contain leading zeros.\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/reformat-date/discuss/1861804/Python-3-Easy-Dict.-Solution-wout-imports-(98)", "python_solutions": "class Solution:\n def reformatDate(self, date: str) -> str:\n s = date.split() # Divides the elements into 3 individual parts\n \n monthDict = {'Jan': '01', 'Feb': '02', \n 'Mar': '03', 'Apr': '04', \n 'May': '05', 'Jun': '06', \n 'Jul': '07', 'Aug': '08', \n 'Sep': '09', 'Oct': '10', \n 'Nov': '11', 'Dec': '12'}\n \n day = s[0][:-2] # Removes the last 2 elements of the day\n month = s[1] \n year = s[2]\n \n if int(day) < 10: # Adds 0 to the front of day if day < 10\n day = '0' + day\n \n return ''.join(f'{year}-{monthDict[month]}-{day}') # Joins it all together. Month is used to draw out the corresponding number from the dict.", "slug": "reformat-date", "post_title": "Python 3 - Easy Dict. Solution w/out imports (98%)", "user": "IvanTsukei", "upvotes": 12, "views": 768, "problem_title": "reformat date", "number": 1507, "acceptance": 0.626, "difficulty": "Easy", "__index_level_0__": 22365, "question": "Given a date string in the form Day Month Year, where:\nDay is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"}.\nMonth is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"}.\nYear is in the range [1900, 2100].\nConvert the date string to the format YYYY-MM-DD, where:\nYYYY denotes the 4 digit year.\nMM denotes the 2 digit month.\nDD denotes the 2 digit day.\n Example 1:\nInput: date = \"20th Oct 2052\"\nOutput: \"2052-10-20\"\nExample 2:\nInput: date = \"6th Jun 1933\"\nOutput: \"1933-06-06\"\nExample 3:\nInput: date = \"26th May 1960\"\nOutput: \"1960-05-26\"\n Constraints:\nThe given dates are guaranteed to be valid, so no error handling is necessary." }, { "post_href": "https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/discuss/730973/Python3-priority-queue", "python_solutions": "class Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n ans = []\n for i in range(len(nums)):\n prefix = 0\n for ii in range(i, len(nums)):\n prefix += nums[ii]\n ans.append(prefix)\n ans.sort()\n return sum(ans[left-1:right]) % 1_000_000_007", "slug": "range-sum-of-sorted-subarray-sums", "post_title": "[Python3] priority queue", "user": "ye15", "upvotes": 46, "views": 3600, "problem_title": "range sum of sorted subarray sums", "number": 1508, "acceptance": 0.593, "difficulty": "Medium", "__index_level_0__": 22398, "question": "You are given the array nums consisting of n positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of n * (n + 1) / 2 numbers.\nReturn the sum of the numbers from index left to index right (indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 109 + 7.\n Example 1:\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 5\nOutput: 13 \nExplanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. \nExample 2:\nInput: nums = [1,2,3,4], n = 4, left = 3, right = 4\nOutput: 6\nExplanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.\nExample 3:\nInput: nums = [1,2,3,4], n = 4, left = 1, right = 10\nOutput: 50\n Constraints:\nn == nums.length\n1 <= nums.length <= 1000\n1 <= nums[i] <= 100\n1 <= left <= right <= n * (n + 1) / 2" }, { "post_href": "https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/1433873/Python3Python-Easy-readable-solution-with-comments.", "python_solutions": "class Solution:\n \n def minDifference(self, nums: List[int]) -> int:\n \n n = len(nums)\n # If nums are less than 3 all can be replace,\n # so min diff will be 0, which is default condition\n if n > 3:\n \n # Init min difference\n min_diff = float(\"inf\")\n \n # sort the array\n nums = sorted(nums)\n \n # Get the window size, this indicates, if we\n # remove 3 element in an array how many element\n # are left, consider 0 as the index, window\n # size should be (n-3), but for array starting\n # with 0 it should be ((n-1)-3)\n window = (n-1)-3\n \n # Run through the entire array slinding the\n # window and calculating minimum difference\n # between the first and the last element of\n # that window\n for i in range(n):\n if i+window >= n:\n break\n else:\n min_diff = min(nums[i+window]-nums[i], min_diff)\n \n # return calculated minimum difference\n return min_diff\n \n return 0 # default condition", "slug": "minimum-difference-between-largest-and-smallest-value-in-three-moves", "post_title": "[Python3/Python] Easy readable solution with comments.", "user": "ssshukla26", "upvotes": 10, "views": 1000, "problem_title": "minimum difference between largest and smallest value in three moves", "number": 1509, "acceptance": 0.546, "difficulty": "Medium", "__index_level_0__": 22403, "question": "You are given an integer array nums.\nIn one move, you can choose one element of nums and change it to any value.\nReturn the minimum difference between the largest and smallest value of nums after performing at most three moves.\n Example 1:\nInput: nums = [5,3,2,4]\nOutput: 0\nExplanation: We can make at most 3 moves.\nIn the first move, change 2 to 3. nums becomes [5,3,3,4].\nIn the second move, change 4 to 3. nums becomes [5,3,3,3].\nIn the third move, change 5 to 3. nums becomes [3,3,3,3].\nAfter performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.\nExample 2:\nInput: nums = [1,5,0,10,14]\nOutput: 1\nExplanation: We can make at most 3 moves.\nIn the first move, change 5 to 0. nums becomes [1,0,0,10,14].\nIn the second move, change 10 to 0. nums becomes [1,0,0,0,14].\nIn the third move, change 14 to 1. nums becomes [1,0,0,0,1].\nAfter performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.\nIt can be shown that there is no way to make the difference 0 in 3 moves.\nExample 3:\nInput: nums = [3,100,20]\nOutput: 0\nExplanation: We can make at most 3 moves.\nIn the first move, change 100 to 7. nums becomes [3,7,20].\nIn the second move, change 20 to 7. nums becomes [3,7,7].\nIn the third move, change 3 to 7. nums becomes [7,7,7].\nAfter performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.\n Constraints:\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/stone-game-iv/discuss/1708107/Python3-DP", "python_solutions": "class Solution:\n def winnerSquareGame(self, n: int) -> bool:\n dp = [False] * (n + 1)\n squares = []\n curSquare = 1\n for i in range(1, n + 1):\n if i == curSquare * curSquare:\n squares.append(i)\n curSquare += 1\n dp[i] = True\n else:\n for square in squares:\n if not dp[i - square]:\n dp[i] = True\n break\n return dp[n]", "slug": "stone-game-iv", "post_title": "[Python3] DP", "user": "PatrickOweijane", "upvotes": 8, "views": 397, "problem_title": "stone game iv", "number": 1510, "acceptance": 0.605, "difficulty": "Hard", "__index_level_0__": 22413, "question": "Alice and Bob take turns playing a game, with Alice starting first.\nInitially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\nAlso, if a player cannot make a move, he/she loses the game.\nGiven a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.\n Example 1:\nInput: n = 1\nOutput: true\nExplanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\nExample 2:\nInput: n = 2\nOutput: false\nExplanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\nExample 3:\nInput: n = 4\nOutput: true\nExplanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n Constraints:\n1 <= n <= 105" }, { "post_href": "https://leetcode.com/problems/number-of-good-pairs/discuss/749025/Python-O(n)-simple-dictionary-solution", "python_solutions": "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n hashMap = {}\n res = 0\n for number in nums: \n if number in hashMap:\n res += hashMap[number]\n hashMap[number] += 1\n else:\n hashMap[number] = 1\n return res", "slug": "number-of-good-pairs", "post_title": "Python O(n) simple dictionary solution", "user": "Arturo001", "upvotes": 88, "views": 6200, "problem_title": "number of good pairs", "number": 1512, "acceptance": 0.882, "difficulty": "Easy", "__index_level_0__": 22427, "question": "Given an array of integers nums, return the number of good pairs.\nA pair (i, j) is called good if nums[i] == nums[j] and i < j.\n Example 1:\nInput: nums = [1,2,3,1,1,3]\nOutput: 4\nExplanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.\nExample 2:\nInput: nums = [1,1,1,1]\nOutput: 6\nExplanation: Each pair in the array are good.\nExample 3:\nInput: nums = [1,2,3]\nOutput: 0\n Constraints:\n1 <= nums.length <= 100\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-substrings-with-only-1s/discuss/731754/Python-Sum-of-Arithmetic-Progression-with-explanation-**100.00-Faster**", "python_solutions": "class Solution:\n def numSub(self, s: str) -> int: \n res = 0\n s = s.split(\"0\")\n\n for one in s:\n if one == \"\":\n continue\n \n n = len(one)\n temp = (n / 2)*(2*n + (n-1)*-1)\n \n if temp >= 1000000007:\n res += temp % 1000000007\n else:\n res += temp\n return int(res)", "slug": "number-of-substrings-with-only-1s", "post_title": "[Python] Sum of Arithmetic Progression with explanation **100.00% Faster**", "user": "Jasper-W", "upvotes": 8, "views": 506, "problem_title": "number of substrings with only 1s", "number": 1513, "acceptance": 0.4539999999999999, "difficulty": "Medium", "__index_level_0__": 22479, "question": "Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: s = \"0110111\"\nOutput: 9\nExplanation: There are 9 substring in total with only 1's characters.\n\"1\" -> 5 times.\n\"11\" -> 3 times.\n\"111\" -> 1 time.\nExample 2:\nInput: s = \"101\"\nOutput: 2\nExplanation: Substring \"1\" is shown 2 times in s.\nExample 3:\nInput: s = \"111111\"\nOutput: 21\nExplanation: Each substring contains only 1's characters.\n Constraints:\n1 <= s.length <= 105\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/path-with-maximum-probability/discuss/731655/Python3-Dijkstra's-algo", "python_solutions": "class Solution:\n def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:\n graph, prob = dict(), dict() #graph with prob\n for i, (u, v) in enumerate(edges):\n graph.setdefault(u, []).append(v)\n graph.setdefault(v, []).append(u)\n prob[u, v] = prob[v, u] = succProb[i]\n \n h = [(-1, start)] #Dijkstra's algo\n seen = set()\n while h: \n p, n = heappop(h)\n if n == end: return -p\n seen.add(n)\n for nn in graph.get(n, []):\n if nn in seen: continue \n heappush(h, (p * prob.get((n, nn), 0), nn))\n return 0", "slug": "path-with-maximum-probability", "post_title": "[Python3] Dijkstra's algo", "user": "ye15", "upvotes": 27, "views": 2500, "problem_title": "path with maximum probability", "number": 1514, "acceptance": 0.484, "difficulty": "Medium", "__index_level_0__": 22497, "question": "You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].\nGiven two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.\nIf there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.\n Example 1:\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\nOutput: 0.25000\nExplanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.\nExample 2:\nInput: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\nOutput: 0.30000\nExample 3:\nInput: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\nOutput: 0.00000\nExplanation: There is no path between 0 and 2.\n Constraints:\n2 <= n <= 10^4\n0 <= start, end < n\nstart != end\n0 <= a, b < n\na != b\n0 <= succProb.length == edges.length <= 2*10^4\n0 <= succProb[i] <= 1\nThere is at most one edge between every two nodes." }, { "post_href": "https://leetcode.com/problems/best-position-for-a-service-centre/discuss/731717/Python3-geometric-median", "python_solutions": "class Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n #euclidean distance \n fn = lambda x, y: sum(sqrt((x-xx)**2 + (y-yy)**2) for xx, yy in positions)\n #centroid as starting point\n x = sum(x for x, _ in positions)/len(positions)\n y = sum(y for _, y in positions)/len(positions)\n \n ans = fn(x, y)\n chg = 100 #change since 0 <= positions[i][0], positions[i][1] <= 100\n while chg > 1e-6: #accuracy within 1e-5\n zoom = True\n for dx, dy in (-1, 0), (0, -1), (0, 1), (1, 0):\n xx = x + chg * dx\n yy = y + chg * dy\n dd = fn(xx, yy)\n if dd < ans: \n ans = dd \n x, y = xx, yy\n zoom = False \n break \n if zoom: chg /= 2\n return ans", "slug": "best-position-for-a-service-centre", "post_title": "[Python3] geometric median", "user": "ye15", "upvotes": 62, "views": 3700, "problem_title": "best position for a service centre", "number": 1515, "acceptance": 0.377, "difficulty": "Hard", "__index_level_0__": 22502, "question": "A delivery company wants to build a new service center in a new city. The company knows the positions of all the customers in this city on a 2D-Map and wants to build the new center in a position such that the sum of the euclidean distances to all customers is minimum.\nGiven an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.\nIn other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:\nAnswers within 10-5 of the actual value will be accepted.\n Example 1:\nInput: positions = [[0,1],[1,0],[1,2],[2,1]]\nOutput: 4.00000\nExplanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\nExample 2:\nInput: positions = [[1,1],[3,3]]\nOutput: 2.82843\nExplanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n Constraints:\n1 <= positions.length <= 50\npositions[i].length == 2\n0 <= xi, yi <= 100" }, { "post_href": "https://leetcode.com/problems/water-bottles/discuss/743152/Python3-5-line-iterative", "python_solutions": "class Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n ans = r = 0\n while numBottles:\n ans += numBottles\n numBottles, r = divmod(numBottles + r, numExchange)\n return ans", "slug": "water-bottles", "post_title": "[Python3] 5-line iterative", "user": "ye15", "upvotes": 9, "views": 573, "problem_title": "water bottles", "number": 1518, "acceptance": 0.602, "difficulty": "Easy", "__index_level_0__": 22503, "question": "There are numBottles water bottles that are initially full of water. You can exchange numExchange empty water bottles from the market with one full water bottle.\nThe operation of drinking a full water bottle turns it into an empty bottle.\nGiven the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.\n Example 1:\nInput: numBottles = 9, numExchange = 3\nOutput: 13\nExplanation: You can exchange 3 empty bottles to get 1 full water bottle.\nNumber of water bottles you can drink: 9 + 3 + 1 = 13.\nExample 2:\nInput: numBottles = 15, numExchange = 4\nOutput: 19\nExplanation: You can exchange 4 empty bottles to get 1 full water bottle. \nNumber of water bottles you can drink: 15 + 3 + 1 = 19.\n Constraints:\n1 <= numBottles <= 100\n2 <= numExchange <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/discuss/1441578/Python-3-or-DFS-Graph-Counter-or-Explanation", "python_solutions": "class Solution:\n def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:\n ans = [0] * n\n tree = collections.defaultdict(list)\n for a, b in edges: # build tree\n tree[a].append(b)\n tree[b].append(a)\n def dfs(node): # dfs\n nonlocal visited, ans, tree\n c = collections.Counter(labels[node])\n for nei in tree[node]:\n if nei in visited: continue # avoid revisit\n visited.add(nei)\n c += dfs(nei) # add counter (essentially adding a 26 elements dictionary)\n ans[node] = c.get(labels[node]) # assign count of label to this node\n return c\n visited = set([0])\n dfs(0)\n return ans", "slug": "number-of-nodes-in-the-sub-tree-with-the-same-label", "post_title": "Python 3 | DFS, Graph, Counter | Explanation", "user": "idontknoooo", "upvotes": 7, "views": 366, "problem_title": "number of nodes in the sub tree with the same label", "number": 1519, "acceptance": 0.41, "difficulty": "Medium", "__index_level_0__": 22528, "question": "You are given a tree (i.e. a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. The root of the tree is the node 0, and each node of the tree has a label which is a lower-case character given in the string labels (i.e. The node with the number i has the label labels[i]).\nThe edges array is given on the form edges[i] = [ai, bi], which means there is an edge between nodes ai and bi in the tree.\nReturn an array of size n where ans[i] is the number of nodes in the subtree of the ith node which have the same label as node i.\nA subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.\n Example 1:\nInput: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\nOutput: [2,1,1,1,1,1,1]\nExplanation: Node 0 has label 'a' and its sub-tree has node 2 with label 'a' as well, thus the answer is 2. Notice that any node is part of its sub-tree.\nNode 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).\nExample 2:\nInput: n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\nOutput: [4,2,1,1]\nExplanation: The sub-tree of node 2 contains only node 2, so the answer is 1.\nThe sub-tree of node 3 contains only node 3, so the answer is 1.\nThe sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\nThe sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.\nExample 3:\nInput: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\nOutput: [3,2,1,1,1]\n Constraints:\n1 <= n <= 105\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nlabels.length == n\nlabels is consisting of only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-non-overlapping-substrings/discuss/1208758/Python3-greedy", "python_solutions": "class Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n locs = {}\n for i, x in enumerate(s): \n locs.setdefault(x, []).append(i)\n \n def fn(lo, hi): \n \"\"\"Return expanded range covering all chars in s[lo:hi+1].\"\"\"\n for xx in locs: \n k0 = bisect_left(locs[xx], lo)\n k1 = bisect_left(locs[xx], hi)\n if k0 < k1 and (locs[xx][0] < lo or hi < locs[xx][-1]): \n lo = min(lo, locs[xx][0])\n hi = max(hi, locs[xx][-1])\n lo, hi = fn(lo, hi)\n return lo, hi\n \n group = set()\n for x in locs: \n group.add(fn(locs[x][0], locs[x][-1]))\n \n ans = [] # ISMP (interval scheduling maximization problem)\n prev = -1 \n for lo, hi in sorted(group, key=lambda x: x[1]): \n if prev < lo: \n ans.append(s[lo:hi+1])\n prev = hi \n return ans", "slug": "maximum-number-of-non-overlapping-substrings", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 1, "views": 281, "problem_title": "maximum number of non overlapping substrings", "number": 1520, "acceptance": 0.381, "difficulty": "Hard", "__index_level_0__": 22532, "question": "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:\nThe substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.\nA substring that contains a certain character c must also contain all occurrences of c.\nFind the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.\nNotice that you can return the substrings in any order.\n Example 1:\nInput: s = \"adefaddaccc\"\nOutput: [\"e\",\"f\",\"ccc\"]\nExplanation: The following are all the possible substrings that meet the conditions:\n[\n \"adefaddaccc\"\n \"adefadda\",\n \"ef\",\n \"e\",\n \"f\",\n \"ccc\",\n]\nIf we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.\nExample 2:\nInput: s = \"abbaccd\"\nOutput: [\"d\",\"bb\",\"cc\"]\nExplanation: Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.\n Constraints:\n1 <= s.length <= 105\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/find-a-value-of-a-mysterious-function-closest-to-target/discuss/746723/Python3-bitwise-and", "python_solutions": "class Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n ans, seen = inf, set()\n for x in arr: \n seen = {ss & x for ss in seen} | {x}\n ans = min(ans, min(abs(ss - target) for ss in seen))\n return ans", "slug": "find-a-value-of-a-mysterious-function-closest-to-target", "post_title": "[Python3] bitwise and", "user": "ye15", "upvotes": 8, "views": 306, "problem_title": "find a value of a mysterious function closest to target", "number": 1521, "acceptance": 0.436, "difficulty": "Hard", "__index_level_0__": 22534, "question": "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.\nReturn the minimum possible value of |func(arr, l, r) - target|.\nNotice that func should be called with the values l and r where 0 <= l, r < arr.length.\n Example 1:\nInput: arr = [9,12,3,7,15], target = 5\nOutput: 2\nExplanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.\nExample 2:\nInput: arr = [1000000,1000000,1000000], target = 1\nOutput: 999999\nExplanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.\nExample 3:\nInput: arr = [1,2,4,8,16], target = 0\nOutput: 0\n Constraints:\n1 <= arr.length <= 105\n1 <= arr[i] <= 106\n0 <= target <= 107" }, { "post_href": "https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/discuss/1813332/Python-3-or-Math-or-Intuitive", "python_solutions": "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n if low % 2 == 0:\n return (high-low+1)//2\n return (high-low)//2 + 1", "slug": "count-odd-numbers-in-an-interval-range", "post_title": "Python 3 | Math | Intuitive", "user": "ndus", "upvotes": 60, "views": 4500, "problem_title": "count odd numbers in an interval range", "number": 1523, "acceptance": 0.462, "difficulty": "Easy", "__index_level_0__": 22537, "question": "Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).\n Example 1:\nInput: low = 3, high = 7\nOutput: 3\nExplanation: The odd numbers between 3 and 7 are [3,5,7].\nExample 2:\nInput: low = 8, high = 10\nOutput: 1\nExplanation: The odd numbers between 8 and 10 are [9].\n Constraints:\n0 <= low <= high <= 10^9" }, { "post_href": "https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/discuss/2061760/Python-oror-8-line-math-using-Prefix-Sum", "python_solutions": "class Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n cumSum = odd = even = 0\n for num in arr:\n cumSum += num\n if cumSum % 2:\n odd += 1\n else:\n even += 1\n return odd * (even + 1) % (pow(10, 9) + 7)", "slug": "number-of-sub-arrays-with-odd-sum", "post_title": "Python || 8-line math using Prefix Sum", "user": "gulugulugulugulu", "upvotes": 1, "views": 138, "problem_title": "number of sub arrays with odd sum", "number": 1524, "acceptance": 0.436, "difficulty": "Medium", "__index_level_0__": 22594, "question": "Given an array of integers arr, return the number of subarrays with an odd sum.\nSince the answer can be very large, return it modulo 109 + 7.\n Example 1:\nInput: arr = [1,3,5]\nOutput: 4\nExplanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\nAll sub-arrays sum are [1,4,9,3,8,5].\nOdd sums are [1,9,3,5] so the answer is 4.\nExample 2:\nInput: arr = [2,4,6]\nOutput: 0\nExplanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\nAll sub-arrays sum are [2,6,12,4,10,6].\nAll sub-arrays have even sum and the answer is 0.\nExample 3:\nInput: arr = [1,2,3,4,5,6,7]\nOutput: 16\n Constraints:\n1 <= arr.length <= 105\n1 <= arr[i] <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-good-ways-to-split-a-string/discuss/1520004/99.7-Python-3-solution-with-17-lines-no-search-explained", "python_solutions": "class Solution:\n def numSplits(self, s: str) -> int:\n\t\t# this is not neccessary, but speeds things up\n length = len(s)\n if length == 1: # never splittable\n return 0\n elif length == 2: # always splittable\n return 1\n\t\t\n\t\t# we are recording the first and last occurence of each included letter\n first = {} # max size = 26\n last = {} # max size = 26\n\t\t\n for index, character in enumerate(s): # O(n)\n if character not in first:\n first[character] = index\n last[character] = index\n\t\t\t\n\t\t# we are concatenating the collected indices into a list and sort them\n indices = list(first.values()) + list(last.values()) # max length 26 + 26 = 52\n indices.sort() # sorting is constant O(1) because of the length limit above\n\t\t\n\t\t# all possible splits will be in the middle of this list\n middle = len(indices)//2 # always an integer because indices has an even length\n\t\t\n\t\t# there are this many possible splits between the two 'median' numbers\n return indices[middle] - indices[middle-1]", "slug": "number-of-good-ways-to-split-a-string", "post_title": "99.7% Python 3 solution with 17 lines, no search, explained", "user": "epistoteles", "upvotes": 70, "views": 2200, "problem_title": "number of good ways to split a string", "number": 1525, "acceptance": 0.6940000000000001, "difficulty": "Medium", "__index_level_0__": 22600, "question": "You are given a string s.\nA split is called good if you can split s into two non-empty strings sleft and sright where their concatenation is equal to s (i.e., sleft + sright = s) and the number of distinct letters in sleft and sright is the same.\nReturn the number of good splits you can make in s.\n Example 1:\nInput: s = \"aacaba\"\nOutput: 2\nExplanation: There are 5 ways to split \"aacaba\" and 2 of them are good. \n(\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n(\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n(\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.\nExample 2:\nInput: s = \"abcd\"\nOutput: 1\nExplanation: Split the string as follows (\"ab\", \"cd\").\n Constraints:\n1 <= s.length <= 105\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/discuss/1589995/Python3-O(n)-time-O(1)-space-solution", "python_solutions": "class Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n res = target[0]\n \n for i in range(1, len(target)):\n if target[i] >= target[i - 1]:\n res -= target[i - 1]\n res += target[i]\n \n return res", "slug": "minimum-number-of-increments-on-subarrays-to-form-a-target-array", "post_title": "[Python3] O(n) time, O(1) space solution", "user": "maosipov11", "upvotes": 1, "views": 87, "problem_title": "minimum number of increments on subarrays to form a target array", "number": 1526, "acceptance": 0.6859999999999999, "difficulty": "Hard", "__index_level_0__": 22624, "question": "You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.\nIn one operation you can choose any subarray from initial and increment each value by one.\nReturn the minimum number of operations to form a target array from initial.\nThe test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\nInput: target = [1,2,3,2,1]\nOutput: 3\nExplanation: We need at least 3 operations to form the target array from the initial array.\n[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n[1,2,2,2,1] increment 1 at index 2.\n[1,2,3,2,1] target array is formed.\nExample 2:\nInput: target = [3,1,1,2]\nOutput: 4\nExplanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]\nExample 3:\nInput: target = [3,1,5,4,2]\nOutput: 7\nExplanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].\n Constraints:\n1 <= target.length <= 105\n1 <= target[i] <= 105" }, { "post_href": "https://leetcode.com/problems/shuffle-string/discuss/768482/Simple-Python-Solution-Faster-than-99.56", "python_solutions": "class Solution:\n def restoreString(self, s: str, indices: List[int]) -> str:\n res = [''] * len(s)\n for i in range(len(s)):\n res[indices[i]] = s[i]\n return ''.join(i for i in res)", "slug": "shuffle-string", "post_title": "Simple Python Solution - Faster than 99.56%", "user": "parkershamblin", "upvotes": 25, "views": 4200, "problem_title": "shuffle string", "number": 1528, "acceptance": 0.857, "difficulty": "Easy", "__index_level_0__": 22628, "question": "You are given a string s and an integer array indices of the same length. The string s will be shuffled such that the character at the ith position moves to indices[i] in the shuffled string.\nReturn the shuffled string.\n Example 1:\nInput: s = \"codeleet\", indices = [4,5,6,7,0,2,1,3]\nOutput: \"leetcode\"\nExplanation: As shown, \"codeleet\" becomes \"leetcode\" after shuffling.\nExample 2:\nInput: s = \"abc\", indices = [0,1,2]\nOutput: \"abc\"\nExplanation: After shuffling, each character remains in its position.\n Constraints:\ns.length == indices.length == n\n1 <= n <= 100\ns consists of only lowercase English letters.\n0 <= indices[i] < n\nAll values of indices are unique." }, { "post_href": "https://leetcode.com/problems/minimum-suffix-flips/discuss/755814/Python3-1-line", "python_solutions": "class Solution:\n def minFlips(self, target: str) -> int:\n return len(list(groupby(\"0\" + target)))-1", "slug": "minimum-suffix-flips", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 16, "views": 872, "problem_title": "minimum suffix flips", "number": 1529, "acceptance": 0.7240000000000001, "difficulty": "Medium", "__index_level_0__": 22687, "question": "You are given a 0-indexed binary string target of length n. You have another binary string s of length n that is initially set to all zeros. You want to make s equal to target.\nIn one operation, you can pick an index i where 0 <= i < n and flip all bits in the inclusive range [i, n - 1]. Flip means changing '0' to '1' and '1' to '0'.\nReturn the minimum number of operations needed to make s equal to target.\n Example 1:\nInput: target = \"10111\"\nOutput: 3\nExplanation: Initially, s = \"00000\".\nChoose index i = 2: \"00000\" -> \"00111\"\nChoose index i = 0: \"00111\" -> \"11000\"\nChoose index i = 1: \"11000\" -> \"10111\"\nWe need at least 3 flip operations to form target.\nExample 2:\nInput: target = \"101\"\nOutput: 3\nExplanation: Initially, s = \"000\".\nChoose index i = 0: \"000\" -> \"111\"\nChoose index i = 1: \"111\" -> \"100\"\nChoose index i = 2: \"100\" -> \"101\"\nWe need at least 3 flip operations to form target.\nExample 3:\nInput: target = \"00000\"\nOutput: 0\nExplanation: We do not need any operations since the initial s already equals target.\n Constraints:\nn == target.length\n1 <= n <= 105\ntarget[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/discuss/755979/Python3-recursive-postorder-dfs", "python_solutions": "class Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n \n def dfs(node):\n \"\"\"Return (a list of) distances to leaves of sub-tree rooted at node.\"\"\"\n nonlocal ans\n if not node: return []\n if node.left is node.right is None: return [0]\n left,right = dfs(node.left), dfs(node.right)\n ans += sum(2 + x + y <= distance for x in left for y in right)\n return [1 + x for x in left + right]\n \n ans = 0\n dfs(root)\n return ans", "slug": "number-of-good-leaf-nodes-pairs", "post_title": "[Python3] recursive postorder dfs", "user": "ye15", "upvotes": 3, "views": 264, "problem_title": "number of good leaf nodes pairs", "number": 1530, "acceptance": 0.607, "difficulty": "Medium", "__index_level_0__": 22705, "question": "You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.\nReturn the number of good leaf node pairs in the tree.\n Example 1:\nInput: root = [1,2,3,null,4], distance = 3\nOutput: 1\nExplanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.\nExample 2:\nInput: root = [1,2,3,4,5,6,7], distance = 3\nOutput: 2\nExplanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.\nExample 3:\nInput: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\nOutput: 1\nExplanation: The only good pair is [2,5].\n Constraints:\nThe number of nodes in the tree is in the range [1, 210].\n1 <= Node.val <= 100\n1 <= distance <= 10" }, { "post_href": "https://leetcode.com/problems/string-compression-ii/discuss/1203398/Python3-top-down-dp", "python_solutions": "class Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n rle = lambda x: x if x <= 1 else int(log10(x)) + 2 # rle length of a char repeated x times\n \n @cache \n def fn(i, k, prev, cnt):\n \"\"\"Return length of rle of s[i:] with k chars to be deleted.\"\"\"\n if k < 0: return inf \n if i == len(s): return 0 \n ans = fn(i+1, k-1, prev, cnt) # delete current character \n if prev == s[i]: \n ans = min(ans, fn(i+1, k, s[i], cnt+1) + rle(cnt+1) - rle(cnt))\n else: \n ans = min(ans, fn(i+1, k, s[i], 1) + 1)\n return ans \n \n return fn(0, k, \"\", 0)", "slug": "string-compression-ii", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 12, "views": 1300, "problem_title": "string compression ii", "number": 1531, "acceptance": 0.499, "difficulty": "Hard", "__index_level_0__": 22711, "question": "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\".\nNotice that in this problem, we are not adding '1' after single characters.\nGiven a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.\nFind the minimum length of the run-length encoded version of s after deleting at most k characters.\n Example 1:\nInput: s = \"aaabcccd\", k = 2\nOutput: 4\nExplanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\nExample 2:\nInput: s = \"aabbaa\", k = 2\nOutput: 2\nExplanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\nExample 3:\nInput: s = \"aaaaaaaaaaa\", k = 0\nOutput: 3\nExplanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n Constraints:\n1 <= s.length <= 100\n0 <= k <= s.length\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/count-good-triplets/discuss/767942/Python3-1-line", "python_solutions": "class Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n return sum(abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c for i in range(len(arr)) for j in range(i+1, len(arr)) for k in range(j+1, len(arr)))", "slug": "count-good-triplets", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 4, "views": 1800, "problem_title": "count good triplets", "number": 1534, "acceptance": 0.8079999999999999, "difficulty": "Easy", "__index_level_0__": 22716, "question": "Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.\nA triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:\n0 <= i < j < k < arr.length\n|arr[i] - arr[j]| <= a\n|arr[j] - arr[k]| <= b\n|arr[i] - arr[k]| <= c\nWhere |x| denotes the absolute value of x.\nReturn the number of good triplets.\n Example 1:\nInput: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\nOutput: 4\nExplanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].\nExample 2:\nInput: arr = [1,1,2,2,3], a = 0, b = 0, c = 1\nOutput: 0\nExplanation: No triplet satisfies all conditions.\n Constraints:\n3 <= arr.length <= 100\n0 <= arr[i] <= 1000\n0 <= a, b, c <= 1000" }, { "post_href": "https://leetcode.com/problems/find-the-winner-of-an-array-game/discuss/767983/Python3-6-line-O(N)", "python_solutions": "class Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n win = cnt = 0 #winner & count \n for i, x in enumerate(arr): \n if win < x: win, cnt = x, 0 #new winner in town \n if i: cnt += 1 #when initializing (i.e. i == 0) count is 0\n if cnt == k: break #early break \n return win", "slug": "find-the-winner-of-an-array-game", "post_title": "[Python3] 6-line O(N)", "user": "ye15", "upvotes": 7, "views": 267, "problem_title": "find the winner of an array game", "number": 1535, "acceptance": 0.488, "difficulty": "Medium", "__index_level_0__": 22741, "question": "Given an integer array arr of distinct integers and an integer k.\nA game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.\nReturn the integer which will win the game.\nIt is guaranteed that there will be a winner of the game.\n Example 1:\nInput: arr = [2,1,3,5,4,6,7], k = 2\nOutput: 5\nExplanation: Let's see the rounds of the game:\nRound | arr | winner | win_count\n 1 | [2,1,3,5,4,6,7] | 2 | 1\n 2 | [2,3,5,4,6,7,1] | 3 | 1\n 3 | [3,5,4,6,7,1,2] | 5 | 1\n 4 | [5,4,6,7,1,2,3] | 5 | 2\nSo we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.\nExample 2:\nInput: arr = [3,2,1], k = 10\nOutput: 3\nExplanation: 3 will win the first 10 rounds consecutively.\n Constraints:\n2 <= arr.length <= 105\n1 <= arr[i] <= 106\narr contains distinct integers.\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/discuss/768030/Python3-bubble-ish-sort", "python_solutions": "class Solution:\n def minSwaps(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n #summarizing row into number \n row = [0]*m \n for i in range(m):\n row[i] = next((j for j in reversed(range(n)) if grid[i][j]), 0)\n \n ans = 0\n #sequentially looking for row to fill in \n for k in range(m): \n for i, v in enumerate(row): \n if v <= k: #enough trailing zeros \n ans += i\n row.pop(i) #value used \n break \n else: return -1 #cannot find such row \n return ans", "slug": "minimum-swaps-to-arrange-a-binary-grid", "post_title": "[Python3] bubble-ish sort", "user": "ye15", "upvotes": 13, "views": 750, "problem_title": "minimum swaps to arrange a binary grid", "number": 1536, "acceptance": 0.465, "difficulty": "Medium", "__index_level_0__": 22744, "question": "Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.\nA grid is said to be valid if all the cells above the main diagonal are zeros.\nReturn the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.\nThe main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).\n Example 1:\nInput: grid = [[0,0,1],[1,1,0],[1,0,0]]\nOutput: 3\nExample 2:\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\nOutput: -1\nExplanation: All rows are similar, swaps have no effect on the grid.\nExample 3:\nInput: grid = [[1,0,0],[1,1,0],[1,1,1]]\nOutput: 0\n Constraints:\nn == grid.length == grid[i].length\n1 <= n <= 200\ngrid[i][j] is either 0 or 1" }, { "post_href": "https://leetcode.com/problems/get-the-maximum-score/discuss/768050/Python3-range-sum-with-two-pointers-O(M%2BN)", "python_solutions": "class Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n ans = i = ii = s = ss = 0\n while i < len(nums1) and ii < len(nums2): \n #update range sum & move pointer \n if nums1[i] < nums2[ii]: \n s += nums1[i] \n i += 1\n elif nums1[i] > nums2[ii]:\n ss += nums2[ii]\n ii += 1\n #add larger range sum to ans\n #add common value & move pointers\n else: \n ans += max(s, ss) + nums1[i]\n s = ss = 0\n i, ii = i+1, ii+1\n #complete the range sum & update ans \n ans += max(s + sum(nums1[i:]), ss + sum(nums2[ii:])) \n return ans % 1_000_000_007", "slug": "get-the-maximum-score", "post_title": "[Python3] range sum with two pointers O(M+N)", "user": "ye15", "upvotes": 1, "views": 73, "problem_title": "get the maximum score", "number": 1537, "acceptance": 0.3929999999999999, "difficulty": "Hard", "__index_level_0__": 22746, "question": "You are given two sorted arrays of distinct integers nums1 and nums2.\nA valid path is defined as follows:\nChoose array nums1 or nums2 to traverse (from index-0).\nTraverse the current array from left to right.\nIf 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).\nThe score is defined as the sum of unique values in a valid path.\nReturn the maximum score you can obtain of all possible valid paths. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\nOutput: 30\nExplanation: Valid paths:\n[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\nThe maximum is obtained with the path in green [2,4,6,8,10].\nExample 2:\nInput: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\nOutput: 109\nExplanation: Maximum sum is obtained with the path [1,3,5,100].\nExample 3:\nInput: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\nOutput: 40\nExplanation: There are no common elements between nums1 and nums2.\nMaximum sum is obtained with the path [6,7,8,9,10].\n Constraints:\n1 <= nums1.length, nums2.length <= 105\n1 <= nums1[i], nums2[i] <= 107\nnums1 and nums2 are strictly increasing." }, { "post_href": "https://leetcode.com/problems/kth-missing-positive-number/discuss/784720/Python3-O(N)-and-O(logN)-solutions", "python_solutions": "class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n ss, x = set(arr), 1\n while True: \n if x not in ss: k -= 1\n if not k: return x\n x += 1", "slug": "kth-missing-positive-number", "post_title": "[Python3] O(N) and O(logN) solutions", "user": "ye15", "upvotes": 5, "views": 240, "problem_title": "kth missing positive number", "number": 1539, "acceptance": 0.56, "difficulty": "Easy", "__index_level_0__": 22749, "question": "Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.\nReturn the kth positive integer that is missing from this array.\n Example 1:\nInput: arr = [2,3,4,7,11], k = 5\nOutput: 9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.\nExample 2:\nInput: arr = [1,2,3,4], k = 2\nOutput: 6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n Constraints:\n1 <= arr.length <= 1000\n1 <= arr[i] <= 1000\n1 <= k <= 1000\narr[i] < arr[j] for 1 <= i < j <= arr.length\n Follow up:\nCould you solve this problem in less than O(n) complexity?" }, { "post_href": "https://leetcode.com/problems/can-convert-string-in-k-moves/discuss/2155709/python-3-or-simple-O(n)O(1)-solution", "python_solutions": "class Solution:\n def canConvertString(self, s: str, t: str, k: int) -> bool:\n if len(s) != len(t):\n return False\n \n cycles, extra = divmod(k, 26)\n shifts = [cycles + (shift <= extra) for shift in range(26)]\n\n for cs, ct in zip(s, t):\n shift = (ord(ct) - ord(cs)) % 26\n if shift == 0:\n continue\n if not shifts[shift]:\n return False\n shifts[shift] -= 1\n \n return True", "slug": "can-convert-string-in-k-moves", "post_title": "python 3 | simple O(n)/O(1) solution", "user": "dereky4", "upvotes": 0, "views": 67, "problem_title": "can convert string in k moves", "number": 1540, "acceptance": 0.332, "difficulty": "Medium", "__index_level_0__": 22800, "question": "Given two strings s and t, your goal is to convert s into t in k moves or less.\nDuring the ith (1 <= i <= k) move you can:\nChoose any index j (1-indexed) from s, such that 1 <= j <= s.length and j has not been chosen in any previous move, and shift the character at that index i times.\nDo nothing.\nShifting a character means replacing it by the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Shifting a character by i means applying the shift operations i times.\nRemember that any index j can be picked at most once.\nReturn true if it's possible to convert s into t in no more than k moves, otherwise return false.\n Example 1:\nInput: s = \"input\", t = \"ouput\", k = 9\nOutput: true\nExplanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.\nExample 2:\nInput: s = \"abc\", t = \"bcd\", k = 10\nOutput: false\nExplanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.\nExample 3:\nInput: s = \"aab\", t = \"bbb\", k = 27\nOutput: true\nExplanation: In the 1st move, we shift the first 'a' 1 time to get 'b'. In the 27th move, we shift the second 'a' 27 times to get 'b'.\n Constraints:\n1 <= s.length, t.length <= 10^5\n0 <= k <= 10^9\ns, t contain only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/discuss/2825876/Python", "python_solutions": "class Solution:\n def minInsertions(self, s: str) -> int:\n \"\"\"\n (\n \"\"\"\n res = need = 0\n\n for i in range(len(s)):\n if s[i] == '(':\n need += 2\n if need % 2 == 1:\n res += 1\n need -= 1\n if s[i] == ')':\n need -= 1\n if need == -1:\n res += 1\n need = 1\n return res + need", "slug": "minimum-insertions-to-balance-a-parentheses-string", "post_title": "Python", "user": "lillllllllly", "upvotes": 0, "views": 2, "problem_title": "minimum insertions to balance a parentheses string", "number": 1541, "acceptance": 0.499, "difficulty": "Medium", "__index_level_0__": 22804, "question": "Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:\nAny left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.\nLeft parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.\nIn other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.\nFor example, \"())\", \"())(())))\" and \"(())())))\" are balanced, \")()\", \"()))\" and \"(()))\" are not balanced.\nYou can insert the characters '(' and ')' at any position of the string to balance it if needed.\nReturn the minimum number of insertions needed to make s balanced.\n Example 1:\nInput: s = \"(()))\"\nOutput: 1\nExplanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.\nExample 2:\nInput: s = \"())\"\nOutput: 0\nExplanation: The string is already balanced.\nExample 3:\nInput: s = \"))())(\"\nOutput: 3\nExplanation: Add '(' to match the first '))', Add '))' to match the last '('.\n Constraints:\n1 <= s.length <= 105\ns consists of '(' and ')' only." }, { "post_href": "https://leetcode.com/problems/find-longest-awesome-substring/discuss/2259262/Python3-or-Prefix-xor-or-O(n)-Solution", "python_solutions": "class Solution:\n def longestAwesome(self, s: str) -> int:\n # li = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n li = [2**i for i in range(10)]\n # checker = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}\n checker = set(li)\n checker.add(0)\n # di: k = prefix xor, v = the first idx I got a new prefix_xor_value.\n di = collections.OrderedDict({0: -1})\n maxLength = prefix_xor = 0\n \n for i in range(len(s)):\n prefix_xor ^= li[int(s[i])]\n # Found a new prefix_xor_value\n if prefix_xor not in di:\n di[prefix_xor] = i\n \n # XOR operation with previous prefix_xor_value\n for key in di.keys():\n if i - di[key] <= maxLength:\n break\n\t\t\t\t# s[di[key] : i] is Awesome Substring\n if key ^ prefix_xor in checker:\n maxLength = i - di[key]\n return maxLength", "slug": "find-longest-awesome-substring", "post_title": "Python3 | Prefix xor | O(n) Solution", "user": "shugokra", "upvotes": 1, "views": 75, "problem_title": "find longest awesome substring", "number": 1542, "acceptance": 0.414, "difficulty": "Hard", "__index_level_0__": 22816, "question": "You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.\nReturn the length of the maximum length awesome substring of s.\n Example 1:\nInput: s = \"3242415\"\nOutput: 5\nExplanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\nExample 2:\nInput: s = \"12345678\"\nOutput: 1\nExample 3:\nInput: s = \"213123\"\nOutput: 6\nExplanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n Constraints:\n1 <= s.length <= 105\ns consists only of digits." }, { "post_href": "https://leetcode.com/problems/make-the-string-great/discuss/781044/Python3-5-line-stack-O(N)", "python_solutions": "class Solution:\n def makeGood(self, s: str) -> str:\n stack = []\n for c in s: \n if stack and abs(ord(stack[-1]) - ord(c)) == 32: stack.pop() #pop \"bad\"\n else: stack.append(c) #push \"good\"\n return \"\".join(stack)", "slug": "make-the-string-great", "post_title": "[Python3] 5-line stack O(N)", "user": "ye15", "upvotes": 34, "views": 1400, "problem_title": "make the string great", "number": 1544, "acceptance": 0.633, "difficulty": "Easy", "__index_level_0__": 22818, "question": "Given a string s of lower and upper case English letters.\nA good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:\n0 <= i <= s.length - 2\ns[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.\nTo make the string good, you can choose two adjacent characters that make the string bad and remove them. You can keep doing this until the string becomes good.\nReturn the string after making it good. The answer is guaranteed to be unique under the given constraints.\nNotice that an empty string is also good.\n Example 1:\nInput: s = \"leEeetcode\"\nOutput: \"leetcode\"\nExplanation: In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".\nExample 2:\nInput: s = \"abBAcC\"\nOutput: \"\"\nExplanation: We have many possible scenarios, and all lead to the same answer. For example:\n\"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n\"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"\nExample 3:\nInput: s = \"s\"\nOutput: \"s\"\n Constraints:\n1 <= s.length <= 100\ns contains only lower and upper case English letters." }, { "post_href": "https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/discuss/781062/Python3-4-line-recursive", "python_solutions": "class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n if k == 1: return \"0\"\n if k == 2**(n-1): return \"1\"\n if k < 2**(n-1): return self.findKthBit(n-1, k)\n return \"0\" if self.findKthBit(n-1, 2**n-k) == \"1\" else \"1\"", "slug": "find-kth-bit-in-nth-binary-string", "post_title": "[Python3] 4-line recursive", "user": "ye15", "upvotes": 11, "views": 432, "problem_title": "find kth bit in nth binary string", "number": 1545, "acceptance": 0.583, "difficulty": "Medium", "__index_level_0__": 22872, "question": "Given two positive integers n and k, the binary string Sn is formed as follows:\nS1 = \"0\"\nSi = Si - 1 + \"1\" + reverse(invert(Si - 1)) for i > 1\nWhere + denotes the concatenation operation, reverse(x) returns the reversed string x, and invert(x) inverts all the bits in x (0 changes to 1 and 1 changes to 0).\nFor example, the first four strings in the above sequence are:\nS1 = \"0\"\nS2 = \"011\"\nS3 = \"0111001\"\nS4 = \"011100110110001\"\nReturn the kth bit in Sn. It is guaranteed that k is valid for the given n.\n Example 1:\nInput: n = 3, k = 1\nOutput: \"0\"\nExplanation: S3 is \"0111001\".\nThe 1st bit is \"0\".\nExample 2:\nInput: n = 4, k = 11\nOutput: \"1\"\nExplanation: S4 is \"011100110110001\".\nThe 11th bit is \"1\".\n Constraints:\n1 <= n <= 20\n1 <= k <= 2n - 1" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/discuss/781075/Python3-O(N)-prefix-sum", "python_solutions": "class Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n ans = prefix = 0\n seen = set([0]) #prefix sum seen so far ()\n for i, x in enumerate(nums): \n prefix += x\n if prefix - target in seen:\n ans += 1\n seen.clear() #reset seen\n seen.add(prefix)\n return ans", "slug": "maximum-number-of-non-overlapping-subarrays-with-sum-equals-target", "post_title": "[Python3] O(N) prefix sum", "user": "ye15", "upvotes": 2, "views": 54, "problem_title": "maximum number of non overlapping subarrays with sum equals target", "number": 1546, "acceptance": 0.472, "difficulty": "Medium", "__index_level_0__": 22892, "question": "Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.\n Example 1:\nInput: nums = [1,1,1,1,1], target = 2\nOutput: 2\nExplanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).\nExample 2:\nInput: nums = [-1,3,5,1,4,2,-9], target = 6\nOutput: 2\nExplanation: There are 3 subarrays with sum equal to 6.\n([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.\n Constraints:\n1 <= nums.length <= 105\n-104 <= nums[i] <= 104\n0 <= target <= 106" }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-cut-a-stick/discuss/781085/Python3-top-down-and-bottom-up-dp", "python_solutions": "class Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n \n @lru_cache(None)\n def fn(lo, hi): \n \"\"\"Return cost of cutting [lo, hi].\"\"\"\n cc = [c for c in cuts if lo < c < hi] #collect cuts within this region \n if not cc: return 0\n ans = inf\n for mid in cc: ans = min(ans, fn(lo, mid) + fn(mid, hi))\n return ans + hi - lo\n \n return fn(0, n)", "slug": "minimum-cost-to-cut-a-stick", "post_title": "[Python3] top-down & bottom-up dp", "user": "ye15", "upvotes": 6, "views": 488, "problem_title": "minimum cost to cut a stick", "number": 1547, "acceptance": 0.57, "difficulty": "Hard", "__index_level_0__": 22897, "question": "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:\nGiven an integer array cuts where cuts[i] denotes a position you should perform a cut at.\nYou should perform the cuts in order, you can change the order of the cuts as you wish.\nThe cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\nReturn the minimum total cost of the cuts.\n Example 1:\nInput: n = 7, cuts = [1,3,4,5]\nOutput: 16\nExplanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\nThe first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\nRearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\nExample 2:\nInput: n = 9, cuts = [5,6,1,4,2]\nOutput: 22\nExplanation: If you try the given cuts ordering the cost will be 25.\nThere are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n Constraints:\n2 <= n <= 106\n1 <= cuts.length <= min(n - 1, 100)\n1 <= cuts[i] <= n - 1\nAll the integers in cuts array are distinct." }, { "post_href": "https://leetcode.com/problems/three-consecutive-odds/discuss/794097/Python3-straight-forward-solution", "python_solutions": "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n count = 0\n \n for i in range(0, len(arr)):\n if arr[i] %2 != 0:\n count += 1\n if count == 3:\n return True\n else:\n count = 0\n return False", "slug": "three-consecutive-odds", "post_title": "Python3 straight forward solution", "user": "sjha2048", "upvotes": 20, "views": 1600, "problem_title": "three consecutive odds", "number": 1550, "acceptance": 0.636, "difficulty": "Easy", "__index_level_0__": 22903, "question": "Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.\n Example 1:\nInput: arr = [2,6,4,1]\nOutput: false\nExplanation: There are no three consecutive odds.\nExample 2:\nInput: arr = [1,2,34,3,4,5,7,23,12]\nOutput: true\nExplanation: [5,7,23] are three consecutive odds.\n Constraints:\n1 <= arr.length <= 1000\n1 <= arr[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-make-array-equal/discuss/1704407/Understandable-code-for-beginners-like-me-in-python-!!", "python_solutions": "class Solution:\n def minOperations(self, n: int) -> int:\n if(n%2!=0):\n n=n//2\n return n*(n+1)\n else:\n n=n//2\n return n**2", "slug": "minimum-operations-to-make-array-equal", "post_title": "Understandable code for beginners like me in python !!", "user": "kabiland", "upvotes": 2, "views": 92, "problem_title": "minimum operations to make array equal", "number": 1551, "acceptance": 0.8109999999999999, "difficulty": "Medium", "__index_level_0__": 22937, "question": "You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e., 0 <= i < n).\nIn one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e., perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.\nGiven an integer n, the length of the array, return the minimum number of operations needed to make all the elements of arr equal.\n Example 1:\nInput: n = 3\nOutput: 2\nExplanation: arr = [1, 3, 5]\nFirst operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\nIn the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].\nExample 2:\nInput: n = 6\nOutput: 9\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/magnetic-force-between-two-balls/discuss/794249/Python3-binary-search-distance-space", "python_solutions": "class Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n position.sort()\n \n def fn(d):\n \"\"\"Return True if d is a feasible distance.\"\"\"\n ans, prev = 0, -inf # where previous ball is put\n for x in position:\n if x - prev >= d: \n ans += 1\n if ans == m: return True\n prev = x\n return False \n \n\t\t# \"last True\" binary search (in contrast to \"first True\" binary search)\n lo, hi = 1, position[-1] - position[0]\n while lo < hi: \n mid = lo + hi + 1 >> 1\n if fn(mid): lo = mid\n else: hi = mid - 1\n return lo", "slug": "magnetic-force-between-two-balls", "post_title": "[Python3] binary search distance space", "user": "ye15", "upvotes": 4, "views": 473, "problem_title": "magnetic force between two balls", "number": 1552, "acceptance": 0.57, "difficulty": "Medium", "__index_level_0__": 22962, "question": "In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the ith basket is at position[i], Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.\nRick stated that magnetic force between two different balls at positions x and y is |x - y|.\nGiven the integer array position and the integer m. Return the required force.\n Example 1:\nInput: position = [1,2,3,4,7], m = 3\nOutput: 3\nExplanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\nExample 2:\nInput: position = [5,4,3,2,1,1000000000], m = 2\nOutput: 999999999\nExplanation: We can use baskets 1 and 1000000000.\n Constraints:\nn == position.length\n2 <= n <= 105\n1 <= position[i] <= 109\nAll integers in position are distinct.\n2 <= m <= position.length" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-days-to-eat-n-oranges/discuss/794275/Python3-bfs", "python_solutions": "class Solution:\n def minDays(self, n: int) -> int:\n ans = 0\n queue = [n]\n seen = set()\n while queue: #bfs \n newq = []\n for x in queue: \n if x == 0: return ans \n seen.add(x)\n if x-1 not in seen: newq.append(x-1)\n if x % 2 == 0 and x//2 not in seen: newq.append(x//2)\n if x % 3 == 0 and x//3 not in seen: newq.append(x//3)\n ans += 1\n queue = newq", "slug": "minimum-number-of-days-to-eat-n-oranges", "post_title": "[Python3] bfs", "user": "ye15", "upvotes": 26, "views": 1500, "problem_title": "minimum number of days to eat n oranges", "number": 1553, "acceptance": 0.346, "difficulty": "Hard", "__index_level_0__": 22969, "question": "There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:\nEat one orange.\nIf the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.\nIf the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.\nYou can only choose one of the actions per day.\nGiven the integer n, return the minimum number of days to eat n oranges.\n Example 1:\nInput: n = 10\nOutput: 4\nExplanation: You have 10 oranges.\nDay 1: Eat 1 orange, 10 - 1 = 9. \nDay 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\nDay 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \nDay 4: Eat the last orange 1 - 1 = 0.\nYou need at least 4 days to eat the 10 oranges.\nExample 2:\nInput: n = 6\nOutput: 3\nExplanation: You have 6 oranges.\nDay 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\nDay 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\nDay 3: Eat the last orange 1 - 1 = 0.\nYou need at least 3 days to eat the 6 oranges.\n Constraints:\n1 <= n <= 2 * 109" }, { "post_href": "https://leetcode.com/problems/thousand-separator/discuss/805712/Python3-1-line", "python_solutions": "class Solution:\n def thousandSeparator(self, n: int) -> str:\n return f\"{n:,}\".replace(\",\", \".\")", "slug": "thousand-separator", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 25, "views": 980, "problem_title": "thousand separator", "number": 1556, "acceptance": 0.5489999999999999, "difficulty": "Easy", "__index_level_0__": 22975, "question": "Given an integer n, add a dot (\".\") as the thousands separator and return it in string format.\n Example 1:\nInput: n = 987\nOutput: \"987\"\nExample 2:\nInput: n = 1234\nOutput: \"1.234\"\n Constraints:\n0 <= n <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/discuss/1212672/Python-Easy-Solution-Count-of-Nodes-with-Zero-Incoming-Degree", "python_solutions": "class Solution:\n def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n if not edges:\n return []\n \n incoming_degrees = {i: 0 for i in range(n)}\n \n for x, y in edges:\n incoming_degrees[y] += 1\n \n result = [k for k, v in incoming_degrees.items() if v == 0]\n return result", "slug": "minimum-number-of-vertices-to-reach-all-nodes", "post_title": "Python Easy Solution - Count of Nodes with Zero Incoming-Degree", "user": "ChidinmaKO", "upvotes": 4, "views": 195, "problem_title": "minimum number of vertices to reach all nodes", "number": 1557, "acceptance": 0.7959999999999999, "difficulty": "Medium", "__index_level_0__": 23002, "question": "Given a directed acyclic graph, with n vertices numbered from 0 to n-1, and an array edges where edges[i] = [fromi, toi] represents a directed edge from node fromi to node toi.\nFind the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.\nNotice that you can return the vertices in any order.\n Example 1:\nInput: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]\nOutput: [0,3]\nExplanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].\nExample 2:\nInput: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]\nOutput: [0,2,3]\nExplanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.\n Constraints:\n2 <= n <= 10^5\n1 <= edges.length <= min(10^5, n * (n - 1) / 2)\nedges[i].length == 2\n0 <= fromi, toi < n\nAll pairs (fromi, toi) are distinct." }, { "post_href": "https://leetcode.com/problems/minimum-numbers-of-function-calls-to-make-target-array/discuss/807358/Python-Bit-logic-Explained", "python_solutions": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n return sum(bin(a).count('1') for a in nums) + len(bin(max(nums))) - 2 - 1", "slug": "minimum-numbers-of-function-calls-to-make-target-array", "post_title": "Python Bit logic Explained", "user": "akhil_ak", "upvotes": 3, "views": 125, "problem_title": "minimum numbers of function calls to make target array", "number": 1558, "acceptance": 0.642, "difficulty": "Medium", "__index_level_0__": 23031, "question": "You are given an integer array nums. You have an integer array arr of the same length with all values set to 0 initially. You also have the following modify function:\nYou want to use the modify function to convert arr to nums using the minimum number of calls.\nReturn the minimum number of function calls to make nums from arr.\nThe test cases are generated so that the answer fits in a 32-bit signed integer.\n Example 1:\nInput: nums = [1,5]\nOutput: 5\nExplanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\nDouble all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).\nIncrement by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).\nTotal of operations: 1 + 2 + 2 = 5.\nExample 2:\nInput: nums = [2,2]\nOutput: 3\nExplanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\nDouble all the elements: [1, 1] -> [2, 2] (1 operation).\nTotal of operations: 2 + 1 = 3.\nExample 3:\nInput: nums = [4,2,5]\nOutput: 6\nExplanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/detect-cycles-in-2d-grid/discuss/806630/Python3-memoized-dfs-with-a-direction-parameter-(16-line)", "python_solutions": "class Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j, d): \n \"\"\"Traverse the grid to find cycle via backtracking.\"\"\"\n if grid[i][j] != \"BLACK\": \n val = grid[i][j]\n grid[i][j] = \"GRAY\" # mark visited in this trial\n for ii, jj, dd in ((i-1, j, -2), (i, j-1, -1), (i, j+1, 1), (i+1, j, 2)):\n if 0 <= ii < m and 0 <= jj < n and d + dd != 0: # in range & not going back \n if grid[ii][jj] == \"GRAY\": return True #cycle found \n if grid[ii][jj] == val: fn(ii, jj, dd)\n grid[i][j] = val \n \n for i in range(m):\n for j in range(n):\n if fn(i, j, 0): return True\n grid[i][j] = \"BLACK\" # mark \"no cycle\"\n return False", "slug": "detect-cycles-in-2d-grid", "post_title": "[Python3] memoized dfs with a direction parameter (16-line)", "user": "ye15", "upvotes": 1, "views": 75, "problem_title": "detect cycles in 2d grid", "number": 1559, "acceptance": 0.48, "difficulty": "Medium", "__index_level_0__": 23037, "question": "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.\nA cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.\nAlso, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.\nReturn true if any cycle of the same value exists in grid, otherwise, return false.\n Example 1:\nInput: grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\nOutput: true\nExplanation: There are two valid cycles shown in different colors in the image below:\nExample 2:\nInput: grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\nOutput: true\nExplanation: There is only one valid cycle highlighted in the image below:\nExample 3:\nInput: grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\nOutput: false\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 500\ngrid consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/most-visited-sector-in-a-circular-track/discuss/806738/Python3-2-line", "python_solutions": "class Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n x, xx = rounds[0], rounds[-1]\n return list(range(x, xx+1)) if x <= xx else list(range(1, xx+1)) + list(range(x, n+1))", "slug": "most-visited-sector-in-a-circular-track", "post_title": "[Python3] 2-line", "user": "ye15", "upvotes": 10, "views": 1200, "problem_title": "most visited sector in a circular track", "number": 1560, "acceptance": 0.584, "difficulty": "Easy", "__index_level_0__": 23046, "question": "Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]\nReturn an array of the most visited sectors sorted in ascending order.\nNotice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).\n Example 1:\nInput: n = 4, rounds = [1,3,1,2]\nOutput: [1,2]\nExplanation: The marathon starts at sector 1. The order of the visited sectors is as follows:\n1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\nWe can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.\nExample 2:\nInput: n = 2, rounds = [2,1,2,1,2,1,2,1,2]\nOutput: [2]\nExample 3:\nInput: n = 7, rounds = [1,3,5,7]\nOutput: [1,2,3,4,5,6,7]\n Constraints:\n2 <= n <= 100\n1 <= m <= 100\nrounds.length == m + 1\n1 <= rounds[i] <= n\nrounds[i] != rounds[i + 1] for 0 <= i < m" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-coins-you-can-get/discuss/1232262/Python-Simple-Solution", "python_solutions": "class Solution:\n def maxCoins(self, piles: List[int]) -> int:\n piles.sort(reverse=True)\n sum = 0\n for i in range(1,len(piles)-int(len(piles)/3),2):\n sum += piles[i]\n print(sum)\n return sum", "slug": "maximum-number-of-coins-you-can-get", "post_title": "Python Simple Solution", "user": "yashwant_mahawar", "upvotes": 2, "views": 146, "problem_title": "maximum number of coins you can get", "number": 1561, "acceptance": 0.7859999999999999, "difficulty": "Medium", "__index_level_0__": 23052, "question": "There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:\nIn each step, you will choose any 3 piles of coins (not necessarily consecutive).\nOf your choice, Alice will pick the pile with the maximum number of coins.\nYou will pick the next pile with the maximum number of coins.\nYour friend Bob will pick the last pile.\nRepeat until there are no more piles of coins.\nGiven an array of integers piles where piles[i] is the number of coins in the ith pile.\nReturn the maximum number of coins that you can have.\n Example 1:\nInput: piles = [2,4,1,2,7,8]\nOutput: 9\nExplanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.\nChoose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.\nThe maximum number of coins which you can have are: 7 + 2 = 9.\nOn the other hand if we choose this arrangement (1, 2, 8), (2, 4, 7) you only get 2 + 4 = 6 coins which is not optimal.\nExample 2:\nInput: piles = [2,4,5]\nOutput: 4\nExample 3:\nInput: piles = [9,8,7,6,5,1,2,3,4]\nOutput: 18\n Constraints:\n3 <= piles.length <= 105\npiles.length % 3 == 0\n1 <= piles[i] <= 104" }, { "post_href": "https://leetcode.com/problems/find-latest-group-of-size-m/discuss/809823/Python3-summarizing-two-approaches", "python_solutions": "class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n span = [0]*(len(arr)+2)\n freq = [0]*(len(arr)+1)\n ans = -1\n for i, x in enumerate(arr, 1): \n freq[span[x-1]] -= 1\n freq[span[x+1]] -= 1\n span[x] = span[x-span[x-1]] = span[x+span[x+1]] = 1 + span[x-1] + span[x+1]\n freq[span[x]] += 1\n \n if freq[m]: ans = i\n return ans", "slug": "find-latest-group-of-size-m", "post_title": "[Python3] summarizing two approaches", "user": "ye15", "upvotes": 0, "views": 57, "problem_title": "find latest group of size m", "number": 1562, "acceptance": 0.425, "difficulty": "Medium", "__index_level_0__": 23086, "question": "Given an array arr that represents a permutation of numbers from 1 to n.\nYou have a binary string of size n that initially has all its bits set to zero. At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1.\nYou are also given an integer m. Find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1's such that it cannot be extended in either direction.\nReturn the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.\n Example 1:\nInput: arr = [3,5,1,2,4], m = 1\nOutput: 4\nExplanation: \nStep 1: \"00100\", groups: [\"1\"]\nStep 2: \"00101\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"11101\", groups: [\"111\", \"1\"]\nStep 5: \"11111\", groups: [\"11111\"]\nThe latest step at which there exists a group of size 1 is step 4.\nExample 2:\nInput: arr = [3,1,5,4,2], m = 2\nOutput: -1\nExplanation: \nStep 1: \"00100\", groups: [\"1\"]\nStep 2: \"10100\", groups: [\"1\", \"1\"]\nStep 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\nStep 4: \"10111\", groups: [\"1\", \"111\"]\nStep 5: \"11111\", groups: [\"11111\"]\nNo group of size 2 exists during any step.\n Constraints:\nn == arr.length\n1 <= m <= n <= 105\n1 <= arr[i] <= n\nAll integers in arr are distinct." }, { "post_href": "https://leetcode.com/problems/stone-game-v/discuss/1504994/Python-O(n2)-optimized-solution.-O(n3)-cannot-pass.", "python_solutions": "class Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n length = len(stoneValue)\n if length == 1:\n return 0\n \n\t\t# Calculate sum\n s = [0 for _ in range(length)]\n s[0] = stoneValue[0]\n for i in range(1, length):\n s[i] = s[i-1] + stoneValue[i]\n\t\t\n\t\t# dp for best value, best_cut for where is the cut in (i, j), i, j inclusive\n dp = [[0 for _ in range(length)] for _ in range(length)]\n best_cut = [[0 for _ in range(length)] for _ in range(length)]\n \n for i in range(0, length-1):\n dp[i][i+1] = min(stoneValue[i], stoneValue[i+1])\n best_cut[i][i+1] = i\n \n for t in range(2, length):\n for i in range(0, length-t):\n tmp_dp = 0\n tmp_cut = 0\n left_bound = best_cut[i][i+t-1]\n if left_bound > i:\n left_bound -= 1\n right_bound = best_cut[i+1][i+t]\n if right_bound < i+t-1:\n right_bound += 1\n \n for k in range(left_bound, 1+right_bound):\n s1 = s[k] - s[i-1] if i > 0 else s[k]\n s2 = s[i+t] - s[k]\n if s1 < s2:\n tmp = s1 + dp[i][k]\n if tmp > tmp_dp:\n tmp_dp = tmp\n tmp_cut = k\n elif s1 > s2:\n tmp = s2 + dp[k+1][i+t]\n if tmp > tmp_dp:\n tmp_dp = tmp\n tmp_cut = k\n else:\n tmp1 = s1 + dp[i][k]\n tmp2 = s2 + dp[k+1][i+t]\n if tmp1 > tmp_dp:\n tmp_dp = tmp1\n tmp_cut = k\n if tmp2 > tmp_dp:\n tmp_dp = tmp2\n tmp_cut = k\n \n dp[i][i+t] = tmp_dp\n best_cut[i][i+t] = tmp_cut\n \n return dp[0][length-1]", "slug": "stone-game-v", "post_title": "Python O(n^2) optimized solution. O(n^3) cannot pass.", "user": "pureme", "upvotes": 4, "views": 202, "problem_title": "stone game v", "number": 1563, "acceptance": 0.406, "difficulty": "Hard", "__index_level_0__": 23087, "question": "There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\nIn each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\nThe game ends when there is only one stone remaining. Alice's is initially zero.\nReturn the maximum score that Alice can obtain.\n Example 1:\nInput: stoneValue = [6,2,3,4,5,5]\nOutput: 18\nExplanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\nIn the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\nThe last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\nExample 2:\nInput: stoneValue = [7,7,7,7,7,7,7]\nOutput: 28\nExample 3:\nInput: stoneValue = [4]\nOutput: 0\n Constraints:\n1 <= stoneValue.length <= 500\n1 <= stoneValue[i] <= 106" }, { "post_href": "https://leetcode.com/problems/detect-pattern-of-length-m-repeated-k-or-more-times/discuss/1254278/Python3-simple-solution", "python_solutions": "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n for i in range(len(arr)-m+1):\n count = 1\n x = arr[i:i+m]\n res = 1\n for j in range(i+m,len(arr)-m+1,m):\n if x == arr[j:j+m]:\n count += 1\n else:\n res = max(res,count)\n count = 1\n x = arr[j:j+m]\n res = max(res,count)\n if res >= k:\n return True\n return False", "slug": "detect-pattern-of-length-m-repeated-k-or-more-times", "post_title": "Python3 simple solution", "user": "EklavyaJoshi", "upvotes": 2, "views": 124, "problem_title": "detect pattern of length m repeated k or more times", "number": 1566, "acceptance": 0.436, "difficulty": "Easy", "__index_level_0__": 23092, "question": "Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.\nA pattern is a subarray (consecutive sub-sequence) that consists of one or more values, repeated multiple times consecutively without overlapping. A pattern is defined by its length and the number of repetitions.\nReturn true if there exists a pattern of length m that is repeated k or more times, otherwise return false.\n Example 1:\nInput: arr = [1,2,4,4,4,4], m = 1, k = 3\nOutput: true\nExplanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.\nExample 2:\nInput: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2\nOutput: true\nExplanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.\nExample 3:\nInput: arr = [1,2,1,2,1,3], m = 2, k = 3\nOutput: false\nExplanation: The pattern (1,2) is of length 2 but is repeated only 2 times. There is no pattern of length 2 that is repeated 3 or more times.\n Constraints:\n2 <= arr.length <= 100\n1 <= arr[i] <= 100\n1 <= m <= 100\n2 <= k <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-length-of-subarray-with-positive-product/discuss/819332/Python3-7-line-O(N)-time-and-O(1)-space", "python_solutions": "class Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n ans = pos = neg = 0\n for x in nums: \n if x > 0: pos, neg = 1 + pos, 1 + neg if neg else 0\n elif x < 0: pos, neg = 1 + neg if neg else 0, 1 + pos\n else: pos = neg = 0 # reset \n ans = max(ans, pos)\n return ans", "slug": "maximum-length-of-subarray-with-positive-product", "post_title": "[Python3] 7-line O(N) time & O(1) space", "user": "ye15", "upvotes": 59, "views": 2700, "problem_title": "maximum length of subarray with positive product", "number": 1567, "acceptance": 0.4379999999999999, "difficulty": "Medium", "__index_level_0__": 23107, "question": "Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.\nA subarray of an array is a consecutive sequence of zero or more values taken out of that array.\nReturn the maximum length of a subarray with positive product.\n Example 1:\nInput: nums = [1,-2,-3,4]\nOutput: 4\nExplanation: The array nums already has a positive product of 24.\nExample 2:\nInput: nums = [0,1,-2,-3,-4]\nOutput: 3\nExplanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.\nNotice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.\nExample 3:\nInput: nums = [-1,-2,-3,0,1]\nOutput: 2\nExplanation: The longest subarray with positive product is [-1,-2] or [-2,-3].\n Constraints:\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-days-to-disconnect-island/discuss/819360/Python3-bfs", "python_solutions": "class Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimension \n grid = \"\".join(\"\".join(map(str, x)) for x in grid)\n \n @lru_cache(None)\n def fn(s): \n \"\"\"Return True if grid is disconnected.\"\"\"\n row, grid = [], []\n for i, c in enumerate(s, 1):\n row.append(int(c))\n if i%n == 0: \n grid.append(row)\n row = []\n \n def dfs(i, j): \n \"\"\"\"\"\"\n grid[i][j] = 0\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj]: dfs(ii, jj)\n return 1\n return sum(dfs(i, j) for i in range(m) for j in range(n) if grid[i][j])\n \n #bfs \n queue = [grid]\n level = 0 \n seen = {grid}\n while queue: \n tmp = []\n for node in queue: \n if fn(node) == 0 or fn(node) >= 2: return level \n for i in range(m*n):\n if node[i] == \"1\": \n nn = node[:i] + \"0\" + node[i+1:]\n if nn not in seen: \n seen.add(nn)\n tmp.append(nn)\n queue = tmp\n level += 1", "slug": "minimum-number-of-days-to-disconnect-island", "post_title": "[Python3] bfs", "user": "ye15", "upvotes": 0, "views": 66, "problem_title": "minimum number of days to disconnect island", "number": 1568, "acceptance": 0.4679999999999999, "difficulty": "Hard", "__index_level_0__": 23132, "question": "You are given an m x n binary grid grid where 1 represents land and 0 represents water. An island is a maximal 4-directionally (horizontal or vertical) connected group of 1's.\nThe grid is said to be connected if we have exactly one island, otherwise is said disconnected.\nIn one day, we are allowed to change any single land cell (1) into a water cell (0).\nReturn the minimum number of days to disconnect the grid.\n Example 1:\nInput: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\n\nOutput: 2\nExplanation: We need at least 2 days to get a disconnected grid.\nChange land grid[1][1] and grid[0][2] to water and get 2 disconnected island.\nExample 2:\nInput: grid = [[1,1]]\nOutput: 2\nExplanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 30\ngrid[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-reorder-array-to-get-same-bst/discuss/819349/Python3-math-ish", "python_solutions": "class Solution:\n def numOfWays(self, nums: List[int]) -> int:\n \n def fn(nums): \n \"\"\"Post-order traversal.\"\"\"\n if len(nums) <= 1: return len(nums) # boundary condition \n ll = [x for x in nums if x < nums[0]]\n rr = [x for x in nums if x > nums[0]]\n left, right = fn(ll), fn(rr)\n if not left or not right: return left or right\n ans = comb(len(rr)+len(ll), len(rr))\n return ans*left*right\n \n return (fn(nums)-1) % 1_000_000_007", "slug": "number-of-ways-to-reorder-array-to-get-same-bst", "post_title": "[Python3] math-ish", "user": "ye15", "upvotes": 2, "views": 337, "problem_title": "number of ways to reorder array to get same bst", "number": 1569, "acceptance": 0.481, "difficulty": "Hard", "__index_level_0__": 23133, "question": "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.\nFor 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.\nReturn the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.\nSince the answer may be very large, return it modulo 109 + 7.\n Example 1:\nInput: nums = [2,1,3]\nOutput: 1\nExplanation: 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.\nExample 2:\nInput: nums = [3,4,5,1,2]\nOutput: 5\nExplanation: 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]\nExample 3:\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: There are no other orderings of nums that will yield the same BST.\n Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= nums.length\nAll integers in nums are distinct." }, { "post_href": "https://leetcode.com/problems/matrix-diagonal-sum/discuss/1369404/PYTHON-Best-solution-with-explanation.-SC-%3A-O(1)-TC-%3A-O(n)", "python_solutions": "class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n \"\"\"\n The primary diagonal is formed by the elements A00, A11, A22, A33.\n Condition for Primary Diagonal:\n The row-column condition is row = column.\n\n The secondary diagonal is formed by the elements A03, A12, A21, A30. \n Condition for Secondary Diagonal:\n The row-column condition is row = numberOfRows - column -1.\n \"\"\"\n s = 0\n l , mid = len(mat), len(mat)//2\n for i in range(l):\n s += mat[i][i] # primary diagonal\n s += mat[len(mat)-i-1][i] # secondary diagonal\n \n # If the mat is odd, then diagonal will coincide, so subtract the middle element\n if l%2 != 0:\n s -= mat[mid][mid]\n \n return s", "slug": "matrix-diagonal-sum", "post_title": "[PYTHON] Best solution with explanation. SC : O(1) TC : O(n)", "user": "er1shivam", "upvotes": 5, "views": 233, "problem_title": "matrix diagonal sum", "number": 1572, "acceptance": 0.7979999999999999, "difficulty": "Easy", "__index_level_0__": 23135, "question": "Given a square matrix mat, return the sum of the matrix diagonals.\nOnly include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.\n Example 1:\nInput: mat = [[1,2,3],\n [4,5,6],\n [7,8,9]]\nOutput: 25\nExplanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\nNotice that element mat[1][1] = 5 is counted only once.\nExample 2:\nInput: mat = [[1,1,1,1],\n [1,1,1,1],\n [1,1,1,1],\n [1,1,1,1]]\nOutput: 8\nExample 3:\nInput: mat = [[5]]\nOutput: 5\n Constraints:\nn == mat.length == mat[i].length\n1 <= n <= 100\n1 <= mat[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-split-a-string/discuss/830700/Python-3-or-Math-(Pass)-Backtracking-(TLE)-or-Explanation", "python_solutions": "class Solution:\n def numWays(self, s: str) -> int:\n total = s.count('1')\n if total % 3: return 0\n n = len(s)\n if not total: return (1+n-2) * (n-2) // 2 % 1000000007\n avg, ans = total // 3, 0\n cnt = first_part_right_zeros = last_part_left_zeros = 0\n for i in range(n):\n if s[i] == '1': cnt += 1\n elif cnt == avg: first_part_right_zeros += 1\n elif cnt > avg: break \n cnt = 0\n for i in range(n-1, -1, -1):\n if s[i] == '1': cnt += 1\n elif cnt == avg: last_part_left_zeros += 1\n elif cnt > avg: break \n return (first_part_right_zeros+1) * (last_part_left_zeros+1) % 1000000007", "slug": "number-of-ways-to-split-a-string", "post_title": "Python 3 | Math (Pass), Backtracking (TLE) | Explanation", "user": "idontknoooo", "upvotes": 2, "views": 215, "problem_title": "number of ways to split a string", "number": 1573, "acceptance": 0.325, "difficulty": "Medium", "__index_level_0__": 23188, "question": "Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.\nReturn the number of ways s can be split such that the number of ones is the same in s1, s2, and s3. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: s = \"10101\"\nOutput: 4\nExplanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n\"1|010|1\"\n\"1|01|01\"\n\"10|10|1\"\n\"10|1|01\"\nExample 2:\nInput: s = \"1001\"\nOutput: 0\nExample 3:\nInput: s = \"0000\"\nOutput: 3\nExplanation: There are three ways to split s in 3 parts.\n\"0|0|00\"\n\"0|00|0\"\n\"00|0|0\"\n Constraints:\n3 <= s.length <= 105\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/shortest-subarray-to-be-removed-to-make-array-sorted/discuss/835866/Python-Solution-Based-on-Binary-Search", "python_solutions": "class Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n \n def lowerbound(left, right, target):\n while left < right:\n mid = left + (right - left) // 2\n \n if arr[mid] == target:\n right = mid\n elif arr[mid] < target:\n left = mid + 1\n else:\n right = mid\n \n return left\n \n \n N = len(arr)\n \n # find the longest ascending array on the left side\n i = 0\n while i + 1 < N and arr[i] <= arr[i+1]:\n i += 1\n \n if i == N - 1:\n # it is already in ascending order\n return 0\n \n # find the longest ascending array on the right side\n j = N - 1\n while j - 1 >= 0 and arr[j] >= arr[j-1]:\n j -= 1\n \n if j == 0:\n # the entire array is in decending order\n return N - 1\n \n # keep ascending array on right side or left side\n result = min(N - (N - j), N - i -1)\n \n \n # find the shortest unordered subarray in the middle \n for k in range(i+1):\n l = lowerbound(j, len(arr), arr[k])\n result = min(result, l - (k + 1))\n \n \n return result", "slug": "shortest-subarray-to-be-removed-to-make-array-sorted", "post_title": "Python Solution Based on Binary Search", "user": "pochy", "upvotes": 4, "views": 694, "problem_title": "shortest subarray to be removed to make array sorted", "number": 1574, "acceptance": 0.366, "difficulty": "Medium", "__index_level_0__": 23195, "question": "Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.\nReturn the length of the shortest subarray to remove.\nA subarray is a contiguous subsequence of the array.\n Example 1:\nInput: arr = [1,2,3,10,4,2,3,5]\nOutput: 3\nExplanation: The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.\nAnother correct solution is to remove the subarray [3,10,4].\nExample 2:\nInput: arr = [5,4,3,2,1]\nOutput: 4\nExplanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].\nExample 3:\nInput: arr = [1,2,3]\nOutput: 0\nExplanation: The array is already non-decreasing. We do not need to remove any elements.\n Constraints:\n1 <= arr.length <= 105\n0 <= arr[i] <= 109" }, { "post_href": "https://leetcode.com/problems/count-all-possible-routes/discuss/831260/Python3-top-down-dp", "python_solutions": "class Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n \n @lru_cache(None)\n def fn(n, x): \n \"\"\"Return all possible routes from n to finish with x fuel.\"\"\"\n if x < 0: return 0 # not going anywhere without fuel \n ans = 0\n if n == finish: ans += 1\n for nn in range(len(locations)): \n if nn != n: ans += fn(nn, x-abs(locations[n] - locations[nn]))\n return ans \n \n return fn(start, fuel) % 1_000_000_007", "slug": "count-all-possible-routes", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 3, "views": 169, "problem_title": "count all possible routes", "number": 1575, "acceptance": 0.568, "difficulty": "Hard", "__index_level_0__": 23203, "question": "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.\nAt each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.\nNotice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).\nReturn the count of all possible routes from start to finish. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\nOutput: 4\nExplanation: The following are all possible routes, each uses 5 units of fuel:\n1 -> 3\n1 -> 2 -> 3\n1 -> 4 -> 3\n1 -> 4 -> 2 -> 3\nExample 2:\nInput: locations = [4,3,1], start = 1, finish = 0, fuel = 6\nOutput: 5\nExplanation: The following are all possible routes:\n1 -> 0, used fuel = 1\n1 -> 2 -> 0, used fuel = 5\n1 -> 2 -> 1 -> 0, used fuel = 5\n1 -> 0 -> 1 -> 0, used fuel = 3\n1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5\nExample 3:\nInput: locations = [5,2,1], start = 0, finish = 2, fuel = 3\nOutput: 0\nExplanation: It is impossible to get from 0 to 2 using only 3 units of fuel since the shortest route needs 4 units of fuel.\n Constraints:\n2 <= locations.length <= 100\n1 <= locations[i] <= 109\nAll integers in locations are distinct.\n0 <= start, finish < locations.length\n1 <= fuel <= 200" }, { "post_href": "https://leetcode.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters/discuss/831516/Python3-one-of-three-letters", "python_solutions": "class Solution:\n def modifyString(self, s: str) -> str:\n s = list(s)\n for i in range(len(s)):\n if s[i] == \"?\": \n for c in \"abc\": \n if (i == 0 or s[i-1] != c) and (i+1 == len(s) or s[i+1] != c): \n s[i] = c\n break \n return \"\".join(s)", "slug": "replace-all-s-to-avoid-consecutive-repeating-characters", "post_title": "[Python3] one of three letters", "user": "ye15", "upvotes": 66, "views": 3100, "problem_title": "replace all s to avoid consecutive repeating characters", "number": 1576, "acceptance": 0.491, "difficulty": "Easy", "__index_level_0__": 23205, "question": "Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.\nIt is guaranteed that there are no consecutive repeating characters in the given string except for '?'.\nReturn the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.\n Example 1:\nInput: s = \"?zs\"\nOutput: \"azs\"\nExplanation: There are 25 solutions for this problem. From \"azs\" to \"yzs\", all are valid. Only \"z\" is an invalid modification as the string will consist of consecutive repeating characters in \"zzs\".\nExample 2:\nInput: s = \"ubv?w\"\nOutput: \"ubvaw\"\nExplanation: There are 24 solutions for this problem. Only \"v\" and \"w\" are invalid modifications as the strings will consist of consecutive repeating characters in \"ubvvw\" and \"ubvww\".\n Constraints:\n1 <= s.length <= 100\ns consist of lowercase English letters and '?'." }, { "post_href": "https://leetcode.com/problems/number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers/discuss/1658113/Python-intuitive-hashmap-solution-O(n*m)-time", "python_solutions": "class Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n sqr1, sqr2 = defaultdict(int), defaultdict(int)\n m, n = len(nums1), len(nums2)\n for i in range(m):\n sqr1[nums1[i]**2] += 1\n for j in range(n):\n sqr2[nums2[j]**2] += 1\n \n res = 0 \n for i in range(m-1):\n for j in range(i+1, m):\n if nums1[i]*nums1[j] in sqr2:\n res += sqr2[nums1[i]*nums1[j]]\n \n for i in range(n-1):\n for j in range(i+1, n):\n if nums2[i]*nums2[j] in sqr1:\n res += sqr1[nums2[i]*nums2[j]]\n return res", "slug": "number-of-ways-where-square-of-number-is-equal-to-product-of-two-numbers", "post_title": "Python intuitive hashmap solution, O(n*m) time", "user": "byuns9334", "upvotes": 2, "views": 114, "problem_title": "number of ways where square of number is equal to product of two numbers", "number": 1577, "acceptance": 0.4, "difficulty": "Medium", "__index_level_0__": 23219, "question": "Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:\nType 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.\nType 2: Triplet (i, j, k) if nums2[i]2 == nums1[j] * nums1[k] where 0 <= i < nums2.length and 0 <= j < k < nums1.length.\n Example 1:\nInput: nums1 = [7,4], nums2 = [5,2,8,9]\nOutput: 1\nExplanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8). \nExample 2:\nInput: nums1 = [1,1], nums2 = [1,1,1]\nOutput: 9\nExplanation: All Triplets are valid, because 12 = 1 * 1.\nType 1: (0,0,1), (0,0,2), (0,1,2), (1,0,1), (1,0,2), (1,1,2). nums1[i]2 = nums2[j] * nums2[k].\nType 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].\nExample 3:\nInput: nums1 = [7,7,8,3], nums2 = [1,2,9,7]\nOutput: 2\nExplanation: There are 2 valid triplets.\nType 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].\nType 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].\n Constraints:\n1 <= nums1.length, nums2.length <= 1000\n1 <= nums1[i], nums2[i] <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-time-to-make-rope-colorful/discuss/831500/Python3-greedy", "python_solutions": "class Solution:\n def minCost(self, s: str, cost: List[int]) -> int:\n ans = prev = 0 # index of previously retained letter \n for i in range(1, len(s)): \n if s[prev] != s[i]: prev = i\n else: \n ans += min(cost[prev], cost[i])\n if cost[prev] < cost[i]: prev = i\n return ans", "slug": "minimum-time-to-make-rope-colorful", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 58, "views": 3800, "problem_title": "minimum time to make rope colorful", "number": 1578, "acceptance": 0.637, "difficulty": "Medium", "__index_level_0__": 23224, "question": "Alice has n balloons arranged on a rope. You are given a 0-indexed string colors where colors[i] is the color of the ith balloon.\nAlice wants the rope to be colorful. She does not want two consecutive balloons to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it colorful. You are given a 0-indexed integer array neededTime where neededTime[i] is the time (in seconds) that Bob needs to remove the ith balloon from the rope.\nReturn the minimum time Bob needs to make the rope colorful.\n Example 1:\nInput: colors = \"abaac\", neededTime = [1,2,3,4,5]\nOutput: 3\nExplanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.\nBob can remove the blue balloon at index 2. This takes 3 seconds.\nThere are no longer two consecutive balloons of the same color. Total time = 3.\nExample 2:\nInput: colors = \"abc\", neededTime = [1,2,3]\nOutput: 0\nExplanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.\nExample 3:\nInput: colors = \"aabaa\", neededTime = [1,2,3,4,1]\nOutput: 2\nExplanation: Bob will remove the balloons at indices 0 and 4. Each balloons takes 1 second to remove.\nThere are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.\n Constraints:\nn == colors.length == neededTime.length\n1 <= n <= 105\n1 <= neededTime[i] <= 104\ncolors contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/special-positions-in-a-binary-matrix/discuss/1802763/Python-Memory-Efficient-Solution", "python_solutions": "class Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n onesx = []\n onesy = []\n for ri, rv in enumerate(mat):\n for ci, cv in enumerate(rv):\n if cv == 1:\n onesx.append(ri)\n onesy.append(ci)\n \n count = 0\n for idx in range(len(onesx)):\n if onesx.count(onesx[idx]) == 1:\n if onesy.count(onesy[idx]) == 1:\n count += 1\n return count", "slug": "special-positions-in-a-binary-matrix", "post_title": "\ud83d\udccc Python Memory-Efficient Solution", "user": "croatoan", "upvotes": 4, "views": 129, "problem_title": "special positions in a binary matrix", "number": 1582, "acceptance": 0.654, "difficulty": "Easy", "__index_level_0__": 23278, "question": "Given an m x n binary matrix mat, return the number of special positions in mat.\nA position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).\n Example 1:\nInput: mat = [[1,0,0],[0,0,1],[1,0,0]]\nOutput: 1\nExplanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.\nExample 2:\nInput: mat = [[1,0,0],[0,1,0],[0,0,1]]\nOutput: 3\nExplanation: (0, 0), (1, 1) and (2, 2) are special positions.\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 100\nmat[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/count-unhappy-friends/discuss/1103620/Readable-python-solution", "python_solutions": "class Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n\n def find_preferred_friends(x: int) -> List[int]:\n \"\"\"\n Returns friends of x that have a higher preference than partner.\n \"\"\"\n\t\t\tpartner = partners[x] # Find the partner of x.\n x_friends = friend_prefs[x] # Find all the friends of x.\n partner_ranking = x_friends[partner] # Get the partner's ranking amongst those friends.\n return list(x_friends)[:partner_ranking] # Return all friends with a preferred lower ranking.\n\n def is_unhappy(x: int) -> bool:\n \"\"\"\n Returns True if person x is unhappy, otherwise False.\n \"\"\"\n # Find the partner for person x.\n partner = partners[x] \n # Find the friends that person x prefers more than this partner.\n preferred_friends = find_preferred_friends(x) \n # A friend is unhappy with their partner if there is another friend with a higher preference \n # and that friend prefers them over their partner.\n return any(friend_prefs[friend][x] <= friend_prefs[friend][partners[friend]] \n for friend in preferred_friends)\n\n # Create dictionary to lookup friend preference for any person.\n friend_prefs = {\n person: {friend: pref for pref, friend in enumerate(friends)}\n for person, friends in enumerate(preferences)\n }\n\t\t# Example:\n\t\t# {0: {1: 0, 3: 1, 2: 2},\n\t # 1: {2: 0, 3: 1, 0: 2},\n\t # 2: {1: 0, 3: 1, 0: 2},\n\t # 3: {0: 0, 2: 1, 1: 2}}\n \n # Create dictionary to find anyone's partner.\n partners = {}\n for x, y in pairs:\n partners[x] = y\n partners[y] = x\n \n\t\t# Count and return the number of unhappy people.\n return sum(is_unhappy(person) for person in range(n))", "slug": "count-unhappy-friends", "post_title": "Readable python solution", "user": "alexanco", "upvotes": 3, "views": 325, "problem_title": "count unhappy friends", "number": 1583, "acceptance": 0.603, "difficulty": "Medium", "__index_level_0__": 23299, "question": "You are given a list of preferences for n friends, where n is always even.\nFor each person i, preferences[i] contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from 0 to n-1.\nAll the friends are divided into pairs. The pairings are given in a list pairs, where pairs[i] = [xi, yi] denotes xi is paired with yi and yi is paired with xi.\nHowever, this pairing may cause some of the friends to be unhappy. A friend x is unhappy if x is paired with y and there exists a friend u who is paired with v but:\nx prefers u over y, and\nu prefers x over v.\nReturn the number of unhappy friends.\n Example 1:\nInput: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\nOutput: 2\nExplanation:\nFriend 1 is unhappy because:\n- 1 is paired with 0 but prefers 3 over 0, and\n- 3 prefers 1 over 2.\nFriend 3 is unhappy because:\n- 3 is paired with 2 but prefers 1 over 2, and\n- 1 prefers 3 over 0.\nFriends 0 and 2 are happy.\nExample 2:\nInput: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\nOutput: 0\nExplanation: Both friends 0 and 1 are happy.\nExample 3:\nInput: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\nOutput: 4\n Constraints:\n2 <= n <= 500\nn is even.\npreferences.length == n\npreferences[i].length == n - 1\n0 <= preferences[i][j] <= n - 1\npreferences[i] does not contain i.\nAll values in preferences[i] are unique.\npairs.length == n/2\npairs[i].length == 2\nxi != yi\n0 <= xi, yi <= n - 1\nEach person is contained in exactly one pair." }, { "post_href": "https://leetcode.com/problems/min-cost-to-connect-all-points/discuss/843995/Python-3-or-Min-Spanning-Tree-or-Prim's-Algorithm", "python_solutions": "class Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n manhattan = lambda p1, p2: abs(p1[0]-p2[0]) + abs(p1[1]-p2[1])\n n, c = len(points), collections.defaultdict(list)\n for i in range(n):\n for j in range(i+1, n):\n d = manhattan(points[i], points[j])\n c[i].append((d, j))\n c[j].append((d, i))\n cnt, ans, visited, heap = 1, 0, [0] * n, c[0]\n visited[0] = 1\n heapq.heapify(heap)\n while heap:\n d, j = heapq.heappop(heap)\n if not visited[j]:\n visited[j], cnt, ans = 1, cnt+1, ans+d\n for record in c[j]: heapq.heappush(heap, record)\n if cnt >= n: break \n return ans", "slug": "min-cost-to-connect-all-points", "post_title": "Python 3 | Min Spanning Tree | Prim's Algorithm", "user": "idontknoooo", "upvotes": 80, "views": 13100, "problem_title": "min cost to connect all points", "number": 1584, "acceptance": 0.6409999999999999, "difficulty": "Medium", "__index_level_0__": 23308, "question": "You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].\nThe cost of connecting two points [xi, yi] and [xj, yj] is the manhattan distance between them: |xi - xj| + |yi - yj|, where |val| denotes the absolute value of val.\nReturn the minimum cost to make all points connected. All points are connected if there is exactly one simple path between any two points.\n Example 1:\nInput: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\nOutput: 20\nExplanation: \nWe can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.\nExample 2:\nInput: points = [[3,12],[-2,5],[-4,1]]\nOutput: 18\n Constraints:\n1 <= points.length <= 1000\n-106 <= xi, yi <= 106\nAll pairs (xi, yi) are distinct." }, { "post_href": "https://leetcode.com/problems/check-if-string-is-transformable-with-substring-sort-operations/discuss/844119/Python3-8-line-deque", "python_solutions": "class Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n if sorted(s) != sorted(t): return False # edge case \n \n pos = [deque() for _ in range(10)]\n for i, ss in enumerate(s): pos[int(ss)].append(i)\n \n for tt in t: \n i = pos[int(tt)].popleft()\n for ii in range(int(tt)): \n if pos[ii] and pos[ii][0] < i: return False # cannot swap \n return True", "slug": "check-if-string-is-transformable-with-substring-sort-operations", "post_title": "[Python3] 8-line deque", "user": "ye15", "upvotes": 2, "views": 198, "problem_title": "check if string is transformable with substring sort operations", "number": 1585, "acceptance": 0.484, "difficulty": "Hard", "__index_level_0__": 23325, "question": "Given two strings s and t, transform string s into string t using the following operation any number of times:\nChoose a non-empty substring in s and sort it in place so the characters are in ascending order.\nFor example, applying the operation on the underlined substring in \"14234\" results in \"12344\".\nReturn true if it is possible to transform s into t. Otherwise, return false.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: s = \"84532\", t = \"34852\"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n\"84532\" (from index 2 to 3) -> \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"\nExample 2:\nInput: s = \"34521\", t = \"23415\"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"\nExample 3:\nInput: s = \"12345\", t = \"12435\"\nOutput: false\n Constraints:\ns.length == t.length\n1 <= s.length <= 105\ns and t consist of only digits." }, { "post_href": "https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/943380/Python-Simple-Solution", "python_solutions": "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n s=0\n for i in range(len(arr)):\n for j in range(i,len(arr),2):\n s+=sum(arr[i:j+1])\n return s", "slug": "sum-of-all-odd-length-subarrays", "post_title": "Python Simple Solution", "user": "lokeshsenthilkumar", "upvotes": 53, "views": 4100, "problem_title": "sum of all odd length subarrays", "number": 1588, "acceptance": 0.835, "difficulty": "Easy", "__index_level_0__": 23326, "question": "Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.\nA subarray is a contiguous subsequence of the array.\n Example 1:\nInput: arr = [1,4,2,5,3]\nOutput: 58\nExplanation: The odd-length subarrays of arr and their sums are:\n[1] = 1\n[4] = 4\n[2] = 2\n[5] = 5\n[3] = 3\n[1,4,2] = 7\n[4,2,5] = 11\n[2,5,3] = 10\n[1,4,2,5,3] = 15\nIf we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\nExample 2:\nInput: arr = [1,2]\nOutput: 3\nExplanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\nExample 3:\nInput: arr = [10,11,12]\nOutput: 66\n Constraints:\n1 <= arr.length <= 100\n1 <= arr[i] <= 1000\n Follow up:\nCould you solve this problem in O(n) time complexity?" }, { "post_href": "https://leetcode.com/problems/maximum-sum-obtained-of-any-permutation/discuss/858448/Python3-mark-and-sweep", "python_solutions": "class Solution:\n def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n chg = [0]*len(nums) # change \n for i, j in requests: \n chg[i] += 1\n if j+1 < len(nums): chg[j+1] -= 1\n for i in range(1, len(nums)): chg[i] += chg[i-1] # cumulated change\n return sum(n*c for n, c in zip(sorted(nums), sorted(chg))) % 1_000_000_007", "slug": "maximum-sum-obtained-of-any-permutation", "post_title": "[Python3] mark & sweep", "user": "ye15", "upvotes": 0, "views": 39, "problem_title": "maximum sum obtained of any permutation", "number": 1589, "acceptance": 0.37, "difficulty": "Medium", "__index_level_0__": 23377, "question": "We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.\nReturn the maximum total sum of all requests among all permutations of nums.\nSince the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\nOutput: 19\nExplanation: One permutation of nums is [2,1,3,4,5] with the following result: \nrequests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\nrequests[1] -> nums[0] + nums[1] = 2 + 1 = 3\nTotal sum: 8 + 3 = 11.\nA permutation with a higher total sum is [3,5,4,2,1] with the following result:\nrequests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\nrequests[1] -> nums[0] + nums[1] = 3 + 5 = 8\nTotal sum: 11 + 8 = 19, which is the best that you can do.\nExample 2:\nInput: nums = [1,2,3,4,5,6], requests = [[0,1]]\nOutput: 11\nExplanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].\nExample 3:\nInput: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\nOutput: 47\nExplanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].\n Constraints:\nn == nums.length\n1 <= n <= 105\n0 <= nums[i] <= 105\n1 <= requests.length <= 105\nrequests[i].length == 2\n0 <= starti <= endi < n" }, { "post_href": "https://leetcode.com/problems/make-sum-divisible-by-p/discuss/1760163/WEEB-DOES-PYTHONC%2B%2B", "python_solutions": "class Solution:\ndef minSubarray(self, nums: List[int], p: int) -> int:\n dp = defaultdict(int)\n dp[0] = -1\n target = sum(nums) % p\n curSum = 0\n result = len(nums)\n \n if sum(nums) % p == 0: return 0\n \n for i in range(len(nums)):\n curSum += nums[i]\n \n curMod = curSum % p\n \n temp = (curSum - target) % p\n \n if temp in dp:\n if i - dp[temp] < result:\n result = i - dp[temp]\n \n dp[curMod] = i\n \n return result if result < len(nums) else -1", "slug": "make-sum-divisible-by-p", "post_title": "WEEB DOES PYTHON/C++", "user": "Skywalker5423", "upvotes": 2, "views": 153, "problem_title": "make sum divisible by p", "number": 1590, "acceptance": 0.28, "difficulty": "Medium", "__index_level_0__": 23378, "question": "Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array.\nReturn the length of the smallest subarray that you need to remove, or -1 if it's impossible.\nA subarray is defined as a contiguous block of elements in the array.\n Example 1:\nInput: nums = [3,1,4,2], p = 6\nOutput: 1\nExplanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.\nExample 2:\nInput: nums = [6,3,5,2], p = 9\nOutput: 2\nExplanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.\nExample 3:\nInput: nums = [1,2,3], p = 3\nOutput: 0\nExplanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109\n1 <= p <= 109" }, { "post_href": "https://leetcode.com/problems/strange-printer-ii/discuss/911370/Same-as-CourseSchedule-Topological-sort.", "python_solutions": "class Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n visited = [0] * 61\n graph = collections.defaultdict(set)\n m, n = len(targetGrid), len(targetGrid[0])\n for c in range(1, 61):\n l,r,t,b = n,-1,m,-1\n\t\t\t#to specify the covered range of color c\n for i in range(m):\n for j in range(n):\n if targetGrid[i][j] == c:\n l = min(l, j)\n r = max(r, j)\n t = min(t, i)\n b = max(b, i)\n\t\t\t#to find the contained colors\n for i in range(t, b + 1):\n for j in range(l, r + 1):\n if targetGrid[i][j] != c:\n graph[targetGrid[i][j]].add(c)\n \n\t\t# to find if there is a cycle \n def dfs(graph,i):\n if visited[i] == -1:\n return False\n if visited[i] == 1:\n return True \n visited[i] = -1\n for j in graph[i]:\n if not dfs(graph,j):\n return False\n visited[i] = 1\n return True\n \n for c in range(61):\n if not dfs(graph,c):\n return False\n return True", "slug": "strange-printer-ii", "post_title": "Same as CourseSchedule, Topological sort.", "user": "Sakata_Gintoki", "upvotes": 17, "views": 810, "problem_title": "strange printer ii", "number": 1591, "acceptance": 0.584, "difficulty": "Hard", "__index_level_0__": 23382, "question": "There is a strange printer with the following two special requirements:\nOn 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.\nOnce the printer has used a color for the above operation, the same color cannot be used again.\nYou are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.\nReturn true if it is possible to print the matrix targetGrid, otherwise, return false.\n Example 1:\nInput: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\nOutput: true\nExample 2:\nInput: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\nOutput: true\nExample 3:\nInput: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\nOutput: false\nExplanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.\n Constraints:\nm == targetGrid.length\nn == targetGrid[i].length\n1 <= m, n <= 60\n1 <= targetGrid[row][col] <= 60" }, { "post_href": "https://leetcode.com/problems/rearrange-spaces-between-words/discuss/1834393/Python-simple-and-elegant", "python_solutions": "class Solution(object):\n def reorderSpaces(self, text):\n word_list = text.split()\n words, spaces = len(word_list), text.count(\" \")\n \n if words > 1:\n q, r = spaces//(words-1), spaces%(words-1)\n return (\" \" * q).join(word_list) + \" \" * r\n else:\n return \"\".join(word_list) + \" \" * spaces", "slug": "rearrange-spaces-between-words", "post_title": "Python - simple and elegant", "user": "domthedeveloper", "upvotes": 3, "views": 176, "problem_title": "rearrange spaces between words", "number": 1592, "acceptance": 0.437, "difficulty": "Easy", "__index_level_0__": 23384, "question": "You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.\nRearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.\nReturn the string after rearranging the spaces.\n Example 1:\nInput: text = \" this is a sentence \"\nOutput: \"this is a sentence\"\nExplanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.\nExample 2:\nInput: text = \" practice makes perfect\"\nOutput: \"practice makes perfect \"\nExplanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.\n Constraints:\n1 <= text.length <= 100\ntext consists of lowercase English letters and ' '.\ntext contains at least one word." }, { "post_href": "https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/discuss/855405/Python-3-or-Backtracking-DFS-clean-or-Explanations", "python_solutions": "class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n ans, n = 0, len(s)\n def dfs(i, cnt, visited):\n nonlocal ans, n\n if i == n: ans = max(ans, cnt); return # stop condition\n for j in range(i+1, n+1): \n if s[i:j] in visited: continue # avoid re-visit/duplicates\n visited.add(s[i:j]) # update visited set\n dfs(j, cnt+1, visited) # backtracking\n visited.remove(s[i:j]) # recover visited set for next possibility\n dfs(0, 0, set()) # function call\n return ans", "slug": "split-a-string-into-the-max-number-of-unique-substrings", "post_title": "Python 3 | Backtracking, DFS, clean | Explanations", "user": "idontknoooo", "upvotes": 5, "views": 849, "problem_title": "split a string into the max number of unique substrings", "number": 1593, "acceptance": 0.55, "difficulty": "Medium", "__index_level_0__": 23407, "question": "Given a string s, return the maximum number of unique substrings that the given string can be split into.\nYou can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: s = \"ababccc\"\nOutput: 5\nExplanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.\nExample 2:\nInput: s = \"aba\"\nOutput: 2\nExplanation: One way to split maximally is ['a', 'ba'].\nExample 3:\nInput: s = \"aa\"\nOutput: 1\nExplanation: It is impossible to split the string any further.\n Constraints:\n1 <= s.length <= 16\ns contains only lower case English letters." }, { "post_href": "https://leetcode.com/problems/maximum-non-negative-product-in-a-matrix/discuss/855131/Python3-top-down-dp", "python_solutions": "class Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n \n @lru_cache(None)\n def fn(i, j): \n \"\"\"Return maximum & minimum products ending at (i, j).\"\"\"\n if i == 0 and j == 0: return grid[0][0], grid[0][0]\n if i < 0 or j < 0: return -inf, inf\n if grid[i][j] == 0: return 0, 0\n mx1, mn1 = fn(i-1, j) # from top\n mx2, mn2 = fn(i, j-1) # from left \n mx, mn = max(mx1, mx2)*grid[i][j], min(mn1, mn2)*grid[i][j]\n return (mx, mn) if grid[i][j] > 0 else (mn, mx)\n \n mx, _ = fn(m-1, n-1)\n return -1 if mx < 0 else mx % 1_000_000_007", "slug": "maximum-non-negative-product-in-a-matrix", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 36, "views": 1800, "problem_title": "maximum non negative product in a matrix", "number": 1594, "acceptance": 0.33, "difficulty": "Medium", "__index_level_0__": 23418, "question": "You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.\nAmong all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.\nReturn the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.\nNotice that the modulo is performed after getting the maximum product.\n Example 1:\nInput: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\nOutput: -1\nExplanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.\nExample 2:\nInput: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\nOutput: 8\nExplanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).\nExample 3:\nInput: grid = [[1,3],[0,-4]]\nOutput: 0\nExplanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 15\n-4 <= grid[i][j] <= 4" }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/858187/Python3-top-down-dp", "python_solutions": "class Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n m, n = len(cost), len(cost[0])\n mn = [min(x) for x in zip(*cost)] # min cost of connecting points in 2nd group \n \n @lru_cache(None)\n def fn(i, mask):\n \"\"\"Return min cost of connecting group1[i:] and group2 represented as mask.\"\"\"\n if i == m: return sum(mn[j] for j in range(n) if not (mask & (1<= size2.\nThe cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.\nReturn the minimum cost it takes to connect the two groups.\n Example 1:\nInput: cost = [[15, 96], [36, 2]]\nOutput: 17\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\nThis results in a total cost of 17.\nExample 2:\nInput: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\nOutput: 4\nExplanation: The optimal way of connecting the groups is:\n1--A\n2--B\n2--C\n3--A\nThis results in a total cost of 4.\nNote that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.\nExample 3:\nInput: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\nOutput: 10\n Constraints:\nsize1 == cost.length\nsize2 == cost[i].length\n1 <= size1, size2 <= 12\nsize1 >= size2\n0 <= cost[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/crawler-log-folder/discuss/866343/Python3-straightforward", "python_solutions": "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n ans = 0\n for log in logs: \n if log == \"./\": continue\n elif log == \"../\": ans = max(0, ans-1) # parent directory\n else: ans += 1 # child directory \n return ans", "slug": "crawler-log-folder", "post_title": "[Python3] straightforward", "user": "ye15", "upvotes": 11, "views": 627, "problem_title": "crawler log folder", "number": 1598, "acceptance": 0.644, "difficulty": "Easy", "__index_level_0__": 23431, "question": "The Leetcode file system keeps a log each time some user performs a change folder operation.\nThe operations are described below:\n\"../\" : Move to the parent folder of the current folder. (If you are already in the main folder, remain in the same folder).\n\"./\" : Remain in the same folder.\n\"x/\" : Move to the child folder named x (This folder is guaranteed to always exist).\nYou are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.\nThe file system starts in the main folder, then the operations in logs are performed.\nReturn the minimum number of operations needed to go back to the main folder after the change folder operations.\n Example 1:\nInput: logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]\nOutput: 2\nExplanation: Use this change folder operation \"../\" 2 times and go back to the main folder.\nExample 2:\nInput: logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]\nOutput: 3\nExample 3:\nInput: logs = [\"d1/\",\"../\",\"../\",\"../\"]\nOutput: 0\n Constraints:\n1 <= logs.length <= 103\n2 <= logs[i].length <= 10\nlogs[i] contains lowercase English letters, digits, '.', and '/'.\nlogs[i] follows the format described in the statement.\nFolder names consist of lowercase English letters and digits." }, { "post_href": "https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/discuss/866356/Python3-simulation", "python_solutions": "class Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n ans = -1\n most = pnl = waiting = 0\n for i, x in enumerate(customers): \n waiting += x # more people waiting in line \n waiting -= (chg := min(4, waiting)) # boarding \n pnl += chg * boardingCost - runningCost \n if most < pnl: ans, most = i+1, pnl\n q, r = divmod(waiting, 4)\n if 4*boardingCost > runningCost: ans += q\n if r*boardingCost > runningCost: ans += 1\n return ans", "slug": "maximum-profit-of-operating-a-centennial-wheel", "post_title": "[Python3] simulation", "user": "ye15", "upvotes": 5, "views": 381, "problem_title": "maximum profit of operating a centennial wheel", "number": 1599, "acceptance": 0.436, "difficulty": "Medium", "__index_level_0__": 23460, "question": "You are the operator of a Centennial Wheel that has four gondolas, and each gondola has room for up to four people. You have the ability to rotate the gondolas counterclockwise, which costs you runningCost dollars.\nYou are given an array customers of length n where customers[i] is the number of new customers arriving just before the ith rotation (0-indexed). This means you must rotate the wheel i times before the customers[i] customers arrive. You cannot make customers wait if there is room in the gondola. Each customer pays boardingCost dollars when they board on the gondola closest to the ground and will exit once that gondola reaches the ground again.\nYou can stop the wheel at any time, including before serving all customers. If you decide to stop serving customers, all subsequent rotations are free in order to get all the customers down safely. Note that if there are currently more than four customers waiting at the wheel, only four will board the gondola, and the rest will wait for the next rotation.\nReturn the minimum number of rotations you need to perform to maximize your profit. If there is no scenario where the profit is positive, return -1.\n Example 1:\nInput: customers = [8,3], boardingCost = 5, runningCost = 6\nOutput: 3\nExplanation: The numbers written on the gondolas are the number of people currently there.\n1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n2. 3 customers arrive, the 4 waiting board the wheel and the other 3 wait, the wheel rotates. Current profit is 8 * $5 - 2 * $6 = $28.\n3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\nThe highest profit was $37 after rotating the wheel 3 times.\nExample 2:\nInput: customers = [10,9,6], boardingCost = 6, runningCost = 4\nOutput: 7\nExplanation:\n1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n2. 9 customers arrive, 4 board and 11 wait (2 originally waiting, 9 newly waiting), the wheel rotates. Current profit is 8 * $6 - 2 * $4 = $40.\n3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\nThe highest profit was $122 after rotating the wheel 7 times.\nExample 3:\nInput: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92\nOutput: -1\nExplanation:\n1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\nThe profit was never positive, so return -1.\n Constraints:\nn == customers.length\n1 <= n <= 105\n0 <= customers[i] <= 50\n1 <= boardingCost, runningCost <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866369/Python3-10-Lines-Bitmasking-or-Combinations-or-Easy-Explanation", "python_solutions": "class Solution:\n def maximumRequests(self, n: int, req: List[List[int]]) -> int:\n tot = len(req)\n for i in range(tot, 0, -1):\n comb = list(itertools.combinations([j for j in range(tot)], i))\n for c in comb:\n net = [0 for j in range(n)]\n for idx in c:\n net[req[idx][0]] -= 1\n net[req[idx][1]] += 1\n if net == [0 for j in range(n)]:\n return i\n return 0", "slug": "maximum-number-of-achievable-transfer-requests", "post_title": "[Python3] 10 Lines Bitmasking | Combinations | Easy Explanation", "user": "uds5501", "upvotes": 17, "views": 1000, "problem_title": "maximum number of achievable transfer requests", "number": 1601, "acceptance": 0.513, "difficulty": "Hard", "__index_level_0__": 23463, "question": "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.\nYou are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.\nAll buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.\nReturn the maximum number of achievable requests.\n Example 1:\nInput: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\nOutput: 5\nExplantion: Let's see the requests:\nFrom building 0 we have employees x and y and both want to move to building 1.\nFrom building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\nFrom building 2 we have employee z and they want to move to building 0.\nFrom building 3 we have employee c and they want to move to building 4.\nFrom building 4 we don't have any requests.\nWe can achieve the requests of users x and b by swapping their places.\nWe can achieve the requests of users y, a and z by swapping the places in the 3 buildings.\nExample 2:\nInput: n = 3, requests = [[0,0],[1,2],[2,1]]\nOutput: 3\nExplantion: Let's see the requests:\nFrom building 0 we have employee x and they want to stay in the same building 0.\nFrom building 1 we have employee y and they want to move to building 2.\nFrom building 2 we have employee z and they want to move to building 1.\nWe can achieve all the requests. \nExample 3:\nInput: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\nOutput: 4\n Constraints:\n1 <= n <= 20\n1 <= requests.length <= 16\nrequests[i].length == 2\n0 <= fromi, toi < n" }, { "post_href": "https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/discuss/1284866/Python3-or-Dict-%2B-Sort", "python_solutions": "class Solution:\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n key_time = {}\n for index, name in enumerate(keyName):\n key_time[name] = key_time.get(name, [])\n key_time[name].append(int(keyTime[index].replace(\":\", \"\")))\n ans = []\n for name, time_list in key_time.items():\n time_list.sort()\n n = len(time_list)\n for i in range(n-2):\n if time_list[i+2] - time_list[i] <= 100:\n ans.append(name)\n break\n return sorted(ans)", "slug": "alert-using-same-key-card-three-or-more-times-in-a-one-hour-period", "post_title": "Python3 | Dict + Sort", "user": "Sanjaychandak95", "upvotes": 3, "views": 314, "problem_title": "alert using same key card three or more times in a one hour period", "number": 1604, "acceptance": 0.473, "difficulty": "Medium", "__index_level_0__": 23465, "question": "LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period.\nYou are given a list of strings keyName and keyTime where [keyName[i], keyTime[i]] corresponds to a person's name and the time when their key-card was used in a single day.\nAccess times are given in the 24-hour time format \"HH:MM\", such as \"23:51\" and \"09:49\".\nReturn a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.\nNotice that \"10:00\" - \"11:00\" is considered to be within a one-hour period, while \"22:51\" - \"23:52\" is not considered to be within a one-hour period.\n Example 1:\nInput: keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]\nOutput: [\"daniel\"]\nExplanation: \"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").\nExample 2:\nInput: keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]\nOutput: [\"bob\"]\nExplanation: \"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").\n Constraints:\n1 <= keyName.length, keyTime.length <= 105\nkeyName.length == keyTime.length\nkeyTime[i] is in the format \"HH:MM\".\n[keyName[i], keyTime[i]] is unique.\n1 <= keyName[i].length <= 10\nkeyName[i] contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/discuss/1734833/Python-or-Backtracking", "python_solutions": "class Solution:\n def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n def backtrack(y, x):\n choice = min(rowSum[y], colSum[x])\n result[y][x] = choice\n rowSum[y] -= choice\n colSum[x] -= choice\n if y == 0 and x == 0:\n return\n\n elif not rowSum[y]:\n backtrack(y - 1, x)\n elif not colSum[x]:\n backtrack(y, x - 1)\n\n Y, X = len(rowSum), len(colSum)\n result = [[0 for _ in range(X)] for _ in range(Y)]\n backtrack(Y-1, X-1)\n return result", "slug": "find-valid-matrix-given-row-and-column-sums", "post_title": "Python | Backtracking", "user": "holdenkold", "upvotes": 1, "views": 102, "problem_title": "find valid matrix given row and column sums", "number": 1605, "acceptance": 0.78, "difficulty": "Medium", "__index_level_0__": 23473, "question": "You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.\nFind any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.\nReturn a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.\n Example 1:\nInput: rowSum = [3,8], colSum = [4,7]\nOutput: [[3,0],\n [1,7]]\nExplanation: \n0th row: 3 + 0 = 3 == rowSum[0]\n1st row: 1 + 7 = 8 == rowSum[1]\n0th column: 3 + 1 = 4 == colSum[0]\n1st column: 0 + 7 = 7 == colSum[1]\nThe row and column sums match, and all matrix elements are non-negative.\nAnother possible matrix is: [[1,2],\n [3,5]]\nExample 2:\nInput: rowSum = [5,7,10], colSum = [8,6,8]\nOutput: [[0,5,0],\n [6,1,0],\n [2,0,8]]\n Constraints:\n1 <= rowSum.length, colSum.length <= 500\n0 <= rowSum[i], colSum[i] <= 108\nsum(rowSum) == sum(colSum)" }, { "post_href": "https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/discuss/1089184/Python3-summarizing-3-approaches", "python_solutions": "class Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n busy = [] # min-heap\n free = list(range(k)) # min-heap \n freq = [0]*k\n \n for i, (ta, tl) in enumerate(zip(arrival, load)): \n while busy and busy[0][0] <= ta: \n _, ii = heappop(busy)\n heappush(free, i + (ii - i) % k) # circularly relocate it\n if free: \n ii = heappop(free) % k \n freq[ii] += 1\n heappush(busy, (ta+tl, ii))\n \n mx = max(freq)\n return [i for i, x in enumerate(freq) if x == mx]", "slug": "find-servers-that-handled-most-number-of-requests", "post_title": "[Python3] summarizing 3 approaches", "user": "ye15", "upvotes": 13, "views": 641, "problem_title": "find servers that handled most number of requests", "number": 1606, "acceptance": 0.429, "difficulty": "Hard", "__index_level_0__": 23483, "question": "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:\nThe ith (0-indexed) request arrives.\nIf all servers are busy, the request is dropped (not handled at all).\nIf the (i % k)th server is available, assign the request to that server.\nOtherwise, 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.\nYou are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.\nReturn a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.\n Example 1:\nInput: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \nOutput: [1] \nExplanation: \nAll of the servers start out available.\nThe first 3 requests are handled by the first 3 servers in order.\nRequest 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\nRequest 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\nServers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\nExample 2:\nInput: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\nOutput: [0]\nExplanation: \nThe first 3 requests are handled by first 3 servers.\nRequest 3 comes in. It is handled by server 0 since the server is available.\nServer 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\nExample 3:\nInput: k = 3, arrival = [1,2,3], load = [10,12,11]\nOutput: [0,1,2]\nExplanation: Each server handles a single request, so they are all considered the busiest.\n Constraints:\n1 <= k <= 105\n1 <= arrival.length, load.length <= 105\narrival.length == load.length\n1 <= arrival[i], load[i] <= 109\narrival is strictly increasing." }, { "post_href": "https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/discuss/1527669/Python-or-Faster-than-94-or-2-methods-or-O(nlogn)", "python_solutions": "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n\n if n<=nums[0]:\n return n\n \n for i in range(1,n):\n count = n-i #counts number of elements in nums greater than equal i\n if nums[i]>=(count) and (count)>nums[i-1]:\n return count \n return -1", "slug": "special-array-with-x-elements-greater-than-or-equal-x", "post_title": "Python | Faster than 94% | 2 methods | O(nlogn)", "user": "ana_2kacer", "upvotes": 5, "views": 531, "problem_title": "special array with x elements greater than or equal x", "number": 1608, "acceptance": 0.601, "difficulty": "Easy", "__index_level_0__": 23484, "question": "You are given an array nums of non-negative integers. nums is considered special if there exists a number x such that there are exactly x numbers in nums that are greater than or equal to x.\nNotice that x does not have to be an element in nums.\nReturn x if the array is special, otherwise, return -1. It can be proven that if nums is special, the value for x is unique.\n Example 1:\nInput: nums = [3,5]\nOutput: 2\nExplanation: There are 2 values (3 and 5) that are greater than or equal to 2.\nExample 2:\nInput: nums = [0,0]\nOutput: -1\nExplanation: No numbers fit the criteria for x.\nIf x = 0, there should be 0 numbers >= x, but there are 2.\nIf x = 1, there should be 1 number >= x, but there are 0.\nIf x = 2, there should be 2 numbers >= x, but there are 0.\nx cannot be greater since there are only 2 numbers in nums.\nExample 3:\nInput: nums = [0,4,3,0,4]\nOutput: 3\nExplanation: There are 3 values that are greater than or equal to 3.\n Constraints:\n1 <= nums.length <= 100\n0 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/even-odd-tree/discuss/877858/Python3-bfs-by-level", "python_solutions": "class Solution:\n def isEvenOddTree(self, root: TreeNode) -> bool:\n even = 1 # even level \n queue = deque([root])\n while queue: \n newq = []\n prev = -inf if even else inf\n for _ in range(len(queue)): \n node = queue.popleft()\n if even and (node.val&1 == 0 or prev >= node.val) or not even and (node.val&1 or prev <= node.val): return False \n prev = node.val \n if node.left: queue.append(node.left)\n if node.right: queue.append(node.right)\n even ^= 1\n return True", "slug": "even-odd-tree", "post_title": "[Python3] bfs by level", "user": "ye15", "upvotes": 1, "views": 103, "problem_title": "even odd tree", "number": 1609, "acceptance": 0.5379999999999999, "difficulty": "Medium", "__index_level_0__": 23519, "question": "A binary tree is named Even-Odd if it meets the following conditions:\nThe root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.\nFor every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).\nFor every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).\nGiven the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.\n Example 1:\nInput: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\nOutput: true\nExplanation: The node values on each level are:\nLevel 0: [1]\nLevel 1: [10,4]\nLevel 2: [3,7,9]\nLevel 3: [12,8,6,2]\nSince levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.\nExample 2:\nInput: root = [5,4,2,3,3,7]\nOutput: false\nExplanation: The node values on each level are:\nLevel 0: [5]\nLevel 1: [4,2]\nLevel 2: [3,3,7]\nNode values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.\nExample 3:\nInput: root = [5,9,1,3,5,7]\nOutput: false\nExplanation: Node values in the level 1 should be even integers.\n Constraints:\nThe number of nodes in the tree is in the range [1, 105].\n1 <= Node.val <= 106" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-visible-points/discuss/1502236/Python-Clean-Sliding-Window", "python_solutions": "class Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, l: List[int]) -> int:\n \n array = []\n nloc = 0\n for p in points:\n if p == l:\n nloc += 1\n else:\n array.append(math.degrees(atan2(p[1]-l[1], p[0]-l[0])))\n array.sort()\n angles = array + [a+360 for a in array]\n left, maxm = 0, 0\n for right, a in enumerate(angles):\n if a-angles[left] > angle:\n left += 1\n maxm = max(right-left+1, maxm)\n \n return maxm + nloc", "slug": "maximum-number-of-visible-points", "post_title": "[Python] Clean Sliding Window", "user": "soma28", "upvotes": 1, "views": 669, "problem_title": "maximum number of visible points", "number": 1610, "acceptance": 0.374, "difficulty": "Hard", "__index_level_0__": 23527, "question": "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.\nInitially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].\nYour browser does not support the video tag or this video format.\nYou can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.\nThere can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.\nReturn the maximum number of points you can see.\n Example 1:\nInput: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\nOutput: 3\nExplanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\nExample 2:\nInput: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\nOutput: 4\nExplanation: All points can be made visible in your field of view, including the one at your location.\nExample 3:\nInput: points = [[1,0],[2,1]], angle = 13, location = [1,1]\nOutput: 1\nExplanation: You can only see one of the two points, as shown above.\n Constraints:\n1 <= points.length <= 105\npoints[i].length == 2\nlocation.length == 2\n0 <= angle < 360\n0 <= posx, posy, xi, yi <= 100" }, { "post_href": "https://leetcode.com/problems/minimum-one-bit-operations-to-make-integers-zero/discuss/2273798/Easy-to-understand-6-line-solution-with-explanation-or-O(N)-time-O(1)-space", "python_solutions": "class Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n \"\"\"\n to flip the bits to turn the number to zero\n \n Interpretation of Rules:\n - recursive:\n to turn a leading one of i bits to zero, the only way is to turn the i-1 bits to a leading one pattern\n and to turn the i-1 bits leading zero to zero, the only way is to turn the i-2 bits to a leading one pattern\n and so on, which is a recursive process\n \n (10000.. -> 11000.. -> 01000..), (01000.. -> 01100.. -> 00100), ..., (..010 -> ..011 -> ..001 -> ..000)\n \n - reversable:\n \n Let's make some observations to check if there's any pattern:\n\n - 2: 10 -> 11 -> 01 -> 00\n - 4: 100 -> 101 -> 111 -> 110 -> 010 -> 011 -> 001 -> 000\n - 8: 1000 -> 1001 -> 1011 -> 1010 -> 1110 -> 1111 -> 1101 -> 1100 -> 0100 -> (reversing 100 to 000) -> 0000\n ...\n \n based on the observation, turning every i bits leading one to zero, is turning the i-1 bits from 00.. to 10..\n and then back to 00.., which is a reverable process, and with the recursive process we can conclude that\n turning any length of 00..M-> 10.. is a reversable process\n \n - all unique states:\n since it is recursive and reversable, and we are flipping every bit between 1 and 0 programtically 10.. <-> 00..\n we can conclude that every intermediate state in a process is unique (2**i unique states, so we need 2**i - 1 steps)\n \n for i bits 10.. <-> 00.. - numer of operations f(i) = 2**i - 1\n \n this also aligns with the observation above that f(i) = 2*f(i-1) - 1 (-1 for no operation needed to achieve the initial 000)\n \n Process:\n to turn any binary to 0, we can turning the 1s to 0s one by one from lower bit to higher bit\n and because turning a higher bit 1 to 0, would passing the unique state including the lower bit 1s\n we can reverse those operations needed for the higher bit 100.. to the unique state including the lower bit 1s\n \n e.g. turning 1010100 to 0\n - 1010(100) -> 1010(000), we will need 2**3 - 1 operations\n - 10(10000) -> 10(00000), we will need (2**5 - 1) - (2**3 - 1) operations\n we will be passing the state 10(10100), which is ready available from the last state\n so we can save/reverse/deduct the operations needed for 1010(000) <-> 1010(100)\n - ...\n \n so for any binary, f(binary) would tell us how many operations we need for binary <-> 000..\n and for any more 1s, 100{binary} we can regard it as a process of 100.. <-> 100{binary} <-> 000{000..}\n which is 100.. <-> 000.. (2**i - 1) saving the operations 100{000..} <-> 100{binary} (f(binary))\n = (2**i - 1) - f(last_binary)\n \n \"\"\"\n binary = format(n, \"b\")\n\n N, res = len(binary), 0\n \n for i in range(1, N+1):\n if binary[-i] == \"1\": res = 2**i-1 - res\n \n return res", "slug": "minimum-one-bit-operations-to-make-integers-zero", "post_title": "Easy to understand 6-line solution with explanation | O(N) time O(1) space", "user": "zhenyulin", "upvotes": 2, "views": 370, "problem_title": "minimum one bit operations to make integers zero", "number": 1611, "acceptance": 0.634, "difficulty": "Hard", "__index_level_0__": 23528, "question": "Given an integer n, you must transform it into 0 using the following operations any number of times:\nChange the rightmost (0th) bit in the binary representation of n.\nChange 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.\nReturn the minimum number of operations to transform n into 0.\n Example 1:\nInput: n = 3\nOutput: 2\nExplanation: The binary representation of 3 is \"11\".\n\"11\" -> \"01\" with the 2nd operation since the 0th bit is 1.\n\"01\" -> \"00\" with the 1st operation.\nExample 2:\nInput: n = 6\nOutput: 4\nExplanation: The binary representation of 6 is \"110\".\n\"110\" -> \"010\" with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.\n\"010\" -> \"011\" with the 1st operation.\n\"011\" -> \"001\" with the 2nd operation since the 0th bit is 1.\n\"001\" -> \"000\" with the 1st operation.\n Constraints:\n0 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/discuss/1171599/Python3-Simple-And-Readable-Solution", "python_solutions": "class Solution:\n def maxDepth(self, s: str) -> int:\n depths = [0]\n \n count = 0\n for i in s:\n if(i == '('):\n count += 1\n elif(i == ')'):\n count -= 1\n depths.append(count)\n \n return max(depths)", "slug": "maximum-nesting-depth-of-the-parentheses", "post_title": "[Python3] Simple And Readable Solution", "user": "VoidCupboard", "upvotes": 7, "views": 258, "problem_title": "maximum nesting depth of the parentheses", "number": 1614, "acceptance": 0.8270000000000001, "difficulty": "Easy", "__index_level_0__": 23531, "question": "Given a valid parentheses string s, return the nesting depth of s. The nesting depth is the maximum number of nested parentheses.\n Example 1:\nInput: s = \"(1+(2*3)+((8)/4))+1\"\nOutput: 3\nExplanation:\nDigit 8 is inside of 3 nested parentheses in the string.\nExample 2:\nInput: s = \"(1)+((2))+(((3)))\"\nOutput: 3\nExplanation:\nDigit 3 is inside of 3 nested parentheses in the string.\nExample 3:\nInput: s = \"()(())((()()))\"\nOutput: 3\n Constraints:\n1 <= s.length <= 100\ns consists of digits 0-9 and characters '+', '-', '*', '/', '(', and ')'.\nIt is guaranteed that parentheses expression s is a VPS." }, { "post_href": "https://leetcode.com/problems/maximal-network-rank/discuss/888965/Python3-graph-as-adjacency-list", "python_solutions": "class Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n graph = {}\n for u, v in roads:\n graph.setdefault(u, set()).add(v)\n graph.setdefault(v, set()).add(u)\n \n ans = 0\n for i in range(n): \n for j in range(i+1, n):\n val = len(graph.get(i, set())) + len(graph.get(j, set())) - (j in graph.get(i, set()))\n ans = max(ans, val)\n return ans", "slug": "maximal-network-rank", "post_title": "[Python3] graph as adjacency list", "user": "ye15", "upvotes": 8, "views": 1100, "problem_title": "maximal network rank", "number": 1615, "acceptance": 0.581, "difficulty": "Medium", "__index_level_0__": 23568, "question": "There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.\nThe network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.\nThe maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.\nGiven the integer n and the array roads, return the maximal network rank of the entire infrastructure.\n Example 1:\nInput: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\nOutput: 4\nExplanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.\nExample 2:\nInput: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\nOutput: 5\nExplanation: There are 5 roads that are connected to cities 1 or 2.\nExample 3:\nInput: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\nOutput: 5\nExplanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.\n Constraints:\n2 <= n <= 100\n0 <= roads.length <= n * (n - 1) / 2\nroads[i].length == 2\n0 <= ai, bi <= n-1\nai != bi\nEach pair of cities has at most one road connecting them." }, { "post_href": "https://leetcode.com/problems/split-two-strings-to-make-palindrome/discuss/888981/Python3-greedy", "python_solutions": "class Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n \n fn = lambda x: x == x[::-1] # check for palindrome \n \n i = 0\n while i < len(a) and a[i] == b[~i]: i += 1\n if fn(a[:i] + b[i:]) or fn(a[:-i] + b[-i:]): return True \n \n i = 0\n while i < len(a) and a[~i] == b[i]: i += 1\n if fn(b[:i] + a[i:]) or fn(b[:-i] + a[-i:]): return True \n \n return False", "slug": "split-two-strings-to-make-palindrome", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 6, "views": 299, "problem_title": "split two strings to make palindrome", "number": 1616, "acceptance": 0.314, "difficulty": "Medium", "__index_level_0__": 23577, "question": "You are given two strings a and b of the same length. Choose an index and split both strings at the same index, splitting a into two strings: aprefix and asuffix where a = aprefix + asuffix, and splitting b into two strings: bprefix and bsuffix where b = bprefix + bsuffix. Check if aprefix + bsuffix or bprefix + asuffix forms a palindrome.\nWhen you split a string s into sprefix and ssuffix, either ssuffix or sprefix is allowed to be empty. For example, if s = \"abc\", then \"\" + \"abc\", \"a\" + \"bc\", \"ab\" + \"c\" , and \"abc\" + \"\" are valid splits.\nReturn true if it is possible to form a palindrome string, otherwise return false.\nNotice that x + y denotes the concatenation of strings x and y.\n Example 1:\nInput: a = \"x\", b = \"y\"\nOutput: true\nExplaination: If either a or b are palindromes the answer is true since you can split in the following way:\naprefix = \"\", asuffix = \"x\"\nbprefix = \"\", bsuffix = \"y\"\nThen, aprefix + bsuffix = \"\" + \"y\" = \"y\", which is a palindrome.\nExample 2:\nInput: a = \"xbdef\", b = \"xecab\"\nOutput: false\nExample 3:\nInput: a = \"ulacfd\", b = \"jizalu\"\nOutput: true\nExplaination: Split them at index 3:\naprefix = \"ula\", asuffix = \"cfd\"\nbprefix = \"jiz\", bsuffix = \"alu\"\nThen, aprefix + bsuffix = \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.\n Constraints:\n1 <= a.length, b.length <= 105\na.length == b.length\na and b consist of lowercase English letters" }, { "post_href": "https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/1068298/Python-Top-Down-DP-O(n5).-35-ms-and-faster-than-100-explained", "python_solutions": "class Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n # Create Tree as adjacency list\n neigh: List[List[int]] = [[] for _ in range(n)]\n for u, v in edges:\n neigh[u - 1].append(v - 1)\n neigh[v - 1].append(u - 1)\n\n distance_array: List[int] = [0] * n\n\n def find_tree_center(vertices: List[int], adj_list: List[List[int]]) -> int:\n \"\"\"Given a tree, return a central vertex (minimum radius vertex) with BFS\"\"\"\n\n num_neighbors: List[int] = list(map(len, adj_list))\n leaf_nodes: Deque[int] = collections.deque((x for x in range(len(vertices)) if num_neighbors[x] == 1))\n while len(leaf_nodes) > 1:\n leaf = leaf_nodes.popleft()\n for neighbor in adj_list[leaf]:\n num_neighbors[neighbor] -= 1\n if num_neighbors[neighbor] == 1:\n leaf_nodes.append(neighbor)\n return leaf_nodes[0]\n\n def merge_into_parent(parent_subtrees: Dict[Tuple[int, int], int],\n child_subtrees: Dict[Tuple[int, int], int]) -> None:\n\n \"\"\" Helper function to merge two disjoint rooted trees T_parent and T_child rooted at 'parent' and 'child',\n into one tree rooted at 'parent', by adding an edge from 'parent' to 'child'.\n Called once for each edge in our tree. parent_subtrees[i, j] is the count of rooted subtrees\n of T_parent that contain 'parent', have diameter i, and height j.\n Worst case complexity: O(n^4) per call\n \"\"\"\n\n for (diam_for_parent, height_for_parent), count_from_parent in list(parent_subtrees.items()):\n\n for (diam_for_child, height_for_child), count_from_child in child_subtrees.items():\n\n new_diameter = max(diam_for_parent, diam_for_child, height_for_parent + height_for_child + 1)\n new_height = max(height_for_parent, height_for_child + 1)\n parent_subtrees[new_diameter, new_height] = parent_subtrees.get((new_diameter, new_height), 0) + count_from_child * count_from_parent\n\n return None\n\n def compute_subtree_counts(current_vertex: int,\n last_vertex: int = -1) -> Dict[Tuple[int, int], int]:\n \"\"\"Recursively counts subtrees rooted at current_vertex using DFS,\n with edge from current_vertex to 'last_vertex' (parent node) cut off\"\"\"\n subtree_counts: Dict[Tuple[int, int], int] = {(0, 0): 1}\n\n for child_vertex in neigh[current_vertex]:\n if child_vertex == last_vertex:\n continue\n\n merge_into_parent(parent_subtrees=subtree_counts,\n child_subtrees=compute_subtree_counts(current_vertex=child_vertex,\n last_vertex=current_vertex))\n\n for (diameter, height), subtree_count in subtree_counts.items():\n distance_array[diameter] += subtree_count\n\n return subtree_counts\n\n # Optimization: Use a max-degree vertex as our root to minimize recursion depth\n max_degree_vertex: int = find_tree_center(vertices=list(range(n)),\n adj_list=neigh)\n\n compute_subtree_counts(current_vertex=max_degree_vertex)\n\n return distance_array[1:]", "slug": "count-subtrees-with-max-distance-between-cities", "post_title": "[Python] Top-Down DP, O(n^5). 35 ms and faster than 100%, explained", "user": "kcsquared", "upvotes": 2, "views": 137, "problem_title": "count subtrees with max distance between cities", "number": 1617, "acceptance": 0.657, "difficulty": "Hard", "__index_level_0__": 23584, "question": "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.\nA subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.\nFor each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.\nReturn an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.\nNotice that the distance between the two cities is the number of edges in the path between them.\n Example 1:\nInput: n = 4, edges = [[1,2],[2,3],[2,4]]\nOutput: [3,4,0]\nExplanation:\nThe subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\nThe subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\nNo subtree has two nodes where the max distance between them is 3.\nExample 2:\nInput: n = 2, edges = [[1,2]]\nOutput: [1]\nExample 3:\nInput: n = 3, edges = [[1,2],[2,3]]\nOutput: [2,1]\n Constraints:\n2 <= n <= 15\nedges.length == n-1\nedges[i].length == 2\n1 <= ui, vi <= n\nAll pairs (ui, vi) are distinct." }, { "post_href": "https://leetcode.com/problems/mean-of-array-after-removing-some-elements/discuss/1193688/2-easy-Python-Solutions", "python_solutions": "class Solution:\n def trimMean(self, arr: List[int]) -> float:\n arr.sort()\n\n return statistics.mean(arr[int(len(arr)*5/100):len(arr)-int(len(arr)*5/100)])", "slug": "mean-of-array-after-removing-some-elements", "post_title": "2 easy Python Solutions", "user": "ayushi7rawat", "upvotes": 6, "views": 617, "problem_title": "mean of array after removing some elements", "number": 1619, "acceptance": 0.647, "difficulty": "Easy", "__index_level_0__": 23587, "question": "Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.\nAnswers within 10-5 of the actual answer will be considered accepted.\n Example 1:\nInput: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\nOutput: 2.00000\nExplanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.\nExample 2:\nInput: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\nOutput: 4.00000\nExample 3:\nInput: arr = [6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4]\nOutput: 4.77778\n Constraints:\n20 <= arr.length <= 1000\narr.length is a multiple of 20.\n0 <= arr[i] <= 105" }, { "post_href": "https://leetcode.com/problems/coordinate-with-maximum-network-quality/discuss/1103762/Python3-enumerate-all-candidates", "python_solutions": "class Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n mx = -inf\n for x in range(51):\n for y in range(51): \n val = 0\n for xi, yi, qi in towers: \n d = sqrt((x-xi)**2 + (y-yi)**2)\n if d <= radius: val += int(qi/(1 + d))\n if val > mx: \n ans = [x, y]\n mx = val\n return ans", "slug": "coordinate-with-maximum-network-quality", "post_title": "[Python3] enumerate all candidates", "user": "ye15", "upvotes": 2, "views": 143, "problem_title": "coordinate with maximum network quality", "number": 1620, "acceptance": 0.376, "difficulty": "Medium", "__index_level_0__": 23615, "question": "You are given an array of network towers towers, where towers[i] = [xi, yi, qi] denotes the ith network tower with location (xi, yi) and quality factor qi. All the coordinates are integral coordinates on the X-Y plane, and the distance between the two coordinates is the Euclidean distance.\nYou are also given an integer radius where a tower is reachable if the distance is less than or equal to radius. Outside that distance, the signal becomes garbled, and the tower is not reachable.\nThe signal quality of the ith tower at a coordinate (x, y) is calculated with the formula \u230aqi / (1 + d)\u230b, where d is the distance between the tower and the coordinate. The network quality at a coordinate is the sum of the signal qualities from all the reachable towers.\nReturn the array [cx, cy] representing the integral coordinate (cx, cy) where the network quality is maximum. If there are multiple coordinates with the same network quality, return the lexicographically minimum non-negative coordinate.\nNote:\nA coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:\nx1 < x2, or\nx1 == x2 and y1 < y2.\n\u230aval\u230b is the greatest integer less than or equal to val (the floor function).\n Example 1:\nInput: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\nOutput: [2,1]\nExplanation: At coordinate (2, 1) the total quality is 13.\n- Quality of 7 from (2, 1) results in \u230a7 / (1 + sqrt(0)\u230b = \u230a7\u230b = 7\n- Quality of 5 from (1, 2) results in \u230a5 / (1 + sqrt(2)\u230b = \u230a2.07\u230b = 2\n- Quality of 9 from (3, 1) results in \u230a9 / (1 + sqrt(1)\u230b = \u230a4.5\u230b = 4\nNo other coordinate has a higher network quality.\nExample 2:\nInput: towers = [[23,11,21]], radius = 9\nOutput: [23,11]\nExplanation: Since there is only one tower, the network quality is highest right at the tower's location.\nExample 3:\nInput: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\nOutput: [1,2]\nExplanation: Coordinate (1, 2) has the highest network quality.\n Constraints:\n1 <= towers.length <= 50\ntowers[i].length == 3\n0 <= xi, yi, qi <= 50\n1 <= radius <= 50" }, { "post_href": "https://leetcode.com/problems/number-of-sets-of-k-non-overlapping-line-segments/discuss/1103787/Python3-top-down-dp", "python_solutions": "class Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n \n @cache\n def fn(n, k):\n \"\"\"Return number of sets.\"\"\"\n if n <= k: return 0 \n if k == 0: return 1\n return 2*fn(n-1, k) + fn(n-1, k-1) - fn(n-2, k)\n \n return fn(n, k) % 1_000_000_007", "slug": "number-of-sets-of-k-non-overlapping-line-segments", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 1, "views": 141, "problem_title": "number of sets of k non overlapping line segments", "number": 1621, "acceptance": 0.422, "difficulty": "Medium", "__index_level_0__": 23617, "question": "Given n points on a 1-D plane, where the ith point (from 0 to n-1) is at x = i, find the number of ways we can draw exactly k non-overlapping line segments such that each segment covers two or more points. The endpoints of each segment must have integral coordinates. The k line segments do not have to cover all n points, and they are allowed to share endpoints.\nReturn the number of ways we can draw k non-overlapping line segments. Since this number can be huge, return it modulo 109 + 7.\n Example 1:\nInput: n = 4, k = 2\nOutput: 5\nExplanation: The two line segments are shown in red and blue.\nThe image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.\nExample 2:\nInput: n = 3, k = 1\nOutput: 3\nExplanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.\nExample 3:\nInput: n = 30, k = 7\nOutput: 796297179\nExplanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.\n Constraints:\n2 <= n <= 1000\n1 <= k <= n-1" }, { "post_href": "https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/899540/Python3-via-dictionary", "python_solutions": "class Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n ans = -1\n seen = {}\n for i, c in enumerate(s): \n if c in seen: ans = max(ans, i - seen[c] - 1)\n seen.setdefault(c, i)\n return ans", "slug": "largest-substring-between-two-equal-characters", "post_title": "[Python3] via dictionary", "user": "ye15", "upvotes": 13, "views": 710, "problem_title": "largest substring between two equal characters", "number": 1624, "acceptance": 0.591, "difficulty": "Easy", "__index_level_0__": 23618, "question": "Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: s = \"aa\"\nOutput: 0\nExplanation: The optimal substring here is an empty substring between the two 'a's.\nExample 2:\nInput: s = \"abca\"\nOutput: 2\nExplanation: The optimal substring here is \"bc\".\nExample 3:\nInput: s = \"cbzxy\"\nOutput: -1\nExplanation: There are no characters that appear twice in s.\n Constraints:\n1 <= s.length <= 300\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/lexicographically-smallest-string-after-applying-operations/discuss/899547/Python3-dfs", "python_solutions": "class Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n op1 = lambda s: \"\".join(str((int(c)+a)%10) if i&1 else c for i, c in enumerate(s))\n op2 = lambda s: s[-b:] + s[:-b]\n \n seen = set()\n stack = [s]\n while stack: \n s = stack.pop()\n seen.add(s)\n if (ss := op1(s)) not in seen: stack.append(ss)\n if (ss := op2(s)) not in seen: stack.append(ss)\n return min(seen)", "slug": "lexicographically-smallest-string-after-applying-operations", "post_title": "[Python3] dfs", "user": "ye15", "upvotes": 7, "views": 384, "problem_title": "lexicographically smallest string after applying operations", "number": 1625, "acceptance": 0.66, "difficulty": "Medium", "__index_level_0__": 23634, "question": "You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.\nYou can apply either of the following two operations any number of times and in any order on s:\nAdd a to all odd indices of s (0-indexed). Digits post 9 are cycled back to 0. For example, if s = \"3456\" and a = 5, s becomes \"3951\".\nRotate s to the right by b positions. For example, if s = \"3456\" and b = 1, s becomes \"6345\".\nReturn the lexicographically smallest string you can obtain by applying the above operations any number of times on s.\nA string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b. For example, \"0158\" is lexicographically smaller than \"0190\" because the first position they differ is at the third letter, and '5' comes before '9'.\n Example 1:\nInput: s = \"5525\", a = 9, b = 2\nOutput: \"2050\"\nExplanation: We can apply the following operations:\nStart: \"5525\"\nRotate: \"2555\"\nAdd: \"2454\"\nAdd: \"2353\"\nRotate: \"5323\"\nAdd: \"5222\"\nAdd: \"5121\"\nRotate: \"2151\"\nAdd: \"2050\"\nThere is no way to obtain a string that is lexicographically smaller than \"2050\".\nExample 2:\nInput: s = \"74\", a = 5, b = 1\nOutput: \"24\"\nExplanation: We can apply the following operations:\nStart: \"74\"\nRotate: \"47\"\nAdd: \"42\"\nRotate: \"24\"\nThere is no way to obtain a string that is lexicographically smaller than \"24\".\nExample 3:\nInput: s = \"0011\", a = 4, b = 2\nOutput: \"0011\"\nExplanation: There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".\n Constraints:\n2 <= s.length <= 100\ns.length is even.\ns consists of digits from 0 to 9 only.\n1 <= a <= 9\n1 <= b <= s.length - 1" }, { "post_href": "https://leetcode.com/problems/best-team-with-no-conflicts/discuss/2848106/Python-Heavily-commented-to-self-understand-first-of-all-DP-2-Loops", "python_solutions": "class Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n '''\n Using example scores = [1,2,3,5] and ages = [8,9,10,1]\n \n data is [(1, 5), (8, 1), (9, 2), (10, 3)]\n and dp is [5, 1, 2, 3]\n \n when curr player is (1, 5)\n there are no prev players -> so leave dp of curr as-is\n \n when curr player is (8, 1)\n prev player's score is not less than curr player score\n nor is previous player's age same as curr player age -> so leave dp of curr as-is\n \n when curr player is (9, 2)\n prev player (1, 5) has score NOT less than, and age NOT equal to ... skipping\n prev player (8, 1) has score YES less than ... so we do something!\n since the accumulated dp of prev player + curr's score is GREATER than curr's accumulated dp value:\n we update curr's accumulated dp value to be instead sum of prev player's dp value and curr's score\n \n when curr player is (10, 3)\n prev player (1, 5) has score NOT less, and age NTO equal to ... skipping\n prev player (8, 1) has score YES less, so update curr's dp value from 3 -> 3+1 = 4\n prev player (9, 2) has score YES less, so update curr's dp value from 4 -> 4+2 = 6\n \n finally we return the max of all dp values for the dream team.\n '''\n # Sort by age and score ASC\n data = sorted(zip(ages, scores), key=lambda x:(x[0], x[1]))\n # Initialize dp with scores for each player\n dp = [score for age, score in data]\n N = len(data)\n \n # For every current player\n for curr in range(N):\n # Compare every previous player\n for prev in range(0, curr):\n # And if previous player score is less OR previous player is same age\n if (data[prev][1] <= data[curr][1] or data[curr][0] == data[prev][0]):\n # Then update dp value for current player to be the max of either\n # -> the current score as it is OR\n # -> the current score PLUS the dp value of previous player\n dp[curr] = max(dp[curr], data[curr][1] + dp[prev])\n\n return max(dp)", "slug": "best-team-with-no-conflicts", "post_title": "[Python] Heavily commented to self understand first of all - DP 2 Loops", "user": "graceiscoding", "upvotes": 0, "views": 1, "problem_title": "best team with no conflicts", "number": 1626, "acceptance": 0.412, "difficulty": "Medium", "__index_level_0__": 23638, "question": "You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the sum of scores of all the players in the team.\nHowever, the basketball team is not allowed to have conflicts. A conflict exists if a younger player has a strictly higher score than an older player. A conflict does not occur between players of the same age.\nGiven two lists, scores and ages, where each scores[i] and ages[i] represents the score and age of the ith player, respectively, return the highest overall score of all possible basketball teams.\n Example 1:\nInput: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\nOutput: 34\nExplanation: You can choose all the players.\nExample 2:\nInput: scores = [4,5,6,5], ages = [2,1,2,1]\nOutput: 16\nExplanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.\nExample 3:\nInput: scores = [1,2,3,5], ages = [8,9,10,1]\nOutput: 6\nExplanation: It is best to choose the first 3 players. \n Constraints:\n1 <= scores.length, ages.length <= 1000\nscores.length == ages.length\n1 <= scores[i] <= 106\n1 <= ages[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/slowest-key/discuss/1172372/Python3-Simple-And-Readable-Solution", "python_solutions": "class Solution:\n def slowestKey(self, r: List[int], k: str) -> str:\n times = {r[0]: [k[0]]}\n \n for i in range(1 , len(r)):\n t = r[i] - r[i - 1]\n if(t in times):\n times[t].append(k[i])\n else:\n times[t] = [k[i]]\n \n keys = times[max(times.keys())]\n \n return max(keys)", "slug": "slowest-key", "post_title": "[Python3] Simple And Readable Solution", "user": "VoidCupboard", "upvotes": 7, "views": 337, "problem_title": "slowest key", "number": 1629, "acceptance": 0.593, "difficulty": "Easy", "__index_level_0__": 23642, "question": "A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.\nYou are given a string keysPressed of length n, where keysPressed[i] was the ith key pressed in the testing sequence, and a sorted list releaseTimes, where releaseTimes[i] was the time the ith key was released. Both arrays are 0-indexed. The 0th key was pressed at the time 0, and every subsequent key was pressed at the exact time the previous key was released.\nThe tester wants to know the key of the keypress that had the longest duration. The ith keypress had a duration of releaseTimes[i] - releaseTimes[i - 1], and the 0th keypress had a duration of releaseTimes[0].\nNote that the same key could have been pressed multiple times during the test, and these multiple presses of the same key may not have had the same duration.\nReturn the key of the keypress that had the longest duration. If there are multiple such keypresses, return the lexicographically largest key of the keypresses.\n Example 1:\nInput: releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"\nOutput: \"c\"\nExplanation: The keypresses were as follows:\nKeypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\nKeypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).\nKeypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).\nKeypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).\nThe longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n'c' is lexicographically larger than 'b', so the answer is 'c'.\nExample 2:\nInput: releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"\nOutput: \"a\"\nExplanation: The keypresses were as follows:\nKeypress for 's' had a duration of 12.\nKeypress for 'p' had a duration of 23 - 12 = 11.\nKeypress for 'u' had a duration of 36 - 23 = 13.\nKeypress for 'd' had a duration of 46 - 36 = 10.\nKeypress for 'a' had a duration of 62 - 46 = 16.\nThe longest of these was the keypress for 'a' with duration 16.\n Constraints:\nreleaseTimes.length == n\nkeysPressed.length == n\n2 <= n <= 1000\n1 <= releaseTimes[i] <= 109\nreleaseTimes[i] < releaseTimes[i+1]\nkeysPressed contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/arithmetic-subarrays/discuss/1231666/Python3-Brute-force", "python_solutions": "class Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n ans = []\n \n def find_diffs(arr):\n \n arr.sort()\n\n dif = []\n \n for i in range(len(arr) - 1):\n dif.append(arr[i] - arr[i + 1])\n \n return len(set(dif)) == 1\n \n for i , j in zip(l , r):\n ans.append(find_diffs(nums[i:j + 1]))\n \n return ans", "slug": "arithmetic-subarrays", "post_title": "[Python3] Brute force", "user": "VoidCupboard", "upvotes": 9, "views": 468, "problem_title": "arithmetic subarrays", "number": 1630, "acceptance": 0.8, "difficulty": "Medium", "__index_level_0__": 23671, "question": "A sequence of numbers is called arithmetic if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence s is arithmetic if and only if s[i+1] - s[i] == s[1] - s[0] for all valid i.\nFor example, these are arithmetic sequences:\n1, 3, 5, 7, 9\n7, 7, 7, 7\n3, -1, -5, -9\nThe following sequence is not arithmetic:\n1, 1, 2, 5, 7\nYou are given an array of n integers, nums, and two arrays of m integers each, l and r, representing the m range queries, where the ith query is the range [l[i], r[i]]. All the arrays are 0-indexed.\nReturn a list of boolean elements answer, where answer[i] is true if the subarray nums[l[i]], nums[l[i]+1], ... , nums[r[i]] can be rearranged to form an arithmetic sequence, and false otherwise.\n Example 1:\nInput: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]\nOutput: [true,false,true]\nExplanation:\nIn the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\nIn the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\nIn the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.\nExample 2:\nInput: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]\nOutput: [false,true,false,false,true,true]\n Constraints:\nn == nums.length\nm == l.length\nm == r.length\n2 <= n <= 500\n1 <= m <= 500\n0 <= l[i] < r[i] < n\n-105 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/path-with-minimum-effort/discuss/909094/Python3-bfs-and-Dijkstra", "python_solutions": "class Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n m, n = len(heights), len(heights[0])\n \n queue = {(0, 0): 0} # (0, 0) maximum height so far \n seen = {(0, 0): 0} # (i, j) -> heights \n ans = inf \n \n while queue: \n newq = {} # new dictionary \n for (i, j), h in queue.items(): \n if i == m-1 and j == n-1: ans = min(ans, h)\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n: \n hh = max(h, abs(heights[i][j] - heights[ii][jj]))\n if hh < seen.get((ii, jj), inf): \n seen[(ii, jj)] = hh \n newq[(ii, jj)] = hh\n queue = newq \n return ans", "slug": "path-with-minimum-effort", "post_title": "[Python3] bfs & Dijkstra", "user": "ye15", "upvotes": 2, "views": 219, "problem_title": "path with minimum effort", "number": 1631, "acceptance": 0.5539999999999999, "difficulty": "Medium", "__index_level_0__": 23710, "question": "You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.\nA route's effort is the maximum absolute difference in heights between two consecutive cells of the route.\nReturn the minimum effort required to travel from the top-left cell to the bottom-right cell.\n Example 1:\nInput: heights = [[1,2,2],[3,8,2],[5,3,5]]\nOutput: 2\nExplanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\nThis is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\nExample 2:\nInput: heights = [[1,2,3],[3,8,4],[5,3,5]]\nOutput: 1\nExplanation: The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].\nExample 3:\nInput: heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]\nOutput: 0\nExplanation: This route does not require any effort.\n Constraints:\nrows == heights.length\ncolumns == heights[i].length\n1 <= rows, columns <= 100\n1 <= heights[i][j] <= 106" }, { "post_href": "https://leetcode.com/problems/rank-transform-of-a-matrix/discuss/913790/Python3-UF", "python_solutions": "class Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n m, n = len(matrix), len(matrix[0]) # dimension \n # mapping from value to index \n mp = {} \n for i in range(m):\n for j in range(n): \n mp.setdefault(matrix[i][j], []).append((i, j))\n \n def find(p):\n \"\"\"Find root of p.\"\"\"\n if p != parent[p]:\n parent[p] = find(parent[p])\n return parent[p]\n \n rank = [0]*(m+n)\n ans = [[0]*n for _ in range(m)]\n \n for k in sorted(mp): # from minimum to maximum \n parent = list(range(m+n))\n for i, j in mp[k]: \n ii, jj = find(i), find(m+j) # find \n parent[ii] = jj # union \n rank[jj] = max(rank[ii], rank[jj]) # max rank \n \n seen = set()\n for i, j in mp[k]:\n ii = find(i)\n if ii not in seen: rank[ii] += 1\n seen.add(ii)\n rank[i] = rank[m+j] = ans[i][j] = rank[ii]\n return ans", "slug": "rank-transform-of-a-matrix", "post_title": "[Python3] UF", "user": "ye15", "upvotes": 5, "views": 465, "problem_title": "rank transform of a matrix", "number": 1632, "acceptance": 0.41, "difficulty": "Hard", "__index_level_0__": 23728, "question": "Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].\nThe rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:\nThe rank is an integer starting from 1.\nIf two elements p and q are in the same row or column, then:\nIf p < q then rank(p) < rank(q)\nIf p == q then rank(p) == rank(q)\nIf p > q then rank(p) > rank(q)\nThe rank should be as small as possible.\nThe test cases are generated so that answer is unique under the given rules.\n Example 1:\nInput: matrix = [[1,2],[3,4]]\nOutput: [[1,2],[2,3]]\nExplanation:\nThe rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\nThe rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\nThe rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.\nExample 2:\nInput: matrix = [[7,7],[7,7]]\nOutput: [[1,1],[1,1]]\nExample 3:\nInput: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\nOutput: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 500\n-109 <= matrix[row][col] <= 109" }, { "post_href": "https://leetcode.com/problems/sort-array-by-increasing-frequency/discuss/963292/Python-1-liner", "python_solutions": "class Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n return sorted(sorted(nums,reverse=1),key=nums.count)", "slug": "sort-array-by-increasing-frequency", "post_title": "Python 1-liner", "user": "lokeshsenthilkumar", "upvotes": 22, "views": 1500, "problem_title": "sort array by increasing frequency", "number": 1636, "acceptance": 0.687, "difficulty": "Easy", "__index_level_0__": 23730, "question": "Given an array of integers nums, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.\nReturn the sorted array.\n Example 1:\nInput: nums = [1,1,2,2,2,3]\nOutput: [3,1,1,2,2,2]\nExplanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.\nExample 2:\nInput: nums = [2,3,1,3,2]\nOutput: [1,3,3,2,2]\nExplanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.\nExample 3:\nInput: nums = [-1,1,-6,4,5,-6,1,4,1]\nOutput: [5,-1,4,4,-6,-6,1,1,1]\n Constraints:\n1 <= nums.length <= 100\n-100 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/widest-vertical-area-between-two-points-containing-no-points/discuss/2806260/Python-or-Easy-Peasy-Code-or-O(n)", "python_solutions": "class Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n l = []\n for i in points:\n l.append(i[0])\n a = 0\n l.sort()\n for i in range(len(l)-1):\n if l[i+1] - l[i] > a:\n a = l[i+1] - l[i]\n return a", "slug": "widest-vertical-area-between-two-points-containing-no-points", "post_title": "Python | Easy Peasy Code | O(n)", "user": "bhuvneshwar906", "upvotes": 0, "views": 2, "problem_title": "widest vertical area between two points containing no points", "number": 1637, "acceptance": 0.8420000000000001, "difficulty": "Medium", "__index_level_0__": 23761, "question": "Given n points on a 2D plane where points[i] = [xi, yi], Return the widest vertical area between two points such that no points are inside the area.\nA vertical area is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The widest vertical area is the one with the maximum width.\nNote that points on the edge of a vertical area are not considered included in the area.\n Example 1:\nInput: points = [[8,7],[9,9],[7,4],[9,7]]\nOutput: 1\nExplanation: Both the red and the blue area are optimal.\nExample 2:\nInput: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\nOutput: 3\n Constraints:\nn == points.length\n2 <= n <= 105\npoints[i].length == 2\n0 <= xi, yi <= 109" }, { "post_href": "https://leetcode.com/problems/count-substrings-that-differ-by-one-character/discuss/1101671/Python3-top-down-and-bottom-up-dp", "python_solutions": "class Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n m, n = len(s), len(t) \n \n @cache\n def fn(i, j, k): \n \"\"\"Return number of substrings ending at s[i] and t[j] with k=0/1 difference.\"\"\"\n if i < 0 or j < 0: return 0 \n if s[i] == t[j]: return fn(i-1, j-1, k) + (k==0)\n else: return 0 if k == 0 else 1 + fn(i-1, j-1, 0)\n \n return sum(fn(i, j, 1) for i in range(m) for j in range(n))", "slug": "count-substrings-that-differ-by-one-character", "post_title": "[Python3] top-down & bottom-up dp", "user": "ye15", "upvotes": 5, "views": 303, "problem_title": "count substrings that differ by one character", "number": 1638, "acceptance": 0.7140000000000001, "difficulty": "Medium", "__index_level_0__": 23779, "question": "Given two strings s and t, find the number of ways you can choose a non-empty substring of s and replace a single character by a different character such that the resulting substring is a substring of t. In other words, find the number of substrings in s that differ from some substring in t by exactly one character.\nFor example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way.\nReturn the number of substrings that satisfy the condition above.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: s = \"aba\", t = \"baba\"\nOutput: 6\nExplanation: The following are the pairs of substrings from s and t that differ by exactly 1 character:\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\n(\"aba\", \"baba\")\nThe underlined portions are the substrings that are chosen from s and t.\nExample 2:\nInput: s = \"ab\", t = \"bb\"\nOutput: 3\nExplanation: The following are the pairs of substrings from s and t that differ by 1 character:\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\n(\"ab\", \"bb\")\nThe underlined portions are the substrings that are chosen from s and t.\n Constraints:\n1 <= s.length, t.length <= 100\ns and t consist of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-form-a-target-string-given-a-dictionary/discuss/1101522/Python3-top-down-dp", "python_solutions": "class Solution:\n def numWays(self, words: List[str], target: str) -> int:\n freq = [defaultdict(int) for _ in range(len(words[0]))]\n for word in words: \n for i, c in enumerate(word): \n freq[i][c] += 1\n \n @cache\n def fn(i, k): \n \"\"\"Return number of ways to form target[i:] w/ col k.\"\"\"\n if i == len(target): return 1\n if k == len(words[0]): return 0 \n return freq[k][target[i]]*fn(i+1, k+1) + fn(i, k+1)\n \n return fn(0, 0) % 1_000_000_007", "slug": "number-of-ways-to-form-a-target-string-given-a-dictionary", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 2, "views": 169, "problem_title": "number of ways to form a target string given a dictionary", "number": 1639, "acceptance": 0.429, "difficulty": "Hard", "__index_level_0__": 23784, "question": "You are given a list of strings of the same length words and a string target.\nYour task is to form target using the given words under the following rules:\ntarget should be formed from left to right.\nTo 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].\nOnce 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.\nRepeat the process until you form the string target.\nNotice that you can use multiple characters from the same string in words provided the conditions above are met.\nReturn the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"\nOutput: 6\nExplanation: There are 6 ways to form target.\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n\"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n\"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\nExample 2:\nInput: words = [\"abba\",\"baab\"], target = \"bab\"\nOutput: 4\nExplanation: There are 4 ways to form target.\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 2 (\"abba\")\n\"bab\" -> index 0 (\"baab\"), index 1 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 0 (\"baab\"), index 2 (\"baab\"), index 3 (\"baab\")\n\"bab\" -> index 1 (\"abba\"), index 2 (\"baab\"), index 3 (\"baab\")\n Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length <= 1000\nAll strings in words have the same length.\n1 <= target.length <= 1000\nwords[i] and target contain only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/check-array-formation-through-concatenation/discuss/918382/Python3-2-line-O(N)", "python_solutions": "class Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n mp = {x[0]: x for x in pieces}\n i = 0\n while i < len(arr): \n if (x := arr[i]) not in mp or mp[x] != arr[i:i+len(mp[x])]: return False \n i += len(mp[x])\n return True", "slug": "check-array-formation-through-concatenation", "post_title": "[Python3] 2-line O(N)", "user": "ye15", "upvotes": 9, "views": 705, "problem_title": "check array formation through concatenation", "number": 1640, "acceptance": 0.561, "difficulty": "Easy", "__index_level_0__": 23790, "question": "You are given an array of distinct integers arr and an array of integer arrays pieces, where the integers in pieces are distinct. Your goal is to form arr by concatenating the arrays in pieces in any order. However, you are not allowed to reorder the integers in each array pieces[i].\nReturn true if it is possible to form the array arr from pieces. Otherwise, return false.\n Example 1:\nInput: arr = [15,88], pieces = [[88],[15]]\nOutput: true\nExplanation: Concatenate [15] then [88]\nExample 2:\nInput: arr = [49,18,16], pieces = [[16,18,49]]\nOutput: false\nExplanation: Even though the numbers match, we cannot reorder pieces[0].\nExample 3:\nInput: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\nOutput: true\nExplanation: Concatenate [91] then [4,64] then [78]\n Constraints:\n1 <= pieces.length <= arr.length <= 100\nsum(pieces[i].length) == arr.length\n1 <= pieces[i].length <= arr.length\n1 <= arr[i], pieces[i][j] <= 100\nThe integers in arr are distinct.\nThe integers in pieces are distinct (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct)." }, { "post_href": "https://leetcode.com/problems/count-sorted-vowel-strings/discuss/2027288/Python-4-approaches-(DP-Maths)", "python_solutions": "class Solution:\n def countVowelStrings(self, n: int) -> int: \n dp = [[0] * 6 for _ in range(n+1)]\n for i in range(1, 6):\n dp[1][i] = i\n \n for i in range(2, n+1):\n dp[i][1]=1\n for j in range(2, 6):\n dp[i][j] = dp[i][j-1] + dp[i-1][j]\n \n return dp[n][5]", "slug": "count-sorted-vowel-strings", "post_title": "\u2705 Python 4 approaches (DP, Maths)", "user": "constantine786", "upvotes": 45, "views": 3200, "problem_title": "count sorted vowel strings", "number": 1641, "acceptance": 0.772, "difficulty": "Medium", "__index_level_0__": 23816, "question": "Given an integer n, return the number of strings of length n that consist only of vowels (a, e, i, o, u) and are lexicographically sorted.\nA string s is lexicographically sorted if for all valid i, s[i] is the same as or comes before s[i+1] in the alphabet.\n Example 1:\nInput: n = 1\nOutput: 5\nExplanation: The 5 sorted strings that consist of vowels only are [\"a\",\"e\",\"i\",\"o\",\"u\"].\nExample 2:\nInput: n = 2\nOutput: 15\nExplanation: The 15 sorted strings that consist of vowels only are\n[\"aa\",\"ae\",\"ai\",\"ao\",\"au\",\"ee\",\"ei\",\"eo\",\"eu\",\"ii\",\"io\",\"iu\",\"oo\",\"ou\",\"uu\"].\nNote that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.\nExample 3:\nInput: n = 33\nOutput: 66045\n Constraints:\n1 <= n <= 50 " }, { "post_href": "https://leetcode.com/problems/furthest-building-you-can-reach/discuss/2176666/Python-or-Min-Heap-or-With-Explanation-or-Easy-to-Understand", "python_solutions": "class Solution:\n def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:\n # prepare: use a min heap to store each difference(climb) between two contiguous buildings\n # strategy: use the ladders for the longest climbs and the bricks for the shortest climbs\n \n min_heap = []\n n = len(heights)\n \n for i in range(n-1):\n climb = heights[i+1] - heights[i]\n \n if climb <= 0:\n continue\n \n # we need to use a ladder or some bricks, always take the ladder at first\n if climb > 0:\n heapq.heappush(min_heap, climb)\n \n # ladders are all in used, find the current shortest climb to use bricks instead!\n if len(min_heap) > ladders:\n # find the current shortest climb to use bricks\n brick_need = heapq.heappop(min_heap)\n bricks -= brick_need\n \n if bricks < 0:\n return i\n \n return n-1", "slug": "furthest-building-you-can-reach", "post_title": "Python | Min Heap | With Explanation | Easy to Understand", "user": "Mikey98", "upvotes": 32, "views": 1800, "problem_title": "furthest building you can reach", "number": 1642, "acceptance": 0.483, "difficulty": "Medium", "__index_level_0__": 23854, "question": "You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.\nYou start your journey from building 0 and move to the next building by possibly using bricks or ladders.\nWhile moving from building i to building i+1 (0-indexed),\nIf the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.\nIf the current building's height is less than the next building's height, you can either use one ladder or (h[i+1] - h[i]) bricks.\nReturn the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.\n Example 1:\nInput: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1\nOutput: 4\nExplanation: Starting at building 0, you can follow these steps:\n- Go to building 1 without using ladders nor bricks since 4 >= 2.\n- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2 < 7.\n- Go to building 3 without using ladders nor bricks since 7 >= 6.\n- Go to building 4 using your only ladder. You must use either bricks or ladders because 6 < 9.\nIt is impossible to go beyond building 4 because you do not have any more bricks or ladders.\nExample 2:\nInput: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2\nOutput: 7\nExample 3:\nInput: heights = [14,3,19,3], bricks = 17, ladders = 0\nOutput: 3\n Constraints:\n1 <= heights.length <= 105\n1 <= heights[i] <= 106\n0 <= bricks <= 109\n0 <= ladders <= heights.length" }, { "post_href": "https://leetcode.com/problems/kth-smallest-instructions/discuss/918429/Python3-greedy", "python_solutions": "class Solution:\n def kthSmallestPath(self, destination: List[int], k: int) -> str:\n m, n = destination # m \"V\" & n \"H\" in total \n ans = \"\"\n while n: \n kk = comb(m+n-1, n-1) # (m+n-1 choose n-1) instructions starting with \"H\" \n if kk >= k: \n ans += \"H\"\n n -= 1\n else: \n ans += \"V\"\n m -= 1\n k -= kk \n return ans + m*\"V\"", "slug": "kth-smallest-instructions", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 5, "views": 286, "problem_title": "kth smallest instructions", "number": 1643, "acceptance": 0.469, "difficulty": "Hard", "__index_level_0__": 23870, "question": "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.\nThe 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).\nMultiple instructions will lead Bob to destination. For example, if destination is (2, 3), both \"HHHVV\" and \"HVHVH\" are valid instructions.\nHowever, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.\nGiven an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.\n Example 1:\nInput: destination = [2,3], k = 1\nOutput: \"HHHVV\"\nExplanation: All the instructions that reach (2, 3) in lexicographic order are as follows:\n[\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].\nExample 2:\nInput: destination = [2,3], k = 2\nOutput: \"HHVHV\"\nExample 3:\nInput: destination = [2,3], k = 3\nOutput: \"HHVVH\"\n Constraints:\ndestination.length == 2\n1 <= row, column <= 15\n1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b." }, { "post_href": "https://leetcode.com/problems/get-maximum-in-generated-array/discuss/1754391/Python-O(1)-solution", "python_solutions": "class Solution:\n def getMaximumGenerated(self, n: int) -> int:\n max_nums = [0, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21]\n return max_nums[n]", "slug": "get-maximum-in-generated-array", "post_title": "Python O(1) solution", "user": "wssx349", "upvotes": 18, "views": 510, "problem_title": "get maximum in generated array", "number": 1646, "acceptance": 0.502, "difficulty": "Easy", "__index_level_0__": 23874, "question": "You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:\nnums[0] = 0\nnums[1] = 1\nnums[2 * i] = nums[i] when 2 <= 2 * i <= n\nnums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n\nReturn the maximum integer in the array nums.\n Example 1:\nInput: n = 7\nOutput: 3\nExplanation: According to the given rules:\n nums[0] = 0\n nums[1] = 1\n nums[(1 * 2) = 2] = nums[1] = 1\n nums[(1 * 2) + 1 = 3] = nums[1] + nums[2] = 1 + 1 = 2\n nums[(2 * 2) = 4] = nums[2] = 1\n nums[(2 * 2) + 1 = 5] = nums[2] + nums[3] = 1 + 2 = 3\n nums[(3 * 2) = 6] = nums[3] = 2\n nums[(3 * 2) + 1 = 7] = nums[3] + nums[4] = 2 + 1 = 3\nHence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.\nExample 2:\nInput: n = 2\nOutput: 1\nExplanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.\nExample 3:\nInput: n = 3\nOutput: 2\nExplanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.\n Constraints:\n0 <= n <= 100" }, { "post_href": "https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/discuss/927527/Python3-most-to-least-frequent-characters", "python_solutions": "class Solution:\n def minDeletions(self, s: str) -> int:\n freq = {} # frequency table \n for c in s: freq[c] = 1 + freq.get(c, 0)\n \n ans = 0\n seen = set()\n for k in sorted(freq.values(), reverse=True): \n while k in seen: \n k -= 1 \n ans += 1\n if k: seen.add(k)\n return ans", "slug": "minimum-deletions-to-make-character-frequencies-unique", "post_title": "[Python3] most to least frequent characters", "user": "ye15", "upvotes": 34, "views": 4100, "problem_title": "minimum deletions to make character frequencies unique", "number": 1647, "acceptance": 0.5920000000000001, "difficulty": "Medium", "__index_level_0__": 23897, "question": "A string s is called good if there are no two different characters in s that have the same frequency.\nGiven a string s, return the minimum number of characters you need to delete to make s good.\nThe frequency of a character in a string is the number of times it appears in the string. For example, in the string \"aab\", the frequency of 'a' is 2, while the frequency of 'b' is 1.\n Example 1:\nInput: s = \"aab\"\nOutput: 0\nExplanation: s is already good.\nExample 2:\nInput: s = \"aaabbbcc\"\nOutput: 2\nExplanation: You can delete two 'b's resulting in the good string \"aaabcc\".\nAnother way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".\nExample 3:\nInput: s = \"ceabaacb\"\nOutput: 2\nExplanation: You can delete both 'c's resulting in the good string \"eabaab\".\nNote that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).\n Constraints:\n1 <= s.length <= 105\ns contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/sell-diminishing-valued-colored-balls/discuss/927674/Python3-Greedy", "python_solutions": "class Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n inventory.sort(reverse=True) # inventory high to low \n inventory += [0]\n ans = 0\n k = 1\n for i in range(len(inventory)-1): \n if inventory[i] > inventory[i+1]: \n if k*(inventory[i] - inventory[i+1]) < orders: \n ans += k*(inventory[i] + inventory[i+1] + 1)*(inventory[i] - inventory[i+1])//2 # arithmic sum \n orders -= k*(inventory[i] - inventory[i+1])\n else: \n q, r = divmod(orders, k)\n ans += k*(2*inventory[i] - q + 1) * q//2 + r*(inventory[i] - q)\n return ans % 1_000_000_007\n k += 1", "slug": "sell-diminishing-valued-colored-balls", "post_title": "[Python3] Greedy", "user": "ye15", "upvotes": 32, "views": 5200, "problem_title": "sell diminishing valued colored balls", "number": 1648, "acceptance": 0.305, "difficulty": "Medium", "__index_level_0__": 23927, "question": "You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.\nThe customer weirdly values the colored balls. Each colored ball's value is the number of balls of that color you currently have in your inventory. For example, if you own 6 yellow balls, the customer would pay 6 for the first yellow ball. After the transaction, there are only 5 yellow balls left, so the next yellow ball is then valued at 5 (i.e., the value of the balls decreases as you sell more to the customer).\nYou are given an integer array, inventory, where inventory[i] represents the number of balls of the ith color that you initially own. You are also given an integer orders, which represents the total number of balls that the customer wants. You can sell the balls in any order.\nReturn the maximum total value that you can attain after selling orders colored balls. As the answer may be too large, return it modulo 109 + 7.\n Example 1:\nInput: inventory = [2,5], orders = 4\nOutput: 14\nExplanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\nThe maximum total value is 2 + 5 + 4 + 3 = 14.\nExample 2:\nInput: inventory = [3,5], orders = 6\nOutput: 19\nExplanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\nThe maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.\n Constraints:\n1 <= inventory.length <= 105\n1 <= inventory[i] <= 109\n1 <= orders <= min(sum(inventory[i]), 109)" }, { "post_href": "https://leetcode.com/problems/defuse-the-bomb/discuss/1903674/Python-Solution", "python_solutions": "class Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n if k == 0:\n return [0] * len(code)\n data = code + code\n result = [sum(data[i + 1: i + 1 + abs(k)]) for i in range(len(code))]\n\t\t# result = []\n # for i in range(len(code)):\n # result.append(sum(data[i + 1: i + 1 + abs(k)]))\n if 0 > k:\n return result[k - 1:] + result[:k - 1]\n return result", "slug": "defuse-the-bomb", "post_title": "Python Solution", "user": "hgalytoby", "upvotes": 2, "views": 142, "problem_title": "defuse the bomb", "number": 1652, "acceptance": 0.612, "difficulty": "Easy", "__index_level_0__": 23933, "question": "You have a bomb to defuse, and your time is running out! Your informer will provide you with a circular array code of length of n and a key k.\nTo decrypt the code, you must replace every number. All the numbers are replaced simultaneously.\nIf k > 0, replace the ith number with the sum of the next k numbers.\nIf k < 0, replace the ith number with the sum of the previous k numbers.\nIf k == 0, replace the ith number with 0.\nAs code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].\nGiven the circular array code and an integer key k, return the decrypted code to defuse the bomb!\n Example 1:\nInput: code = [5,7,1,4], k = 3\nOutput: [12,10,16,13]\nExplanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.\nExample 2:\nInput: code = [1,2,3,4], k = 0\nOutput: [0,0,0,0]\nExplanation: When k is zero, the numbers are replaced by 0. \nExample 3:\nInput: code = [2,4,9,3], k = -2\nOutput: [12,5,6,13]\nExplanation: The decrypted code is [3+9, 2+3, 4+2, 9+4]. Notice that the numbers wrap around again. If k is negative, the sum is of the previous numbers.\n Constraints:\nn == code.length\n1 <= n <= 100\n1 <= code[i] <= 100\n-(n - 1) <= k <= n - 1" }, { "post_href": "https://leetcode.com/problems/minimum-deletions-to-make-string-balanced/discuss/1020107/Python-DP-solution-easy-to-understand", "python_solutions": "class Solution:\n def minimumDeletions(self, s: str) -> int:\n # track the minimum number of deletions to make the current string balanced ending with 'a', 'b'\n end_a, end_b = 0,0 \n for val in s:\n if val == 'a':\n # to end with 'a', nothing to do with previous ending with 'a'\n # to end with 'b', need to delete the current 'a' from previous ending with 'b'\n end_b += 1\n else:\n # to end with 'a', need to delete the current 'b' from previous ending with 'a'\n # to end with 'b', nothing to do, so just pick smaller of end_a, end_b\n end_a, end_b = end_a+1, min(end_a, end_b)\n return min(end_a, end_b)", "slug": "minimum-deletions-to-make-string-balanced", "post_title": "[Python] DP solution easy to understand", "user": "cloverpku", "upvotes": 12, "views": 1100, "problem_title": "minimum deletions to make string balanced", "number": 1653, "acceptance": 0.588, "difficulty": "Medium", "__index_level_0__": 23952, "question": "You are given a string s consisting only of characters 'a' and 'b'.\nYou can delete any number of characters in s to make s balanced. s is balanced if there is no pair of indices (i,j) such that i < j and s[i] = 'b' and s[j]= 'a'.\nReturn the minimum number of deletions needed to make s balanced.\n Example 1:\nInput: s = \"aababbab\"\nOutput: 2\nExplanation: You can either:\nDelete the characters at 0-indexed positions 2 and 6 (\"aababbab\" -> \"aaabbb\"), or\nDelete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").\nExample 2:\nInput: s = \"bbaaaaabb\"\nOutput: 2\nExplanation: The only solution is to delete the first two characters.\n Constraints:\n1 <= s.length <= 105\ns[i] is 'a' or 'b'." }, { "post_href": "https://leetcode.com/problems/minimum-jumps-to-reach-home/discuss/1540090/Simple-BFS-oror-Clean-and-Concise-oror-Well-coded", "python_solutions": "class Solution:\ndef minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n \n forbidden = set(forbidden)\n limit = max(x,max(forbidden))+a+b\n seen = set()\n q = [(0,0,False)]\n while q:\n p,s,isb = q.pop(0)\n if p>limit or p<0 or p in forbidden or (p,isb) in seen:\n continue\n \n if p==x:\n return s\n \n q.append((p+a,s+1,False))\n if not isb:\n q.append((p-b,s+1,True))\n seen.add((p,isb))\n \n return -1", "slug": "minimum-jumps-to-reach-home", "post_title": "\ud83d\udccc\ud83d\udccc Simple BFS || Clean & Concise || Well-coded \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 4, "views": 618, "problem_title": "minimum jumps to reach home", "number": 1654, "acceptance": 0.287, "difficulty": "Medium", "__index_level_0__": 23965, "question": "A certain bug's home is on the x-axis at position x. Help them get there from position 0.\nThe bug jumps according to the following rules:\nIt can jump exactly a positions forward (to the right).\nIt can jump exactly b positions backward (to the left).\nIt cannot jump backward twice in a row.\nIt cannot jump to any forbidden positions.\nThe bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.\nGiven an array of integers forbidden, where forbidden[i] means that the bug cannot jump to the position forbidden[i], and integers a, b, and x, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position x, return -1.\n Example 1:\nInput: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\nOutput: 3\nExplanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.\nExample 2:\nInput: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\nOutput: -1\nExample 3:\nInput: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\nOutput: 2\nExplanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.\n Constraints:\n1 <= forbidden.length <= 1000\n1 <= a, b, forbidden[i] <= 2000\n0 <= x <= 2000\nAll the elements in forbidden are distinct.\nPosition x is not forbidden." }, { "post_href": "https://leetcode.com/problems/distribute-repeating-integers/discuss/1103429/Python3-backtracking", "python_solutions": "class Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n freq = {}\n for x in nums: freq[x] = 1 + freq.get(x, 0)\n \n vals = sorted(freq.values(), reverse=True)\n quantity.sort(reverse=True) # pruning - large values first \n \n def fn(i): \n \"\"\"Return True if possible to distribute quantity[i:] to remaining.\"\"\"\n if i == len(quantity): return True \n seen = set()\n for k in range(len(vals)): \n if vals[k] >= quantity[i] and vals[k] not in seen: \n seen.add(vals[k]) # pruning - unqiue values \n vals[k] -= quantity[i]\n if fn(i+1): return True \n vals[k] += quantity[i] # backtracking\n \n return fn(0)", "slug": "distribute-repeating-integers", "post_title": "[Python3] backtracking", "user": "ye15", "upvotes": 2, "views": 159, "problem_title": "distribute repeating integers", "number": 1655, "acceptance": 0.392, "difficulty": "Hard", "__index_level_0__": 23971, "question": "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:\nThe ith customer gets exactly quantity[i] integers,\nThe integers the ith customer gets are all equal, and\nEvery customer is satisfied.\nReturn true if it is possible to distribute nums according to the above conditions.\n Example 1:\nInput: nums = [1,2,3,4], quantity = [2]\nOutput: false\nExplanation: The 0th customer cannot be given two different integers.\nExample 2:\nInput: nums = [1,2,3,3], quantity = [2]\nOutput: true\nExplanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\nExample 3:\nInput: nums = [1,1,2,2], quantity = [2,2]\nOutput: true\nExplanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n Constraints:\nn == nums.length\n1 <= n <= 105\n1 <= nums[i] <= 1000\nm == quantity.length\n1 <= m <= 10\n1 <= quantity[i] <= 105\nThere are at most 50 unique values in nums." }, { "post_href": "https://leetcode.com/problems/determine-if-two-strings-are-close/discuss/935962/Python3-2-line-via-counter", "python_solutions": "class Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n cnt1, cnt2 = Counter(word1), Counter(word2)\n return cnt1.keys() == cnt2.keys() and sorted(cnt1.values()) == sorted(cnt2.values())", "slug": "determine-if-two-strings-are-close", "post_title": "[Python3] 2-line via counter", "user": "ye15", "upvotes": 2, "views": 112, "problem_title": "determine if two strings are close", "number": 1657, "acceptance": 0.541, "difficulty": "Medium", "__index_level_0__": 23973, "question": "Two strings are considered close if you can attain one from the other using the following operations:\nOperation 1: Swap any two existing characters.\nFor example, abcde -> aecdb\nOperation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.\nFor example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)\nYou can use the operations on either string as many times as necessary.\nGiven two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.\n Example 1:\nInput: word1 = \"abc\", word2 = \"bca\"\nOutput: true\nExplanation: You can attain word2 from word1 in 2 operations.\nApply Operation 1: \"abc\" -> \"acb\"\nApply Operation 1: \"acb\" -> \"bca\"\nExample 2:\nInput: word1 = \"a\", word2 = \"aa\"\nOutput: false\nExplanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.\nExample 3:\nInput: word1 = \"cabbba\", word2 = \"abbccc\"\nOutput: true\nExplanation: You can attain word2 from word1 in 3 operations.\nApply Operation 1: \"cabbba\" -> \"caabbb\"\nApply Operation 2: \"caabbb\" -> \"baaccc\"\nApply Operation 2: \"baaccc\" -> \"abbccc\"\n Constraints:\n1 <= word1.length, word2.length <= 105\nword1 and word2 contain only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/935986/Python3-O(N)-hash-table-of-prefix", "python_solutions": "class Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n mp = {0: 0}\n prefix = 0\n for i, num in enumerate(nums, 1): \n prefix += num\n mp[prefix] = i \n \n ans = mp.get(x, inf)\n for i, num in enumerate(reversed(nums), 1): \n x -= num\n if x in mp and mp[x] + i <= len(nums): ans = min(ans, i + mp[x])\n return ans if ans < inf else -1", "slug": "minimum-operations-to-reduce-x-to-zero", "post_title": "[Python3] O(N) hash table of prefix", "user": "ye15", "upvotes": 21, "views": 1600, "problem_title": "minimum operations to reduce x to zero", "number": 1658, "acceptance": 0.376, "difficulty": "Medium", "__index_level_0__": 23983, "question": "You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.\nReturn the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.\n Example 1:\nInput: nums = [1,1,4,2,3], x = 5\nOutput: 2\nExplanation: The optimal solution is to remove the last two elements to reduce x to zero.\nExample 2:\nInput: nums = [5,6,7,8,9], x = 4\nOutput: -1\nExample 3:\nInput: nums = [3,2,20,1,1,3], x = 10\nOutput: 5\nExplanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 104\n1 <= x <= 109" }, { "post_href": "https://leetcode.com/problems/maximize-grid-happiness/discuss/1132982/Python3-top-down-dp", "python_solutions": "class Solution:\n def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:\n \n @cache\n def fn(prev, i, j, intro, extro): \n \"\"\"Return max grid happiness at (i, j).\"\"\"\n if i == m: return 0 # no more position\n if j == n: return fn(prev, i+1, 0, intro, extro)\n if intro == extro == 0: return 0 \n \n prev0 = prev[:j] + (0,) + prev[j+1:]\n ans = fn(prev0, i, j+1, intro, extro)\n if intro: \n val = 120 \n if i and prev[j]: # neighbor from above \n val -= 30 \n if prev[j] == 1: val -= 30 \n else: val += 20 \n if j and prev[j-1]: # neighbor from left \n val -= 30 \n if prev[j-1] == 1: val -= 30 \n else: val += 20 \n prev0 = prev[:j] + (1,) + prev[j+1:]\n ans = max(ans, val + fn(prev0, i, j+1, intro-1, extro))\n if extro: \n val = 40 \n if i and prev[j]: \n val += 20 \n if prev[j] == 1: val -= 30 \n else: val += 20 \n if j and prev[j-1]: \n val += 20 \n if prev[j-1] == 1: val -= 30 \n else: val += 20 \n prev0 = prev[:j] + (2,) + prev[j+1:]\n ans = max(ans, val + fn(prev0, i, j+1, intro, extro-1))\n return ans \n \n return fn((0,)*n, 0, 0, introvertsCount, extrovertsCount)", "slug": "maximize-grid-happiness", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 1, "views": 319, "problem_title": "maximize grid happiness", "number": 1659, "acceptance": 0.384, "difficulty": "Hard", "__index_level_0__": 23992, "question": "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.\nYou should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.\nThe happiness of each person is calculated as follows:\nIntroverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).\nExtroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).\nNeighbors live in the directly adjacent cells north, east, south, and west of a person's cell.\nThe grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.\n Example 1:\nInput: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\nOutput: 240\nExplanation: Assume the grid is 1-indexed with coordinates (row, column).\nWe can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120\n- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\n- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60\nThe grid happiness is 120 + 60 + 60 = 240.\nThe above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.\nExample 2:\nInput: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\nOutput: 260\nExplanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\nThe grid happiness is 90 + 80 + 90 = 260.\nExample 3:\nInput: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\nOutput: 240\n Constraints:\n1 <= m, n <= 5\n0 <= introvertsCount, extrovertsCount <= min(m * n, 6)" }, { "post_href": "https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/discuss/944697/Python-3-or-Python-1-liner-or-No-explanation", "python_solutions": "class Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n return ''.join(word1) == ''.join(word2)", "slug": "check-if-two-string-arrays-are-equivalent", "post_title": "Python 3 | Python 1-liner | No explanation \ud83d\ude04", "user": "idontknoooo", "upvotes": 15, "views": 1200, "problem_title": "check if two string arrays are equivalent", "number": 1662, "acceptance": 0.833, "difficulty": "Easy", "__index_level_0__": 23993, "question": "Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.\nA string is represented by an array if the array elements concatenated in order forms the string.\n Example 1:\nInput: word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\nOutput: true\nExplanation:\nword1 represents string \"ab\" + \"c\" -> \"abc\"\nword2 represents string \"a\" + \"bc\" -> \"abc\"\nThe strings are the same, so return true.\nExample 2:\nInput: word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\nOutput: false\nExample 3:\nInput: word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\nOutput: true\n Constraints:\n1 <= word1.length, word2.length <= 103\n1 <= word1[i].length, word2[i].length <= 103\n1 <= sum(word1[i].length), sum(word2[i].length) <= 103\nword1[i] and word2[i] consist of lowercase letters." }, { "post_href": "https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/discuss/1871793/Python3-GREEDY-FILLING-()-Explained", "python_solutions": "class Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n res, k, i = ['a'] * n, k - n, n - 1\n while k:\n k += 1\n if k/26 >= 1:\n res[i], k, i = 'z', k - 26, i - 1\n else:\n res[i], k = chr(k + 96), 0\n\n return ''.join(res)", "slug": "smallest-string-with-a-given-numeric-value", "post_title": "\u2714\ufe0f [Python3] GREEDY FILLING (\ud83c\udf38\u00ac\u203f\u00ac), Explained", "user": "artod", "upvotes": 56, "views": 2900, "problem_title": "smallest string with a given numeric value", "number": 1663, "acceptance": 0.6679999999999999, "difficulty": "Medium", "__index_level_0__": 24045, "question": "The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.\nThe numeric value of a string consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string \"abe\" is equal to 1 + 2 + 5 = 8.\nYou are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.\nNote that a string x is lexicographically smaller than string y if x comes before y in dictionary order, that is, either x is a prefix of y, or if i is the first position such that x[i] != y[i], then x[i] comes before y[i] in alphabetic order.\n Example 1:\nInput: n = 3, k = 27\nOutput: \"aay\"\nExplanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.\nExample 2:\nInput: n = 5, k = 73\nOutput: \"aaszz\"\n Constraints:\n1 <= n <= 105\nn <= k <= 26 * n" }, { "post_href": "https://leetcode.com/problems/ways-to-make-a-fair-array/discuss/1775588/WEEB-EXPLAINS-PYTHONC%2B%2B-DPPREFIX-SUM-SOLN", "python_solutions": "class Solution:\n\tdef waysToMakeFair(self, nums: List[int]) -> int:\n\t\tif len(nums) == 1:\n\t\t\treturn 1\n\n\t\tif len(nums) == 2:\n\t\t\treturn 0\n\n\t\tprefixEven = sum(nums[2::2])\n\t\tprefixOdd = sum(nums[1::2])\n\t\tresult = 0\n\n\t\tif prefixEven == prefixOdd and len(set(nums)) == 1:\n\t\t\tresult += 1\n\n\t\tfor i in range(1,len(nums)):\n\t\t\tif i == 1:\n\t\t\t\tprefixOdd, prefixEven = prefixEven, prefixOdd \n\n\t\t\tif i > 1:\n\t\t\t\tif i % 2 == 0:\n\t\t\t\t\tprefixEven -= nums[i-1]\n\t\t\t\t\tprefixEven += nums[i-2]\n\n\t\t\t\telse:\n\t\t\t\t\tprefixOdd -= nums[i-1]\n\t\t\t\t\tprefixOdd += nums[i-2]\n\n\t\t\tif prefixOdd == prefixEven:\n\t\t\t\tresult += 1\n\n\t\treturn result", "slug": "ways-to-make-a-fair-array", "post_title": "WEEB EXPLAINS PYTHON/C++ DP/PREFIX SUM SOLN", "user": "Skywalker5423", "upvotes": 6, "views": 264, "problem_title": "ways to make a fair array", "number": 1664, "acceptance": 0.635, "difficulty": "Medium", "__index_level_0__": 24088, "question": "You are given an integer array nums. You can choose exactly one index (0-indexed) and remove the element. Notice that the index of the elements may change after the removal.\nFor example, if nums = [6,1,7,4,1]:\nChoosing to remove index 1 results in nums = [6,7,4,1].\nChoosing to remove index 2 results in nums = [6,1,4,1].\nChoosing to remove index 4 results in nums = [6,1,7,4].\nAn array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.\nReturn the number of indices that you could choose such that after the removal, nums is fair.\n Example 1:\nInput: nums = [2,1,6,4]\nOutput: 1\nExplanation:\nRemove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\nRemove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\nRemove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\nRemove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\nThere is 1 index that you can remove to make nums fair.\nExample 2:\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can remove any index and the remaining array is fair.\nExample 3:\nInput: nums = [1,2,3]\nOutput: 0\nExplanation: You cannot make a fair array after removing any index.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-initial-energy-to-finish-tasks/discuss/944714/Python-3-or-Sort-%2B-Greedy-and-Sort-%2B-Binary-Search-or-Explanation", "python_solutions": "class Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key=lambda x: x[0]-x[1])\n def ok(mid):\n for actual, minimum in tasks:\n if minimum > mid or actual > mid: return False\n if minimum <= mid: mid -= actual\n return True\n l, r = 0, 10 ** 9\n while l <= r:\n mid = (l+r) // 2\n if ok(mid): r = mid - 1\n else: l = mid + 1\n return l", "slug": "minimum-initial-energy-to-finish-tasks", "post_title": "Python 3 | Sort + Greedy & Sort + Binary Search | Explanation", "user": "idontknoooo", "upvotes": 2, "views": 173, "problem_title": "minimum initial energy to finish tasks", "number": 1665, "acceptance": 0.562, "difficulty": "Hard", "__index_level_0__": 24100, "question": "You are given an array tasks where tasks[i] = [actuali, minimumi]:\nactuali is the actual amount of energy you spend to finish the ith task.\nminimumi is the minimum amount of energy you require to begin the ith task.\nFor example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.\nYou can finish the tasks in any order you like.\nReturn the minimum initial amount of energy you will need to finish all the tasks.\n Example 1:\nInput: tasks = [[1,2],[2,4],[4,8]]\nOutput: 8\nExplanation:\nStarting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\nNotice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\nExample 2:\nInput: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\nOutput: 32\nExplanation:\nStarting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.\nExample 3:\nInput: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\nOutput: 27\nExplanation:\nStarting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 2nd task. Now energy = 22 - 2 = 20.\n - 3rd task. Now energy = 20 - 3 = 17.\n - 1st task. Now energy = 17 - 1 = 16.\n - 4th task. Now energy = 16 - 4 = 12.\n - 6th task. Now energy = 12 - 6 = 6.\n Constraints:\n1 <= tasks.length <= 105\n1 <= actuali <= minimumi <= 104" }, { "post_href": "https://leetcode.com/problems/maximum-repeating-substring/discuss/1400359/Python3-Simple-Solution", "python_solutions": "class Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n i = 0\n while word*(i+1) in sequence:\n i+=1\n return i", "slug": "maximum-repeating-substring", "post_title": "Python3, Simple Solution", "user": "Flerup", "upvotes": 4, "views": 306, "problem_title": "maximum repeating substring", "number": 1668, "acceptance": 0.396, "difficulty": "Easy", "__index_level_0__": 24110, "question": "For a string sequence, a string word is k-repeating if word concatenated k times is a substring of sequence. The word's maximum k-repeating value is the highest value k where word is k-repeating in sequence. If word is not a substring of sequence, word's maximum k-repeating value is 0.\nGiven strings sequence and word, return the maximum k-repeating value of word in sequence.\n Example 1:\nInput: sequence = \"ababc\", word = \"ab\"\nOutput: 2\nExplanation: \"abab\" is a substring in \"ababc\".\nExample 2:\nInput: sequence = \"ababc\", word = \"ba\"\nOutput: 1\nExplanation: \"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".\nExample 3:\nInput: sequence = \"ababc\", word = \"ac\"\nOutput: 0\nExplanation: \"ac\" is not a substring in \"ababc\". \n Constraints:\n1 <= sequence.length <= 100\n1 <= word.length <= 100\nsequence and word contains only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/merge-in-between-linked-lists/discuss/1833998/Python3-oror-Explanation-and-Example", "python_solutions": "class Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n curr=list1\n for count in range(b):\n if count==a-1: # travel to a node and --> step 1\n start=curr # then save pointer in start\n curr=curr.next # continue travel to b node --> step 2\n start.next=list2 # point start to list2 --> step3\n while list2.next: # travel list2 --> step 4\n list2=list2.next\n list2.next=curr.next # map end of list2 to b\n return list1", "slug": "merge-in-between-linked-lists", "post_title": "Python3 || Explanation & Example", "user": "rushi_javiya", "upvotes": 2, "views": 48, "problem_title": "merge in between linked lists", "number": 1669, "acceptance": 0.745, "difficulty": "Medium", "__index_level_0__": 24129, "question": "You are given two linked lists: list1 and list2 of sizes n and m respectively.\nRemove list1's nodes from the ath node to the bth node, and put list2 in their place.\nThe blue edges and nodes in the following figure indicate the result:\nBuild the result list and return its head.\n Example 1:\nInput: list1 = [10,1,13,6,9,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\nOutput: [10,1,13,1000000,1000001,1000002,5]\nExplanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.\nExample 2:\nInput: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\nOutput: [0,1,1000000,1000001,1000002,1000003,1000004,6]\nExplanation: The blue edges and nodes in the above figure indicate the result.\n Constraints:\n3 <= list1.length <= 104\n1 <= a <= b < list1.length - 1\n1 <= list2.length <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/discuss/1543614/Python-oror-Easy-Solution", "python_solutions": "class Solution:\n\tdef minimumMountainRemovals(self, lst: List[int]) -> int:\n\t\tl = len(lst)\n\t\tdp = [0] * l\n\t\tdp1 = [0] * l\n\n\t\tfor i in range(l): # for increasing subsequence\n\t\t\tmaxi = 0\n\t\t\tfor j in range(i):\n\t\t\t\tif lst[i] > lst[j]:\n\t\t\t\t\tif dp[j] > maxi:\n\t\t\t\t\t\tmaxi = dp[j]\n\n\t\t\tdp[i] = maxi + 1\n\n\t\tfor i in range(l - 1, -1, -1): # for decreasing subsequence\n\t\t\tmaxi1 = 0\n\t\t\tfor j in range(l - 1, i, -1):\n\t\t\t\tif lst[i] > lst[j]:\n\t\t\t\t\tif dp1[j] > maxi1:\n\t\t\t\t\t\tmaxi1 = dp1[j]\n\n\t\t\tdp1[i] = maxi1 + 1\n\n\t\tans = 0\n\t\tfor i in range(l):\n\t\t\tif dp[i] > 1 and dp1[i] > 1:\n\t\t\t\ttemp = dp[i] + dp1[i] - 1\n\t\t\t\tif temp > ans:\n\t\t\t\t\tans = temp\n\n\t\treturn l - ans", "slug": "minimum-number-of-removals-to-make-mountain-array", "post_title": "Python || Easy Solution", "user": "naveenrathore", "upvotes": 2, "views": 209, "problem_title": "minimum number of removals to make mountain array", "number": 1671, "acceptance": 0.425, "difficulty": "Hard", "__index_level_0__": 24141, "question": "You may recall that an array arr is a mountain array if and only if:\narr.length >= 3\nThere exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:\narr[0] < arr[1] < ... < arr[i - 1] < arr[i]\narr[i] > arr[i + 1] > ... > arr[arr.length - 1]\nGiven an integer array nums, return the minimum number of elements to remove to make nums a mountain array.\n Example 1:\nInput: nums = [1,3,1]\nOutput: 0\nExplanation: The array itself is a mountain array so we do not need to remove any elements.\nExample 2:\nInput: nums = [2,1,1,5,6,2,3,1]\nOutput: 3\nExplanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n Constraints:\n3 <= nums.length <= 1000\n1 <= nums[i] <= 109\nIt is guaranteed that you can make a mountain array out of nums." }, { "post_href": "https://leetcode.com/problems/richest-customer-wealth/discuss/2675823/Python-or-1-liner-simple-solution", "python_solutions": "class Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n return max([sum(acc) for acc in accounts])", "slug": "richest-customer-wealth", "post_title": "Python | 1-liner simple solution", "user": "LordVader1", "upvotes": 36, "views": 2200, "problem_title": "richest customer wealth", "number": 1672, "acceptance": 0.882, "difficulty": "Easy", "__index_level_0__": 24144, "question": "You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the ith customer has in the jth bank. Return the wealth that the richest customer has.\nA customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth.\n Example 1:\nInput: accounts = [[1,2,3],[3,2,1]]\nOutput: 6\nExplanation:\n1st customer has wealth = 1 + 2 + 3 = 6\n2nd customer has wealth = 3 + 2 + 1 = 6\nBoth customers are considered the richest with a wealth of 6 each, so return 6.\nExample 2:\nInput: accounts = [[1,5],[7,3],[3,5]]\nOutput: 10\nExplanation: \n1st customer has wealth = 6\n2nd customer has wealth = 10 \n3rd customer has wealth = 8\nThe 2nd customer is the richest with a wealth of 10.\nExample 3:\nInput: accounts = [[2,8,7],[7,1,3],[1,9,5]]\nOutput: 17\n Constraints:\nm == accounts.length\nn == accounts[i].length\n1 <= m, n <= 50\n1 <= accounts[i][j] <= 100" }, { "post_href": "https://leetcode.com/problems/find-the-most-competitive-subsequence/discuss/953711/Python3-greedy-O(N)", "python_solutions": "class Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stack = [] # (increasing) mono-stack \n for i, x in enumerate(nums): \n while stack and stack[-1] > x and len(stack) + len(nums) - i > k: stack.pop()\n if len(stack) < k: stack.append(x)\n return stack", "slug": "find-the-most-competitive-subsequence", "post_title": "[Python3] greedy O(N)", "user": "ye15", "upvotes": 6, "views": 342, "problem_title": "find the most competitive subsequence", "number": 1673, "acceptance": 0.493, "difficulty": "Medium", "__index_level_0__": 24193, "question": "Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.\nAn array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.\nWe define that a subsequence a is more competitive than a subsequence b (of the same length) if in the first position where a and b differ, subsequence a has a number less than the corresponding number in b. For example, [1,3,4] is more competitive than [1,3,5] because the first position they differ is at the final number, and 4 is less than 5.\n Example 1:\nInput: nums = [3,5,2,6], k = 2\nOutput: [2,6]\nExplanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.\nExample 2:\nInput: nums = [2,4,3,3,5,4,9,6], k = 4\nOutput: [2,3,3,4]\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109\n1 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/minimum-moves-to-make-array-complementary/discuss/1650877/Sweep-Algorithm-or-Explained-Python", "python_solutions": "class Solution: \n def minMoves(self, nums: List[int], limit: int) -> int:\n n = len(nums)\n overlay_arr = [0] * (2*limit+2)\n for i in range(n//2):\n left_boundary = min(nums[i], nums[n-1-i]) + 1\n no_move_value = nums[i] + nums[n-1-i]\n right_boundary = max(nums[i], nums[n-1-i]) + limit\n overlay_arr[left_boundary] -= 1\n overlay_arr[no_move_value] -= 1\n overlay_arr[no_move_value+1] += 1\n overlay_arr[right_boundary+1] += 1\n curr_moves = n #initial assumption of two moves for each pair\n res = float(\"inf\")\n\t\t# start Sweeping\n for i in range(2, 2*limit+1):\n curr_moves += overlay_arr[i]\n res = min(res, curr_moves)\n return res", "slug": "minimum-moves-to-make-array-complementary", "post_title": "Sweep Algorithm | Explained [Python]", "user": "xyz76", "upvotes": 5, "views": 397, "problem_title": "minimum moves to make array complementary", "number": 1674, "acceptance": 0.386, "difficulty": "Medium", "__index_level_0__": 24201, "question": "You are given an integer array nums of even length n and an integer limit. In one move, you can replace any integer from nums with another integer between 1 and limit, inclusive.\nThe array nums is complementary if for all indices i (0-indexed), nums[i] + nums[n - 1 - i] equals the same number. For example, the array [1,2,3,4] is complementary because for all indices i, nums[i] + nums[n - 1 - i] = 5.\nReturn the minimum number of moves required to make nums complementary.\n Example 1:\nInput: nums = [1,2,4,3], limit = 4\nOutput: 1\nExplanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\nnums[0] + nums[3] = 1 + 3 = 4.\nnums[1] + nums[2] = 2 + 2 = 4.\nnums[2] + nums[1] = 2 + 2 = 4.\nnums[3] + nums[0] = 3 + 1 = 4.\nTherefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.\nExample 2:\nInput: nums = [1,2,2,1], limit = 2\nOutput: 2\nExplanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.\nExample 3:\nInput: nums = [1,2,1,2], limit = 2\nOutput: 0\nExplanation: nums is already complementary.\n Constraints:\nn == nums.length\n2 <= n <= 105\n1 <= nums[i] <= limit <= 105\nn is even." }, { "post_href": "https://leetcode.com/problems/minimize-deviation-in-array/discuss/1782626/Python-Simple-Python-Solution-By-SortedList", "python_solutions": "class Solution:\n\tdef minimumDeviation(self, nums: List[int]) -> int:\n\n\t\tfrom sortedcontainers import SortedList\n\n\t\tfor i in range(len(nums)):\n\n\t\t\tif nums[i]%2!=0:\n\t\t\t\tnums[i]=nums[i]*2\n\n\t\tnums = SortedList(nums)\n\n\t\tresult = 100000000000\n\n\t\twhile True:\n\t\t\tmin_value = nums[0]\n\t\t\tmax_value = nums[-1]\n\n\t\t\tif max_value % 2 == 0:\n\t\t\t\tnums.pop()\n\t\t\t\tnums.add(max_value // 2)\n\t\t\t\tmax_value = nums[-1]\n\t\t\t\tmin_value = nums[0]\n\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\telse:\n\t\t\t\tresult = min(result , max_value - min_value)\n\t\t\t\tbreak\n\n\t\treturn result", "slug": "minimize-deviation-in-array", "post_title": "[ Python ] \u2714\u2714 Simple Python Solution By SortedList \ud83d\udd25\u270c", "user": "ASHOK_KUMAR_MEGHVANSHI", "upvotes": 10, "views": 563, "problem_title": "minimize deviation in array", "number": 1675, "acceptance": 0.52, "difficulty": "Hard", "__index_level_0__": 24204, "question": "You are given an array nums of n positive integers.\nYou can perform two types of operations on any element of the array any number of times:\nIf the element is even, divide it by 2.\nFor 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].\nIf the element is odd, multiply it by 2.\nFor 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].\nThe deviation of the array is the maximum difference between any two elements in the array.\nReturn the minimum deviation the array can have after performing some number of operations.\n Example 1:\nInput: nums = [1,2,3,4]\nOutput: 1\nExplanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\nExample 2:\nInput: nums = [4,1,5,20,3]\nOutput: 3\nExplanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\nExample 3:\nInput: nums = [2,10,8]\nOutput: 3\n Constraints:\nn == nums.length\n2 <= n <= 5 * 104\n1 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/goal-parser-interpretation/discuss/961441/Python-one-liner", "python_solutions": "class Solution:\n def interpret(self, command: str) -> str:\n return command.replace('()','o').replace('(al)','al')", "slug": "goal-parser-interpretation", "post_title": "Python one-liner", "user": "lokeshsenthilkumar", "upvotes": 92, "views": 8000, "problem_title": "goal parser interpretation", "number": 1678, "acceptance": 0.861, "difficulty": "Easy", "__index_level_0__": 24208, "question": "You own a Goal Parser that can interpret a string command. The command consists of an alphabet of \"G\", \"()\" and/or \"(al)\" in some order. The Goal Parser will interpret \"G\" as the string \"G\", \"()\" as the string \"o\", and \"(al)\" as the string \"al\". The interpreted strings are then concatenated in the original order.\nGiven the string command, return the Goal Parser's interpretation of command.\n Example 1:\nInput: command = \"G()(al)\"\nOutput: \"Goal\"\nExplanation: The Goal Parser interprets the command as follows:\nG -> G\n() -> o\n(al) -> al\nThe final concatenated result is \"Goal\".\nExample 2:\nInput: command = \"G()()()()(al)\"\nOutput: \"Gooooal\"\nExample 3:\nInput: command = \"(al)G(al)()()G\"\nOutput: \"alGalooG\"\n Constraints:\n1 <= command.length <= 100\ncommand consists of \"G\", \"()\", and/or \"(al)\" in some order." }, { "post_href": "https://leetcode.com/problems/max-number-of-k-sum-pairs/discuss/2005867/Python-Simple-One-Pass", "python_solutions": "class Solution:\n def maxOperations(self, nums: List[int], k: int) -> int:\n counter = defaultdict(int)\n \n count = 0\n for x in nums:\n comp = k - x\n if counter[comp]>0:\n counter[comp]-=1\n count+=1\n else:\n counter[x] +=1\n \n return count", "slug": "max-number-of-k-sum-pairs", "post_title": "Python Simple One Pass", "user": "constantine786", "upvotes": 2, "views": 181, "problem_title": "max number of k sum pairs", "number": 1679, "acceptance": 0.573, "difficulty": "Medium", "__index_level_0__": 24253, "question": "You are given an integer array nums and an integer k.\nIn one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.\nReturn the maximum number of operations you can perform on the array.\n Example 1:\nInput: nums = [1,2,3,4], k = 5\nOutput: 2\nExplanation: Starting with nums = [1,2,3,4]:\n- Remove numbers 1 and 4, then nums = [2,3]\n- Remove numbers 2 and 3, then nums = []\nThere are no more pairs that sum up to 5, hence a total of 2 operations.\nExample 2:\nInput: nums = [3,1,3,4,3], k = 6\nOutput: 1\nExplanation: Starting with nums = [3,1,3,4,3]:\n- Remove the first two 3's, then nums = [1,4,3]\nThere are no more pairs that sum up to 6, hence a total of 1 operation.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/discuss/2612717/python-one-line-solution-94-beats", "python_solutions": "class Solution:\n def concatenatedBinary(self, n: int) -> int:\n return int(\"\".join([bin(i)[2:] for i in range(1,n+1)]),2)%(10**9+7)", "slug": "concatenation-of-consecutive-binary-numbers", "post_title": "python one line solution 94% beats", "user": "benon", "upvotes": 5, "views": 677, "problem_title": "concatenation of consecutive binary numbers", "number": 1680, "acceptance": 0.57, "difficulty": "Medium", "__index_level_0__": 24298, "question": "Given an integer n, return the decimal value of the binary string formed by concatenating the binary representations of 1 to n in order, modulo 109 + 7.\n Example 1:\nInput: n = 1\nOutput: 1\nExplanation: \"1\" in binary corresponds to the decimal value 1. \nExample 2:\nInput: n = 3\nOutput: 27\nExplanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\nAfter concatenating them, we have \"11011\", which corresponds to the decimal value 27.\nExample 3:\nInput: n = 12\nOutput: 505379714\nExplanation: The concatenation results in \"1101110010111011110001001101010111100\".\nThe decimal value of that is 118505380540.\nAfter modulo 109 + 7, the result is 505379714.\n Constraints:\n1 <= n <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-incompatibility/discuss/965262/Python3-backtracking", "python_solutions": "class Solution:\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n nums.sort()\n \n def fn(i, cand): \n \"\"\"Populate stack and compute minimum incompatibility.\"\"\"\n nonlocal ans \n if cand + len(nums) - i - sum(not x for x in stack) > ans: return \n if i == len(nums): ans = cand\n else: \n for ii in range(k): \n if len(stack[ii]) < len(nums)//k and (not stack[ii] or stack[ii][-1] != nums[i]) and (not ii or stack[ii-1] != stack[ii]): \n stack[ii].append(nums[i])\n if len(stack[ii]) == 1: fn(i+1, cand)\n else: fn(i+1, cand + stack[ii][-1] - stack[ii][-2])\n stack[ii].pop()\n \n ans = inf\n stack = [[] for _ in range(k)]\n fn(0, 0)\n return ans if ans < inf else -1", "slug": "minimum-incompatibility", "post_title": "[Python3] backtracking", "user": "ye15", "upvotes": 3, "views": 156, "problem_title": "minimum incompatibility", "number": 1681, "acceptance": 0.374, "difficulty": "Hard", "__index_level_0__": 24343, "question": "You are given an integer array nums 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.\nA subset's incompatibility is the difference between the maximum and minimum elements in that array.\nReturn the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.\nA subset is a group integers that appear in the array with no particular order.\n Example 1:\nInput: nums = [1,2,1,4], k = 2\nOutput: 4\nExplanation: The optimal distribution of subsets is [1,2] and [1,4].\nThe incompatibility is (2-1) + (4-1) = 4.\nNote that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\nExample 2:\nInput: nums = [6,3,8,1,3,1,2,2], k = 4\nOutput: 6\nExplanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\nThe incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\nExample 3:\nInput: nums = [5,3,3,6,3,3], k = 3\nOutput: -1\nExplanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n Constraints:\n1 <= k <= nums.length <= 16\nnums.length is divisible by k\n1 <= nums[i] <= nums.length" }, { "post_href": "https://leetcode.com/problems/count-the-number-of-consistent-strings/discuss/1054303/Python-simple-one-liner", "python_solutions": "class Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n return sum(set(allowed) >= set(i) for i in words)", "slug": "count-the-number-of-consistent-strings", "post_title": "Python - simple one liner", "user": "angelique_", "upvotes": 12, "views": 828, "problem_title": "count the number of consistent strings", "number": 1684, "acceptance": 0.8190000000000001, "difficulty": "Easy", "__index_level_0__": 24347, "question": "You are given a string allowed consisting of distinct characters and an array of strings words. A string is consistent if all characters in the string appear in the string allowed.\nReturn the number of consistent strings in the array words.\n Example 1:\nInput: allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]\nOutput: 2\nExplanation: Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.\nExample 2:\nInput: allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]\nOutput: 7\nExplanation: All strings are consistent.\nExample 3:\nInput: allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]\nOutput: 4\nExplanation: Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.\n Constraints:\n1 <= words.length <= 104\n1 <= allowed.length <= 26\n1 <= words[i].length <= 10\nThe characters in allowed are distinct.\nwords[i] and allowed contain only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array/discuss/1439047/Python-3-or-O(N)-Prefix-Sum-Clean-or-Explanation", "python_solutions": "class Solution:\n def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:\n pre_sum = [0]\n for num in nums: # calculate prefix sum\n pre_sum.append(pre_sum[-1] + num)\n n = len(nums) # render the output\n return [(num*(i+1) - pre_sum[i+1]) + (pre_sum[-1]-pre_sum[i] - (n-i)*num) for i, num in enumerate(nums)]", "slug": "sum-of-absolute-differences-in-a-sorted-array", "post_title": "Python 3 | O(N), Prefix Sum, Clean | Explanation", "user": "idontknoooo", "upvotes": 3, "views": 327, "problem_title": "sum of absolute differences in a sorted array", "number": 1685, "acceptance": 0.649, "difficulty": "Medium", "__index_level_0__": 24396, "question": "You are given an integer array nums sorted in non-decreasing order.\nBuild and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.\nIn other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).\n Example 1:\nInput: nums = [2,3,5]\nOutput: [4,3,5]\nExplanation: Assuming the arrays are 0-indexed, then\nresult[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\nresult[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\nresult[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.\nExample 2:\nInput: nums = [1,4,6,8,10]\nOutput: [24,15,13,15,21]\n Constraints:\n2 <= nums.length <= 105\n1 <= nums[i] <= nums[i + 1] <= 104" }, { "post_href": "https://leetcode.com/problems/stone-game-vi/discuss/1860830/python-easy-solution-using-sort", "python_solutions": "class Solution:\n def stoneGameVI(self, alice: List[int], bob: List[int]) -> int:\n n = len(alice)\n arr = [alice[i] + bob[i] for i in range(n)]\n s = sum(bob)\n res = 0\n k = (n+1)//2\n arr.sort(reverse=True)\n for i in range(0, n, 2):\n res += arr[i]\n \n \n if res > s:\n return 1\n elif res == s:\n return 0 \n else:\n return -1", "slug": "stone-game-vi", "post_title": "python easy solution using sort", "user": "byuns9334", "upvotes": 0, "views": 85, "problem_title": "stone game vi", "number": 1686, "acceptance": 0.544, "difficulty": "Medium", "__index_level_0__": 24408, "question": "Alice and Bob take turns playing a game, with Alice starting first.\nThere are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.\nYou are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the ith stone.\nThe winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.\nDetermine the result of the game, and:\nIf Alice wins, return 1.\nIf Bob wins, return -1.\nIf the game results in a draw, return 0.\n Example 1:\nInput: aliceValues = [1,3], bobValues = [2,1]\nOutput: 1\nExplanation:\nIf Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\nBob can only choose stone 0, and will only receive 2 points.\nAlice wins.\nExample 2:\nInput: aliceValues = [1,2], bobValues = [3,1]\nOutput: 0\nExplanation:\nIf Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\nDraw.\nExample 3:\nInput: aliceValues = [2,4,3], bobValues = [1,6,7]\nOutput: -1\nExplanation:\nRegardless of how Alice plays, Bob will be able to have more points than Alice.\nFor example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.\nBob wins.\n Constraints:\nn == aliceValues.length == bobValues.length\n1 <= n <= 105\n1 <= aliceValues[i], bobValues[i] <= 100" }, { "post_href": "https://leetcode.com/problems/delivering-boxes-from-storage-to-ports/discuss/1465884/Python3-dp-%2B-greedy", "python_solutions": "class Solution:\n def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:\n dp = [0] + [inf]*len(boxes)\n trips = 2\n ii = 0\n for i in range(len(boxes)):\n maxWeight -= boxes[i][1]\n if i and boxes[i-1][0] != boxes[i][0]: trips += 1\n while maxBoxes < i - ii + 1 or maxWeight < 0 or ii < i and dp[ii] == dp[ii+1]:\n maxWeight += boxes[ii][1]\n if boxes[ii][0] != boxes[ii+1][0]: trips-=1\n ii += 1\n dp[i+1] = dp[ii] + trips\n return dp[-1]", "slug": "delivering-boxes-from-storage-to-ports", "post_title": "[Python3] dp + greedy", "user": "ye15", "upvotes": 1, "views": 204, "problem_title": "delivering boxes from storage to ports", "number": 1687, "acceptance": 0.385, "difficulty": "Hard", "__index_level_0__": 24410, "question": "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.\nYou are given an array boxes, where boxes[i] = [portsi, weighti], and three integers portsCount, maxBoxes, and maxWeight.\nportsi is the port where you need to deliver the ith box and weightsi is the weight of the ith box.\nportsCount is the number of ports.\nmaxBoxes and maxWeight are the respective box and weight limits of the ship.\nThe boxes need to be delivered in the order they are given. The ship will follow these steps:\nThe ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.\nFor 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.\nThe ship then makes a return trip to storage to take more boxes from the queue.\nThe ship must end at storage after all the boxes have been delivered.\nReturn the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.\n Example 1:\nInput: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\nOutput: 4\nExplanation: The optimal strategy is as follows: \n- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\nSo the total number of trips is 4.\nNote that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\nExample 2:\nInput: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\nOutput: 6\nExplanation: The optimal strategy is as follows: \n- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.\n- The ship takes the fifth box, goes to port 2, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\nExample 3:\nInput: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\nOutput: 6\nExplanation: The optimal strategy is as follows:\n- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.\n- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.\nSo the total number of trips is 2 + 2 + 2 = 6.\n Constraints:\n1 <= boxes.length <= 105\n1 <= portsCount, maxBoxes, maxWeight <= 105\n1 <= portsi <= portsCount\n1 <= weightsi <= maxWeight" }, { "post_href": "https://leetcode.com/problems/count-of-matches-in-tournament/discuss/1276389/simple-python-solution-easy-to-understand", "python_solutions": "class Solution:\n\tdef numberOfMatches(self, n: int) -> int:\n\n\t\t# the logic is, among n teams only 1 team will won, so n-1 teams will lose\n\t\t# hence there will be n-1 match (so that n-1 teams can lose) \n\n\t\treturn n-1", "slug": "count-of-matches-in-tournament", "post_title": "simple python solution-easy to understand", "user": "nandanabhishek", "upvotes": 4, "views": 272, "problem_title": "count of matches in tournament", "number": 1688, "acceptance": 0.8320000000000001, "difficulty": "Easy", "__index_level_0__": 24411, "question": "You are given an integer n, the number of teams in a tournament that has strange rules:\nIf the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round.\nIf the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round.\nReturn the number of matches played in the tournament until a winner is decided.\n Example 1:\nInput: n = 7\nOutput: 6\nExplanation: Details of the tournament: \n- 1st Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 2nd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 3 + 2 + 1 = 6.\nExample 2:\nInput: n = 14\nOutput: 13\nExplanation: Details of the tournament:\n- 1st Round: Teams = 14, Matches = 7, and 7 teams advance.\n- 2nd Round: Teams = 7, Matches = 3, and 4 teams advance.\n- 3rd Round: Teams = 4, Matches = 2, and 2 teams advance.\n- 4th Round: Teams = 2, Matches = 1, and 1 team is declared the winner.\nTotal number of matches = 7 + 3 + 2 + 1 = 13.\n Constraints:\n1 <= n <= 200" }, { "post_href": "https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers/discuss/2202648/C%2B%2BJavaPython-Easy-One-liner-with-explanation", "python_solutions": "class Solution:\n def minPartitions(self, n: str) -> int:\n return int(max(n))", "slug": "partitioning-into-minimum-number-of-deci-binary-numbers", "post_title": "[C++/Java/Python]- Easy One liner with explanation", "user": "constantine786", "upvotes": 52, "views": 3800, "problem_title": "partitioning into minimum number of deci binary numbers", "number": 1689, "acceptance": 0.8959999999999999, "difficulty": "Medium", "__index_level_0__": 24443, "question": "A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.\nGiven a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n.\n Example 1:\nInput: n = \"32\"\nOutput: 3\nExplanation: 10 + 11 + 11 = 32\nExample 2:\nInput: n = \"82734\"\nOutput: 8\nExample 3:\nInput: n = \"27346209830709182346\"\nOutput: 9\n Constraints:\n1 <= n.length <= 105\nn consists of only digits.\nn does not contain any leading zeros and represents a positive integer." }, { "post_href": "https://leetcode.com/problems/stone-game-vii/discuss/971804/Python3-Easy-code-with-explanation-DP", "python_solutions": "class Solution:\n def stoneGameVII(self, stones: List[int]) -> int:\n dp = [[0 for _ in range(len(stones))] for _ in range(len(stones))] # dp table n x n\n run_sum = [0] # running sum -> sum [i..j] = run_sum[j] - run_sum[i]\n s = 0\n \n\t\t## Calculation of running sum\n for i in stones:\n s += i\n run_sum.append(s)\n\t\t\n n = len(stones) \n \n for k in range(1, n): # no. of stones left\n for i in range(0, n - k): # from each starting point\n remove_i_stone = (run_sum[i+k+1] - run_sum[i+1]) # score after removing i th stone\n remove_j_stone = (run_sum[i+k] - run_sum[i]) # score after removing j th stone\n \n if (n-(k+1))%2 == 0: # alice's move \n dp[i][i+k] = max(remove_i_stone + dp[i+1][i+k],\n remove_j_stone + dp[i][i+k-1])\n else: # bob's move\n dp[i][i+k] = min(-remove_i_stone + dp[i+1][i+k],\n - remove_j_stone + dp[i][i+k-1])\n \n return dp[0][n - 1]", "slug": "stone-game-vii", "post_title": "[Python3] Easy code with explanation - DP", "user": "mihirrane", "upvotes": 9, "views": 851, "problem_title": "stone game vii", "number": 1690, "acceptance": 0.586, "difficulty": "Medium", "__index_level_0__": 24486, "question": "Alice and Bob take turns playing a game, with Alice starting first.\nThere are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.\nBob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.\nGiven an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob's score if they both play optimally.\n Example 1:\nInput: stones = [5,3,1,4,2]\nOutput: 6\nExplanation: \n- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].\n- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].\n- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].\n- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].\n- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].\nThe score difference is 18 - 12 = 6.\nExample 2:\nInput: stones = [7,90,5,1,100,10,10,2]\nOutput: 122\n Constraints:\nn == stones.length\n2 <= n <= 1000\n1 <= stones[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/maximum-height-by-stacking-cuboids/discuss/970397/Python-3-or-DP-Sort-O(N2)-or-Explanation", "python_solutions": "class Solution:\n def maxHeight(self, cuboids: List[List[int]]) -> int:\n cuboids = sorted([sorted(cub) for cub in cuboids], reverse=True) # sort LxWxH in cube, then sort cube reversely\n ok = lambda x, y: (x[0] >= y[0] and x[1] >= y[1] and x[2] >= y[2]) # make a lambda function to verify whether y can be put on top of x\n n = len(cuboids)\n dp = [cu[2] for cu in cuboids] # create dp array\n ans = max(dp)\n for i in range(1, n): # iterate over each cube\n for j in range(i): # compare with previous calculated cube\n if ok(cuboids[j], cuboids[i]): # update dp[i] if cube[i] can be put on top of cube[j]\n dp[i] = max(dp[i], dp[j] + cuboids[i][2]) # always get the maximum\n ans = max(ans, dp[i]) # record the largest value\n return ans", "slug": "maximum-height-by-stacking-cuboids", "post_title": "Python 3 | DP, Sort, O(N^2) | Explanation", "user": "idontknoooo", "upvotes": 7, "views": 425, "problem_title": "maximum height by stacking cuboids", "number": 1691, "acceptance": 0.541, "difficulty": "Hard", "__index_level_0__": 24492, "question": "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.\nYou can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.\nReturn the maximum height of the stacked cuboids.\n Example 1:\nInput: cuboids = [[50,45,20],[95,37,53],[45,23,12]]\nOutput: 190\nExplanation:\nCuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\nCuboid 0 is placed next with the 45x20 side facing down with height 50.\nCuboid 2 is placed next with the 23x12 side facing down with height 45.\nThe total height is 95 + 50 + 45 = 190.\nExample 2:\nInput: cuboids = [[38,25,45],[76,35,3]]\nOutput: 76\nExplanation:\nYou can't place any of the cuboids on the other.\nWe choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.\nExample 3:\nInput: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\nOutput: 102\nExplanation:\nAfter rearranging the cuboids, you can see that all cuboids have the same dimension.\nYou can place the 11x7 side down on all cuboids so their heights are 17.\nThe maximum height of stacked cuboids is 6 * 17 = 102.\n Constraints:\nn == cuboids.length\n1 <= n <= 100\n1 <= widthi, lengthi, heighti <= 100" }, { "post_href": "https://leetcode.com/problems/reformat-phone-number/discuss/978512/Python3-string-processing", "python_solutions": "class Solution:\n def reformatNumber(self, number: str) -> str:\n number = number.replace(\"-\", \"\").replace(\" \", \"\") # removing - and space \n ans = []\n for i in range(0, len(number), 3): \n if len(number) - i != 4: ans.append(number[i:i+3])\n else: \n ans.extend([number[i:i+2], number[i+2:]])\n break \n return \"-\".join(ans)", "slug": "reformat-phone-number", "post_title": "[Python3] string processing", "user": "ye15", "upvotes": 13, "views": 676, "problem_title": "reformat phone number", "number": 1694, "acceptance": 0.649, "difficulty": "Easy", "__index_level_0__": 24498, "question": "You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.\nYou would like to reformat the phone number in a certain manner. Firstly, remove all spaces and dashes. Then, group the digits from left to right into blocks of length 3 until there are 4 or fewer digits. The final digits are then grouped as follows:\n2 digits: A single block of length 2.\n3 digits: A single block of length 3.\n4 digits: Two blocks of length 2 each.\nThe blocks are then joined by dashes. Notice that the reformatting process should never produce any blocks of length 1 and produce at most two blocks of length 2.\nReturn the phone number after formatting.\n Example 1:\nInput: number = \"1-23-45 6\"\nOutput: \"123-456\"\nExplanation: The digits are \"123456\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\nJoining the blocks gives \"123-456\".\nExample 2:\nInput: number = \"123 4-567\"\nOutput: \"123-45-67\"\nExplanation: The digits are \"1234567\".\nStep 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\nStep 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\nJoining the blocks gives \"123-45-67\".\nExample 3:\nInput: number = \"123 4-5678\"\nOutput: \"123-456-78\"\nExplanation: The digits are \"12345678\".\nStep 1: The 1st block is \"123\".\nStep 2: The 2nd block is \"456\".\nStep 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\nJoining the blocks gives \"123-456-78\".\n Constraints:\n2 <= number.length <= 100\nnumber consists of digits and the characters '-' and ' '.\nThere are at least two digits in number." }, { "post_href": "https://leetcode.com/problems/maximum-erasure-value/discuss/2140512/Python-Easy-2-approaches", "python_solutions": "class Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n counter=defaultdict(int) # track count of elements in the window\n res=i=tot=0\n\t\t\n for j in range(len(nums)):\n x=nums[j] \n tot+=x\n counter[x]+=1\n # adjust the left bound of sliding window until you get all unique elements\n while i < j and counter[x]>1: \n counter[nums[i]]-=1\n tot-=nums[i]\n i+=1\n \n res=max(res, tot) \n return res", "slug": "maximum-erasure-value", "post_title": "\u2705 Python Easy 2 approaches", "user": "constantine786", "upvotes": 15, "views": 1400, "problem_title": "maximum erasure value", "number": 1695, "acceptance": 0.5770000000000001, "difficulty": "Medium", "__index_level_0__": 24519, "question": "You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements.\nReturn the maximum score you can get by erasing exactly one subarray.\nAn array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r).\n Example 1:\nInput: nums = [4,2,4,5,6]\nOutput: 17\nExplanation: The optimal subarray here is [2,4,5,6].\nExample 2:\nInput: nums = [5,2,1,2,5,2,1,2,5]\nOutput: 8\nExplanation: The optimal subarray here is [5,2,1] or [1,2,5].\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/jump-game-vi/discuss/978563/Python3-range-max", "python_solutions": "class Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n pq = [] # max heap \n for i in reversed(range(len(nums))): \n while pq and pq[0][1] - i > k: heappop(pq)\n ans = nums[i] - pq[0][0] if pq else nums[i]\n heappush(pq, (-ans, i))\n return ans", "slug": "jump-game-vi", "post_title": "[Python3] range max", "user": "ye15", "upvotes": 7, "views": 504, "problem_title": "jump game vi", "number": 1696, "acceptance": 0.4629999999999999, "difficulty": "Medium", "__index_level_0__": 24557, "question": "You are given a 0-indexed integer array nums and an integer k.\nYou are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.\nYou want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.\nReturn the maximum score you can get.\n Example 1:\nInput: nums = [1,-1,-2,4,-7,3], k = 2\nOutput: 7\nExplanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\nExample 2:\nInput: nums = [10,-5,-2,4,0,3], k = 3\nOutput: 17\nExplanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\nExample 3:\nInput: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\nOutput: 0\n Constraints:\n1 <= nums.length, k <= 105\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/checking-existence-of-edge-length-limited-paths/discuss/981352/Python3-Union-find", "python_solutions": "class Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \n parent = [i for i in range(n+1)]\n \n rank = [0 for i in range(n+1)]\n\n def find(parent, x):\n\n if parent[x] == x:\n return x\n parent[x] = find(parent, parent[x])\n return parent[x]\n\n def union(parent, a, b):\n\n a = find(parent, a)\n b = find(parent, b)\n\n if a == b:\n return \n\n if rank[a] < rank[b]:\n parent[a] = b\n elif rank[a] > rank[b]:\n parent[b] = a\n else:\n parent[b] = a\n rank[a] += 1\n \n edgeList.sort(key = lambda x: x[2])\n res = [0] * len(queries)\n queries = [[i, ch] for i, ch in enumerate(queries)]\n queries.sort(key = lambda x: x[1][2])\n \n ind = 0\n for i, (a, b, w) in queries:\n \n while ind < len(edgeList) and edgeList[ind][2] < w:\n union(parent, edgeList[ind][0], edgeList[ind][1])\n ind += 1\n \n res[i] = find(parent, a) == find(parent, b)\n return res", "slug": "checking-existence-of-edge-length-limited-paths", "post_title": "Python3 Union find", "user": "ermolushka2", "upvotes": 0, "views": 80, "problem_title": "checking existence of edge length limited paths", "number": 1697, "acceptance": 0.502, "difficulty": "Hard", "__index_level_0__": 24570, "question": "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.\nGiven an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj .\nReturn a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.\n Example 1:\nInput: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\nOutput: [false,true]\nExplanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\nFor the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\nFor the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.\nExample 2:\nInput: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\nOutput: [true,false]\nExplanation: The above figure shows the given graph.\n Constraints:\n2 <= n <= 105\n1 <= edgeList.length, queries.length <= 105\nedgeList[i].length == 3\nqueries[j].length == 3\n0 <= ui, vi, pj, qj <= n - 1\nui != vi\npj != qj\n1 <= disi, limitj <= 109\nThere may be multiple edges between two nodes." }, { "post_href": "https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/discuss/1228863/Python3-32ms-Brute-Force-Solution", "python_solutions": "class Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n curr = 0\n \n while students:\n if(students[0] == sandwiches[0]):\n curr = 0\n students.pop(0)\n sandwiches.pop(0)\n else:\n curr += 1\n students.append(students.pop(0))\n \n if(curr >= len(students)):\n break\n \n return len(students)", "slug": "number-of-students-unable-to-eat-lunch", "post_title": "[Python3] 32ms Brute Force Solution", "user": "VoidCupboard", "upvotes": 11, "views": 442, "problem_title": "number of students unable to eat lunch", "number": 1700, "acceptance": 0.679, "difficulty": "Easy", "__index_level_0__": 24572, "question": "The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers 0 and 1 respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.\nThe number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:\nIf the student at the front of the queue prefers the sandwich on the top of the stack, they will take it and leave the queue.\nOtherwise, they will leave it and go to the queue's end.\nThis continues until none of the queue students want to take the top sandwich and are thus unable to eat.\nYou are given two integer arrays students and sandwiches where sandwiches[i] is the type of the ith sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the jth student in the initial queue (j = 0 is the front of the queue). Return the number of students that are unable to eat.\n Example 1:\nInput: students = [1,1,0,0], sandwiches = [0,1,0,1]\nOutput: 0 \nExplanation:\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].\n- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].\n- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].\n- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].\n- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].\n- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].\nHence all students are able to eat.\nExample 2:\nInput: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\nOutput: 3\n Constraints:\n1 <= students.length, sandwiches.length <= 100\nstudents.length == sandwiches.length\nsandwiches[i] is 0 or 1.\nstudents[i] is 0 or 1." }, { "post_href": "https://leetcode.com/problems/average-waiting-time/discuss/1236349/Python3-Simple-And-Fast-Solution", "python_solutions": "class Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n arr = []\n \n time = 0\n \n for i , j in customers:\n if(i > time):\n time = i + j\n else:\n time += j\n arr.append(time - i)\n \n return sum(arr) / len(arr)", "slug": "average-waiting-time", "post_title": "[Python3] Simple And Fast Solution", "user": "VoidCupboard", "upvotes": 6, "views": 194, "problem_title": "average waiting time", "number": 1701, "acceptance": 0.624, "difficulty": "Medium", "__index_level_0__": 24612, "question": "There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:\narrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order.\ntimei is the time needed to prepare the order of the ith customer.\nWhen a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers in the order they were given in the input.\nReturn the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.\n Example 1:\nInput: customers = [[1,2],[2,5],[4,3]]\nOutput: 5.00000\nExplanation:\n1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2.\n2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6.\n3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7.\nSo the average waiting time = (2 + 6 + 7) / 3 = 5.\nExample 2:\nInput: customers = [[5,2],[5,4],[10,3],[20,1]]\nOutput: 3.25000\nExplanation:\n1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2.\n2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6.\n3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4.\n4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1.\nSo the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.\n Constraints:\n1 <= customers.length <= 105\n1 <= arrivali, timei <= 104\narrivali <= arrivali+1" }, { "post_href": "https://leetcode.com/problems/maximum-binary-string-after-change/discuss/1382851/python-3-oror-clean-oror-easy-approach", "python_solutions": "lass Solution:\n def maximumBinaryString(self, s: str) -> str:\n #count of 0\n c=0\n #final ans string will contain only one zero.therefore shift the first 0 to c places.Initialize ans string with all 1s\n lst=[\"1\"]*len(s)\n for i in range (0,len(s)):\n if s[i]==\"0\":\n c+=1\n for i in range (0,len(s)):\n\t\t#finding the ist 0\n if s[i]==\"0\":\n lst[i+c-1]=\"0\"\n return \"\".join(lst)\n return s", "slug": "maximum-binary-string-after-change", "post_title": "python 3 || clean || easy approach", "user": "minato_namikaze", "upvotes": 4, "views": 175, "problem_title": "maximum binary string after change", "number": 1702, "acceptance": 0.462, "difficulty": "Medium", "__index_level_0__": 24622, "question": "You are given a binary string binary consisting of only 0's or 1's. You can apply each of the following operations any number of times:\nOperation 1: If the number contains the substring \"00\", you can replace it with \"10\".\nFor example, \"00010\" -> \"10010\"\nOperation 2: If the number contains the substring \"10\", you can replace it with \"01\".\nFor example, \"00010\" -> \"00001\"\nReturn the maximum binary string you can obtain after any number of operations. Binary string x is greater than binary string y if x's decimal representation is greater than y's decimal representation.\n Example 1:\nInput: binary = \"000110\"\nOutput: \"111011\"\nExplanation: A valid transformation sequence can be:\n\"000110\" -> \"000101\" \n\"000101\" -> \"100101\" \n\"100101\" -> \"110101\" \n\"110101\" -> \"110011\" \n\"110011\" -> \"111011\"\nExample 2:\nInput: binary = \"01\"\nOutput: \"01\"\nExplanation: \"01\" cannot be transformed any further.\n Constraints:\n1 <= binary.length <= 105\nbinary consist of '0' and '1'." }, { "post_href": "https://leetcode.com/problems/minimum-adjacent-swaps-for-k-consecutive-ones/discuss/1002574/Python3-1-pass-O(N)", "python_solutions": "class Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n ii = val = 0 \n ans = inf\n loc = [] # location of 1s\n for i, x in enumerate(nums): \n if x: \n loc.append(i)\n m = (ii + len(loc) - 1)//2 # median \n val += loc[-1] - loc[m] - (len(loc)-ii)//2 # adding right \n if len(loc) - ii > k: \n m = (ii + len(loc))//2 # updated median \n val -= loc[m] - loc[ii] - (len(loc)-ii)//2 # removing left \n ii += 1\n if len(loc)-ii == k: ans = min(ans, val) # len(ones) - ii effective length\n return ans", "slug": "minimum-adjacent-swaps-for-k-consecutive-ones", "post_title": "[Python3] 1-pass O(N)", "user": "ye15", "upvotes": 2, "views": 572, "problem_title": "minimum adjacent swaps for k consecutive ones", "number": 1703, "acceptance": 0.423, "difficulty": "Hard", "__index_level_0__": 24630, "question": "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.\nReturn the minimum number of moves required so that nums has k consecutive 1's.\n Example 1:\nInput: nums = [1,0,0,1,0,1], k = 2\nOutput: 1\nExplanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.\nExample 2:\nInput: nums = [1,0,0,0,0,0,1,1], k = 3\nOutput: 5\nExplanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].\nExample 3:\nInput: nums = [1,1,0,1], k = 2\nOutput: 0\nExplanation: nums already has 2 consecutive 1's.\n Constraints:\n1 <= nums.length <= 105\nnums[i] is 0 or 1.\n1 <= k <= sum(nums)" }, { "post_href": "https://leetcode.com/problems/determine-if-string-halves-are-alike/discuss/991430/Runtime-is-faster-than-98-and-the-memory-usage-is-less-than-90-Python-3-Accepted", "python_solutions": "class Solution:\n def halvesAreAlike(self, s: str) -> bool:\n vowels = set('aeiouAEIOU')\n count = 0\n for i in range(len(s)//2):\n if s[i] in vowels:\n count+=1\n if s[-i-1] in vowels:\n count-=1\n\n return count == 0", "slug": "determine-if-string-halves-are-alike", "post_title": "Runtime is faster than 98% and the memory usage is less than 90% Python 3 [Accepted]", "user": "WiseLin", "upvotes": 5, "views": 341, "problem_title": "determine if string halves are alike", "number": 1704, "acceptance": 0.774, "difficulty": "Easy", "__index_level_0__": 24632, "question": "You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.\nTwo strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.\nReturn true if a and b are alike. Otherwise, return false.\n Example 1:\nInput: s = \"book\"\nOutput: true\nExplanation: a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.\nExample 2:\nInput: s = \"textbook\"\nOutput: false\nExplanation: a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\nNotice that the vowel o is counted twice.\n Constraints:\n2 <= s.length <= 1000\ns.length is even.\ns consists of uppercase and lowercase letters." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-eaten-apples/discuss/988437/Python3-priority-queue", "python_solutions": "class Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n ans = 0\n \n pq = [] # min-heap \n for i, (x, d) in enumerate(zip(apples, days)): \n while pq and pq[0][0] <= i: heappop(pq) # rotten \n if x: heappush(pq, (i+d, x))\n if pq: \n ii, x = heappop(pq)\n if x-1: heappush(pq, (ii, x-1))\n ans += 1\n \n i += 1\n while pq: \n ii, x = heappop(pq)\n x = min(x, ii-i)\n ans += x\n i += x \n return ans", "slug": "maximum-number-of-eaten-apples", "post_title": "[Python3] priority queue", "user": "ye15", "upvotes": 3, "views": 113, "problem_title": "maximum number of eaten apples", "number": 1705, "acceptance": 0.381, "difficulty": "Medium", "__index_level_0__": 24687, "question": "There is a special kind of apple tree that grows apples every day for n days. On the ith day, the tree grows apples[i] apples that will rot after days[i] days, that is on day i + days[i] the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by apples[i] == 0 and days[i] == 0.\nYou decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first n days.\nGiven two integer arrays days and apples of length n, return the maximum number of apples you can eat.\n Example 1:\nInput: apples = [1,2,3,5,2], days = [3,2,1,4,2]\nOutput: 7\nExplanation: You can eat 7 apples:\n- On the first day, you eat an apple that grew on the first day.\n- On the second day, you eat an apple that grew on the second day.\n- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n- On the fourth to the seventh days, you eat apples that grew on the fourth day.\nExample 2:\nInput: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\nOutput: 5\nExplanation: You can eat 5 apples:\n- On the first to the third day you eat apples that grew on the first day.\n- Do nothing on the fouth and fifth days.\n- On the sixth and seventh days you eat apples that grew on the sixth day.\n Constraints:\nn == apples.length == days.length\n1 <= n <= 2 * 104\n0 <= apples[i], days[i] <= 2 * 104\ndays[i] = 0 if and only if apples[i] = 0." }, { "post_href": "https://leetcode.com/problems/where-will-the-ball-fall/discuss/1443268/Python-3-or-DFS-Simulation-or-Explanation", "python_solutions": "class Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n m, n = len(grid), len(grid[0])\n @cache\n def helper(r, c):\n if r == m:\n return c\n elif grid[r][c] == 1 and c+1 < n and grid[r][c+1] == 1:\n return helper(r+1, c+1)\n elif grid[r][c] == -1 and 0 <= c-1 and grid[r][c-1] == -1:\n return helper(r+1, c-1)\n else:\n return -1\n \n return [helper(0, j) for j in range(n)]", "slug": "where-will-the-ball-fall", "post_title": "Python 3 | DFS, Simulation | Explanation", "user": "idontknoooo", "upvotes": 28, "views": 1400, "problem_title": "where will the ball fall", "number": 1706, "acceptance": 0.716, "difficulty": "Medium", "__index_level_0__": 24689, "question": "You have a 2-D grid of size m x n representing a box, and you have n balls. The box is open on the top and bottom sides.\nEach cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.\nA board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.\nA board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.\nWe drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a \"V\" shaped pattern between two boards or if a board redirects the ball into either wall of the box.\nReturn an array answer of size n where answer[i] is the column that the ball falls out of at the bottom after dropping the ball from the ith column at the top, or -1 if the ball gets stuck in the box.\n Example 1:\nInput: grid = [[1,1,1,-1,-1],[1,1,1,-1,-1],[-1,-1,-1,1,1],[1,1,1,1,-1],[-1,-1,-1,-1,-1]]\nOutput: [1,-1,-1,-1,-1]\nExplanation: This example is shown in the photo.\nBall b0 is dropped at column 0 and falls out of the box at column 1.\nBall b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\nBall b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\nBall b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\nBall b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.\nExample 2:\nInput: grid = [[-1]]\nOutput: [-1]\nExplanation: The ball gets stuck against the left wall.\nExample 3:\nInput: grid = [[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1],[1,1,1,1,1,1],[-1,-1,-1,-1,-1,-1]]\nOutput: [0,1,2,3,4,-1]\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 100\ngrid[i][j] is 1 or -1." }, { "post_href": "https://leetcode.com/problems/maximum-xor-with-an-element-from-array/discuss/988468/Python3-trie", "python_solutions": "class Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n queries = sorted((m, x, i) for i, (x, m) in enumerate(queries))\n ans = [-1]*len(queries)\n \n trie = {}\n k = 0\n for m, x, i in queries: \n while k < len(nums) and nums[k] <= m: \n node = trie\n val = bin(nums[k])[2:].zfill(32)\n for c in val: node = node.setdefault(int(c), {})\n node[\"#\"] = nums[k]\n k += 1\n if trie: \n node = trie\n val = bin(x)[2:].zfill(32)\n for c in val: node = node.get(1-int(c)) or node.get(int(c))\n ans[i] = x ^ node[\"#\"]\n return ans", "slug": "maximum-xor-with-an-element-from-array", "post_title": "[Python3] trie", "user": "ye15", "upvotes": 17, "views": 773, "problem_title": "maximum xor with an element from array", "number": 1707, "acceptance": 0.442, "difficulty": "Hard", "__index_level_0__": 24743, "question": "You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].\nThe answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.\nReturn an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.\n Example 1:\nInput: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\nOutput: [3,3,7]\nExplanation:\n1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n2) 1 XOR 2 = 3.\n3) 5 XOR 2 = 7.\nExample 2:\nInput: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\nOutput: [15,-1,5]\n Constraints:\n1 <= nums.length, queries.length <= 105\nqueries[i].length == 2\n0 <= nums[j], xi, mi <= 109" }, { "post_href": "https://leetcode.com/problems/maximum-units-on-a-truck/discuss/999230/Python-Simple-solution", "python_solutions": "class Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x:x[1],reverse=1)\n s=0\n for i,j in boxTypes:\n i=min(i,truckSize)\n s+=i*j\n truckSize-=i\n if truckSize==0:\n break\n return s", "slug": "maximum-units-on-a-truck", "post_title": "[Python] Simple solution", "user": "lokeshsenthilkumar", "upvotes": 30, "views": 4500, "problem_title": "maximum units on a truck", "number": 1710, "acceptance": 0.7390000000000001, "difficulty": "Easy", "__index_level_0__": 24744, "question": "You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:\nnumberOfBoxesi is the number of boxes of type i.\nnumberOfUnitsPerBoxi is the number of units in each box of the type i.\nYou are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.\nReturn the maximum total number of units that can be put on the truck.\n Example 1:\nInput: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\nOutput: 8\nExplanation: There are:\n- 1 box of the first type that contains 3 units.\n- 2 boxes of the second type that contain 2 units each.\n- 3 boxes of the third type that contain 1 unit each.\nYou can take all the boxes of the first and second types, and one box of the third type.\nThe total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.\nExample 2:\nInput: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\nOutput: 91\n Constraints:\n1 <= boxTypes.length <= 1000\n1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000\n1 <= truckSize <= 106" }, { "post_href": "https://leetcode.com/problems/count-good-meals/discuss/999170/Python3-frequency-table", "python_solutions": "class Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n ans = 0\n freq = defaultdict(int)\n for x in deliciousness: \n for k in range(22): ans += freq[2**k - x]\n freq[x] += 1\n return ans % 1_000_000_007", "slug": "count-good-meals", "post_title": "[Python3] frequency table", "user": "ye15", "upvotes": 43, "views": 4100, "problem_title": "count good meals", "number": 1711, "acceptance": 0.29, "difficulty": "Medium", "__index_level_0__": 24793, "question": "A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.\nYou can pick any two different foods to make a good meal.\nGiven an array of integers deliciousness where deliciousness[i] is the deliciousness of the ith item of food, return the number of different good meals you can make from this list modulo 109 + 7.\nNote that items with different indices are considered different even if they have the same deliciousness value.\n Example 1:\nInput: deliciousness = [1,3,5,7,9]\nOutput: 4\nExplanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\nTheir respective sums are 4, 8, 8, and 16, all of which are powers of 2.\nExample 2:\nInput: deliciousness = [1,1,1,3,3,3,7]\nOutput: 15\nExplanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.\n Constraints:\n1 <= deliciousness.length <= 105\n0 <= deliciousness[i] <= 220" }, { "post_href": "https://leetcode.com/problems/ways-to-split-array-into-three-subarrays/discuss/999157/Python3-binary-search-and-2-pointer", "python_solutions": "class Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0\n for i in range(1, len(nums)): \n j = bisect_left(prefix, 2*prefix[i])\n k = bisect_right(prefix, (prefix[i] + prefix[-1])//2)\n ans += max(0, min(len(nums), k) - max(i+1, j))\n return ans % 1_000_000_007", "slug": "ways-to-split-array-into-three-subarrays", "post_title": "[Python3] binary search & 2-pointer", "user": "ye15", "upvotes": 65, "views": 4900, "problem_title": "ways to split array into three subarrays", "number": 1712, "acceptance": 0.325, "difficulty": "Medium", "__index_level_0__": 24801, "question": "A split of an integer array is good if:\nThe array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.\nThe sum of the elements in left is less than or equal to the sum of the elements in mid, and the sum of the elements in mid is less than or equal to the sum of the elements in right.\nGiven nums, an array of non-negative integers, return the number of good ways to split nums. As the number may be too large, return it modulo 109 + 7.\n Example 1:\nInput: nums = [1,1,1]\nOutput: 1\nExplanation: The only good way to split nums is [1] [1] [1].\nExample 2:\nInput: nums = [1,2,2,2,5,0]\nOutput: 3\nExplanation: There are three good ways of splitting nums:\n[1] [2] [2,2,5,0]\n[1] [2,2] [2,5,0]\n[1,2] [2,2] [5,0]\nExample 3:\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: There is no good way to split nums.\n Constraints:\n3 <= nums.length <= 105\n0 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/discuss/999141/Python3-binary-search", "python_solutions": "class Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n loc = {x: i for i, x in enumerate(target)}\n stack = []\n for x in arr: \n if x in loc: \n i = bisect_left(stack, loc[x])\n if i < len(stack): stack[i] = loc[x]\n else: stack.append(loc[x])\n return len(target) - len(stack)", "slug": "minimum-operations-to-make-a-subsequence", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 5, "views": 294, "problem_title": "minimum operations to make a subsequence", "number": 1713, "acceptance": 0.492, "difficulty": "Hard", "__index_level_0__": 24810, "question": "You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.\nIn one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.\nReturn the minimum number of operations needed to make target a subsequence of arr.\nA subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\n Example 1:\nInput: target = [5,1,3], arr = [9,4,2,3,4]\nOutput: 2\nExplanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.\nExample 2:\nInput: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]\nOutput: 3\n Constraints:\n1 <= target.length, arr.length <= 105\n1 <= target[i], arr[i] <= 109\ntarget contains no duplicates." }, { "post_href": "https://leetcode.com/problems/calculate-money-in-leetcode-bank/discuss/1138960/Python-3-very-easy-solution", "python_solutions": "class Solution:\n def totalMoney(self, n: int) -> int:\n res,k=0,0\n for i in range(n):\n if i%7==0:\n k+=1\n res+=k+(i%7)\n return res", "slug": "calculate-money-in-leetcode-bank", "post_title": "Python 3 very easy solution", "user": "lin11116459", "upvotes": 5, "views": 367, "problem_title": "calculate money in leetcode bank", "number": 1716, "acceptance": 0.652, "difficulty": "Easy", "__index_level_0__": 24813, "question": "Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.\nHe starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday, he will put in $1 more than the day before. On every subsequent Monday, he will put in $1 more than the previous Monday.\nGiven n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.\n Example 1:\nInput: n = 4\nOutput: 10\nExplanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.\nExample 2:\nInput: n = 10\nOutput: 37\nExplanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.\nExample 3:\nInput: n = 20\nOutput: 96\nExplanation: After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/maximum-score-from-removing-substrings/discuss/1009152/Python-solution-with-explanation", "python_solutions": "class Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n\t\t# to calculate first, high value of x or y\n a, b = 'ab', 'ba'\n if y > x:\n b, a, y, x = a, b, x, y\n\n answer = 0\n \n for word in [a, b]:\n stack = []\n\n i = 0\n while i < len(s):\n stack.append(s[i])\n \n n = len(stack)\n prefix = stack[n-2] + stack[n-1]\n # if see the prefix ab or ba move from stack and increment the answer\n if prefix == word:\n answer += x\n stack.pop()\n stack.pop()\n i += 1\n # change the x point to y for 2nd iteration\n x = y\n \n # assign new letters with already removed prefix\n s = ''.join(stack)\n return answer", "slug": "maximum-score-from-removing-substrings", "post_title": "Python solution with explanation\ud83d\udc83\ud83c\udffb", "user": "just_4ina", "upvotes": 9, "views": 602, "problem_title": "maximum score from removing substrings", "number": 1717, "acceptance": 0.461, "difficulty": "Medium", "__index_level_0__": 24848, "question": "You are given a string s and two integers x and y. You can perform two types of operations any number of times.\nRemove substring \"ab\" and gain x points.\nFor example, when removing \"ab\" from \"cabxbae\" it becomes \"cxbae\".\nRemove substring \"ba\" and gain y points.\nFor example, when removing \"ba\" from \"cabxbae\" it becomes \"cabxe\".\nReturn the maximum points you can gain after applying the above operations on s.\n Example 1:\nInput: s = \"cdbcbbaaabab\", x = 4, y = 5\nOutput: 19\nExplanation:\n- Remove the \"ba\" underlined in \"cdbcbbaaabab\". Now, s = \"cdbcbbaaab\" and 5 points are added to the score.\n- Remove the \"ab\" underlined in \"cdbcbbaaab\". Now, s = \"cdbcbbaa\" and 4 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcbbaa\". Now, s = \"cdbcba\" and 5 points are added to the score.\n- Remove the \"ba\" underlined in \"cdbcba\". Now, s = \"cdbc\" and 5 points are added to the score.\nTotal score = 5 + 4 + 5 + 5 = 19.\nExample 2:\nInput: s = \"aabbaaxybbaabb\", x = 5, y = 4\nOutput: 20\n Constraints:\n1 <= s.length <= 105\n1 <= x, y <= 104\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/construct-the-lexicographically-largest-valid-sequence/discuss/1008948/Python-Greedy%2BBacktracking-or-Well-Explained-or-Comments", "python_solutions": "class Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n \n arr = [0]*(2*n-1) # the array we want to put numbers. 0 means no number has been put here\n i = 0 # current index to put a number \n vi = [False] * (n+1) # check if we have used that number\n \n\t\t# backtracking\n def dfs(arr, i, vi):\n\t\t # if we already fill the array successfully, return True\n if i >= (2*n-1):\n return True\n\t\t\t\t\n\t\t\t# try each number from n to 1\n for x in range(n, 0, -1):\n\t\t\t # two cases:\n\t\t\t # x > 1, we check two places. Mind index out of bound here.\n\t\t\t # x = 1, we only check one place\n\t\t\t\t# arr[i] == 0 means index i is not occupied\n if (x > 1 and ((not (arr[i] == 0 and (i+x < 2*n-1) and arr[i+x] == 0)) or vi[x])) \\\n\t\t\t\t\tor (x == 1 and (arr[i] != 0 or vi[x])):\n continue\n\t\t\t\t\n\t\t\t\t# if it can be placed, then place it\n if x > 1:\n arr[i] = x\n arr[i+x] = x\n else:\n arr[i] = x\n vi[x] = True\n\t\t\t\t\n\t\t\t\t# find the next available place\n nexti = i+1\n while nexti < 2*n-1 and arr[nexti]:\n nexti += 1\n\t\t\t\t\n\t\t\t\t# place the next one\n if dfs(arr, nexti, vi):\n\t\t\t\t\t# if it success, it is already the lexicographically largest one, we don't search anymore\n return True\n\t\t\t\t\t\n\t\t\t\t# backtracking... restore the state\n if x > 1:\n arr[i] = 0\n arr[i+x] = 0\n else:\n arr[i] = 0\n vi[x] = False\n\t\t\t\n\t\t\t# we could not find a solution, return False\n return False\n\t\t\n dfs(arr, i, vi)\n return arr", "slug": "construct-the-lexicographically-largest-valid-sequence", "post_title": "Python Greedy+Backtracking | Well Explained | Comments", "user": "etoss", "upvotes": 23, "views": 1800, "problem_title": "construct the lexicographically largest valid sequence", "number": 1718, "acceptance": 0.516, "difficulty": "Medium", "__index_level_0__": 24850, "question": "Given an integer n, find a sequence that satisfies all of the following:\nThe integer 1 occurs once in the sequence.\nEach integer between 2 and n occurs twice in the sequence.\nFor every integer i between 2 and n, the distance between the two occurrences of i is exactly i.\nThe distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|.\nReturn the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution.\nA sequence a is lexicographically larger than a sequence b (of the same length) if in the first position where a and b differ, sequence a has a number greater than the corresponding number in b. For example, [0,1,9,0] is lexicographically larger than [0,1,5,6] because the first position they differ is at the third number, and 9 is greater than 5.\n Example 1:\nInput: n = 3\nOutput: [3,1,2,3,2]\nExplanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.\nExample 2:\nInput: n = 5\nOutput: [5,3,1,4,3,5,2,4,2]\n Constraints:\n1 <= n <= 20" }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-reconstruct-a-tree/discuss/1128518/Python3-greedy", "python_solutions": "class Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n graph = {}\n for x, y in pairs: \n graph.setdefault(x, set()).add(y)\n graph.setdefault(y, set()).add(x)\n \n ans = 1 \n ancestors = set()\n for n in sorted(graph, key=lambda x: len(graph[x]), reverse=True): \n p = min(ancestors & graph[n], key=lambda x: len(graph[x]), default=None) # immediate ancestor \n ancestors.add(n)\n if p: \n if graph[n] - (graph[p] | {p}): return 0 # impossible to have more than ancestor\n if len(graph[n]) == len(graph[p]): ans = 2\n elif len(graph[n]) != len(graph)-1: return 0\n return ans", "slug": "number-of-ways-to-reconstruct-a-tree", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 5, "views": 330, "problem_title": "number of ways to reconstruct a tree", "number": 1719, "acceptance": 0.43, "difficulty": "Hard", "__index_level_0__": 24855, "question": "You are given an array pairs, where pairs[i] = [xi, yi], and:\nThere are no duplicates.\nxi < yi\nLet ways be the number of rooted trees that satisfy the following conditions:\nThe tree consists of nodes whose values appeared in pairs.\nA pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi.\nNote: the tree does not have to be a binary tree.\nTwo ways are considered to be different if there is at least one node that has different parents in both ways.\nReturn:\n0 if ways == 0\n1 if ways == 1\n2 if ways > 1\nA rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.\nAn ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.\n Example 1:\nInput: pairs = [[1,2],[2,3]]\nOutput: 1\nExplanation: There is exactly one valid rooted tree, which is shown in the above figure.\nExample 2:\nInput: pairs = [[1,2],[2,3],[1,3]]\nOutput: 2\nExplanation: There are multiple valid rooted trees. Three of them are shown in the above figures.\nExample 3:\nInput: pairs = [[1,2],[2,3],[2,4],[1,5]]\nOutput: 0\nExplanation: There are no valid rooted trees.\n Constraints:\n1 <= pairs.length <= 105\n1 <= xi < yi <= 500\nThe elements in pairs are unique." }, { "post_href": "https://leetcode.com/problems/decode-xored-array/discuss/1075067/Python-1-Liner-(List-Comprehension-with-Assignment-Expresion)", "python_solutions": "class Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n return [first] + [first:= first ^ x for x in encoded]", "slug": "decode-xored-array", "post_title": "Python - 1 Liner (List Comprehension with Assignment Expresion)", "user": "leeteatsleep", "upvotes": 17, "views": 957, "problem_title": "decode xored array", "number": 1720, "acceptance": 0.86, "difficulty": "Easy", "__index_level_0__": 24857, "question": "There is a hidden integer array arr that consists of n non-negative integers.\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = [1,2,3].\nYou are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].\nReturn the original array arr. It can be proved that the answer exists and is unique.\n Example 1:\nInput: encoded = [1,2,3], first = 1\nOutput: [1,0,2,1]\nExplanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]\nExample 2:\nInput: encoded = [6,2,7,3], first = 4\nOutput: [4,2,0,7,4]\n Constraints:\n2 <= n <= 104\nencoded.length == n - 1\n0 <= encoded[i] <= 105\n0 <= first <= 105" }, { "post_href": "https://leetcode.com/problems/swapping-nodes-in-a-linked-list/discuss/1911996/Python-Simple-Solution-with-Explanation", "python_solutions": "class Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n l = head # left node\n for _ in range(k-1):\n l = l.next\n # the rest of the code logic here", "slug": "swapping-nodes-in-a-linked-list", "post_title": "[Python] Simple Solution with Explanation", "user": "zayne-siew", "upvotes": 82, "views": 2800, "problem_title": "swapping nodes in a linked list", "number": 1721, "acceptance": 0.677, "difficulty": "Medium", "__index_level_0__": 24885, "question": "You are given the head of a linked list, and an integer k.\nReturn the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).\n Example 1:\nInput: head = [1,2,3,4,5], k = 2\nOutput: [1,4,3,2,5]\nExample 2:\nInput: head = [7,9,6,6,7,8,3,0,9,5], k = 5\nOutput: [7,9,6,6,8,7,3,0,9,5]\n Constraints:\nThe number of nodes in the list is n.\n1 <= k <= n <= 105\n0 <= Node.val <= 100" }, { "post_href": "https://leetcode.com/problems/minimize-hamming-distance-after-swap-operations/discuss/1982743/Python3-solution", "python_solutions": "class Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n def gen_adjacency():\n adj = {}\n for i in range(len(source)):\n adj[i] = []\n for a, b in allowedSwaps:\n adj[a].append(b)\n adj[b].append(a)\n return adj\n \n def dfs(i):\n visited.add(i)\n this_group.add(i)\n for neigh in adj[i]:\n if neigh not in visited:\n dfs(neigh)\n\n adj = gen_adjacency()\n visited = set()\n common_counts = 0\n for i in adj:\n if i not in visited:\n this_group = set()\n dfs(i)\n s_counts = collections.Counter([source[i] for i in this_group])\n t_counts = collections.Counter([target[i] for i in this_group])\n common = set(s_counts).intersection(t_counts)\n for common_int in common:\n common_counts += min(s_counts[common_int], t_counts[common_int])\n ans = len(source) - common_counts\n return ans", "slug": "minimize-hamming-distance-after-swap-operations", "post_title": "Python3 solution", "user": "dalechoi", "upvotes": 0, "views": 45, "problem_title": "minimize hamming distance after swap operations", "number": 1722, "acceptance": 0.487, "difficulty": "Medium", "__index_level_0__": 24919, "question": "You are given two integer arrays, source and target, both of length n. You are also given an array allowedSwaps where each allowedSwaps[i] = [ai, bi] indicates that you are allowed to swap the elements at index ai and index bi (0-indexed) of array source. Note that you can swap elements at a specific pair of indices multiple times and in any order.\nThe Hamming distance of two arrays of the same length, source and target, is the number of positions where the elements are different. Formally, it is the number of indices i for 0 <= i <= n-1 where source[i] != target[i] (0-indexed).\nReturn the minimum Hamming distance of source and target after performing any amount of swap operations on array source.\n Example 1:\nInput: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\nOutput: 1\nExplanation: source can be transformed the following way:\n- Swap indices 0 and 1: source = [2,1,3,4]\n- Swap indices 2 and 3: source = [2,1,4,3]\nThe Hamming distance of source and target is 1 as they differ in 1 position: index 3.\nExample 2:\nInput: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\nOutput: 2\nExplanation: There are no allowed swaps.\nThe Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.\nExample 3:\nInput: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\nOutput: 0\n Constraints:\nn == source.length == target.length\n1 <= n <= 105\n1 <= source[i], target[i] <= 105\n0 <= allowedSwaps.length <= 105\nallowedSwaps[i].length == 2\n0 <= ai, bi <= n - 1\nai != bi" }, { "post_href": "https://leetcode.com/problems/find-minimum-time-to-finish-all-jobs/discuss/1009859/Python3-backtracking", "python_solutions": "class Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n jobs.sort(reverse=True)\n \n def fn(i):\n \"\"\"Assign jobs to worker and find minimum time.\"\"\"\n nonlocal ans \n if i == len(jobs): ans = max(time)\n else: \n for kk in range(k): \n if not kk or time[kk-1] > time[kk]: \n time[kk] += jobs[i]\n if max(time) < ans: fn(i+1)\n time[kk] -= jobs[i]\n \n ans = inf\n time = [0]*k\n fn(0)\n return ans", "slug": "find-minimum-time-to-finish-all-jobs", "post_title": "[Python3] backtracking", "user": "ye15", "upvotes": 5, "views": 805, "problem_title": "find minimum time to finish all jobs", "number": 1723, "acceptance": 0.426, "difficulty": "Hard", "__index_level_0__": 24921, "question": "You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job.\nThere are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\nReturn the minimum possible maximum working time of any assignment.\n Example 1:\nInput: jobs = [3,2,3], k = 3\nOutput: 3\nExplanation: By assigning each person one job, the maximum time is 3.\nExample 2:\nInput: jobs = [1,2,4,7,8], k = 2\nOutput: 11\nExplanation: Assign the jobs the following way:\nWorker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\nWorker 2: 4, 7 (working time = 4 + 7 = 11)\nThe maximum working time is 11.\n Constraints:\n1 <= k <= jobs.length <= 12\n1 <= jobs[i] <= 107" }, { "post_href": "https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square/discuss/1020629/Python3-freq-table", "python_solutions": "class Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n freq = {}\n for l, w in rectangles: \n x = min(l, w)\n freq[x] = 1 + freq.get(x, 0)\n return freq[max(freq)]", "slug": "number-of-rectangles-that-can-form-the-largest-square", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 3, "views": 222, "problem_title": "number of rectangles that can form the largest square", "number": 1725, "acceptance": 0.787, "difficulty": "Easy", "__index_level_0__": 24924, "question": "You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.\nYou can cut the ith rectangle to form a square with a side length of k if both k <= li and k <= wi. For example, if you have a rectangle [4,6], you can cut it to get a square with a side length of at most 4.\nLet maxLen be the side length of the largest square you can obtain from any of the given rectangles.\nReturn the number of rectangles that can make a square with a side length of maxLen.\n Example 1:\nInput: rectangles = [[5,8],[3,9],[5,12],[16,5]]\nOutput: 3\nExplanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].\nThe largest possible square is of length 5, and you can get it out of 3 rectangles.\nExample 2:\nInput: rectangles = [[2,3],[3,7],[4,3],[3,7]]\nOutput: 3\n Constraints:\n1 <= rectangles.length <= 1000\nrectangles[i].length == 2\n1 <= li, wi <= 109\nli != wi" }, { "post_href": "https://leetcode.com/problems/tuple-with-same-product/discuss/1020657/Python3-freq-table", "python_solutions": "class Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n ans = 0\n freq = {}\n for i in range(len(nums)):\n for j in range(i+1, len(nums)): \n key = nums[i] * nums[j]\n ans += freq.get(key, 0)\n freq[key] = 1 + freq.get(key, 0)\n return 8*ans", "slug": "tuple-with-same-product", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 31, "views": 2100, "problem_title": "tuple with same product", "number": 1726, "acceptance": 0.608, "difficulty": "Medium", "__index_level_0__": 24954, "question": "Given an array nums of distinct positive integers, return the number of tuples (a, b, c, d) such that a * b = c * d where a, b, c, and d are elements of nums, and a != b != c != d.\n Example 1:\nInput: nums = [2,3,4,6]\nOutput: 8\nExplanation: There are 8 valid tuples:\n(2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n(3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\nExample 2:\nInput: nums = [1,2,4,5,10]\nOutput: 16\nExplanation: There are 16 valid tuples:\n(1,10,2,5) , (1,10,5,2) , (10,1,2,5) , (10,1,5,2)\n(2,5,1,10) , (2,5,10,1) , (5,2,1,10) , (5,2,10,1)\n(2,10,4,5) , (2,10,5,4) , (10,2,4,5) , (10,2,5,4)\n(4,5,2,10) , (4,5,10,2) , (5,4,2,10) , (5,4,10,2)\n Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 104\nAll elements in nums are distinct." }, { "post_href": "https://leetcode.com/problems/largest-submatrix-with-rearrangements/discuss/1020589/Simple-Python3-or-9-Lines-or-Beats-100-or-Detailed-Explanation", "python_solutions": "class Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n m, n, ans = len(matrix), len(matrix[0]), 0\n \n for j in range(n):\n for i in range(1, m):\n matrix[i][j] += matrix[i-1][j] if matrix[i][j] else 0\n \n for i in range(m): \n matrix[i].sort(reverse=1)\n for j in range(n):\n ans = max(ans, (j+1)*matrix[i][j])\n return ans", "slug": "largest-submatrix-with-rearrangements", "post_title": "Simple Python3 | 9 Lines | Beats 100% | Detailed Explanation", "user": "sushanthsamala", "upvotes": 9, "views": 627, "problem_title": "largest submatrix with rearrangements", "number": 1727, "acceptance": 0.61, "difficulty": "Medium", "__index_level_0__": 24962, "question": "You are given a binary matrix matrix of size m x n, and you are allowed to rearrange the columns of the matrix in any order.\nReturn the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.\n Example 1:\nInput: matrix = [[0,0,1],[1,1,1],[1,0,1]]\nOutput: 4\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 4.\nExample 2:\nInput: matrix = [[1,0,1,0,1]]\nOutput: 3\nExplanation: You can rearrange the columns as shown above.\nThe largest submatrix of 1s, in bold, has an area of 3.\nExample 3:\nInput: matrix = [[1,1,0],[1,0,1]]\nOutput: 2\nExplanation: Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m * n <= 105\nmatrix[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/cat-and-mouse-ii/discuss/1020616/Python3-Clean-and-Commented-Top-down-DP-with-the-early-stopping-trick", "python_solutions": "class Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n m, n = len(grid), len(grid[0])\n mouse_pos = cat_pos = None\n\t\tavailable = 0 # available steps for mouse and cat\n\t\t# Search the start pos of mouse and cat\n for i in range(m):\n for j in range(n):\n\t\t\t\tif grid[i][j] != '#':\n available += 1\n if grid[i][j] == 'M':\n mouse_pos = (i, j)\n elif grid[i][j] == 'C':\n cat_pos = (i, j)\n \n @functools.lru_cache(None)\n def dp(turn, mouse_pos, cat_pos):\n # if turn == m * n * 2:\n\t\t\t# We already search the whole grid (9372 ms 74.3 MB)\n\t\t\tif turn == available * 2:\n\t\t\t\t# We already search the whole touchable grid (5200 ms 57.5 MB)\n return False\n if turn % 2 == 0:\n # Mouse\n i, j = mouse_pos\n for di, dj in dirs:\n for jump in range(mouseJump + 1):\n\t\t\t\t\t\t# Note that we want to do range(mouseJump + 1) instead of range(1, mouseJump + 1)\n\t\t\t\t\t\t# considering the case that we can stay at the same postion for next turn.\n new_i, new_j = i + di * jump, j + dj * jump\n if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != '#':\n\t\t\t\t\t\t\t# Valid pos\n if dp(turn + 1, (new_i, new_j), cat_pos) or grid[new_i][new_j] == 'F':\n return True\n else:\n\t\t\t\t\t\t\t# Stop extending the jump since we cannot go further\n break\n return False\n else:\n # Cat\n i, j = cat_pos\n for di, dj in dirs:\n for jump in range(catJump + 1):\n new_i, new_j = i + di * jump, j + dj * jump\n if 0 <= new_i < m and 0 <= new_j < n and grid[new_i][new_j] != '#':\n if not dp(turn + 1, mouse_pos, (new_i, new_j)) or (new_i, new_j) == mouse_pos or grid[new_i][new_j] == 'F':\n\t\t\t\t\t\t\t# This condition will also handle the case that the cat cannot jump through the mouse\n return False\n else:\n break\n return True\n\t\t\t\t\n return dp(0, mouse_pos, cat_pos)", "slug": "cat-and-mouse-ii", "post_title": "Python3 Clean & Commented Top-down DP with the early stopping trick", "user": "GBLin5566", "upvotes": 48, "views": 4000, "problem_title": "cat and mouse ii", "number": 1728, "acceptance": 0.402, "difficulty": "Hard", "__index_level_0__": 24966, "question": "A game is played by a cat and a mouse named Cat and Mouse.\nThe environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food.\nPlayers are represented by the characters 'C'(Cat),'M'(Mouse).\nFloors are represented by the character '.' and can be walked on.\nWalls are represented by the character '#' and cannot be walked on.\nFood is represented by the character 'F' and can be walked on.\nThere is only one of each character 'C', 'M', and 'F' in grid.\nMouse and Cat play according to the following rules:\nMouse moves first, then they take turns to move.\nDuring 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.\ncatJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.\nStaying in the same position is allowed.\nMouse can jump over Cat.\nThe game can end in 4 ways:\nIf Cat occupies the same position as Mouse, Cat wins.\nIf Cat reaches the food first, Cat wins.\nIf Mouse reaches the food first, Mouse wins.\nIf Mouse cannot get to the food within 1000 turns, Cat wins.\nGiven a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.\n Example 1:\nInput: grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\nOutput: true\nExplanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.\nExample 2:\nInput: grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\nOutput: true\nExample 3:\nInput: grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\nOutput: false\n Constraints:\nrows == grid.length\ncols = grid[i].length\n1 <= rows, cols <= 8\ngrid[i][j] consist only of characters 'C', 'M', 'F', '.', and '#'.\nThere is only one of each character 'C', 'M', and 'F' in grid.\n1 <= catJump, mouseJump <= 8" }, { "post_href": "https://leetcode.com/problems/find-the-highest-altitude/discuss/1223440/24ms-Python-(with-comments)", "python_solutions": "class Solution(object):\n def largestAltitude(self, gain):\n \"\"\"\n :type gain: List[int]\n :rtype: int\n \"\"\"\n\t\t#initialize a variable to store the end output\n result = 0\n\t\t#initialize a variable to keep track of the altitude at each iteration\n current_altitude=0\n\t\t#looping through each of the gains\n for g in gain:\n\t\t#updating the current altitude based on the gain\n current_altitude += g\n\t\t\t#if the current altitude is greater than the highest altitude recorded then assign it as the result. This done iteratively, allows us to find the highest altitude\n if current_altitude > result:\n result = current_altitude\n return result", "slug": "find-the-highest-altitude", "post_title": "24ms, Python (with comments)", "user": "Akshar-code", "upvotes": 7, "views": 575, "problem_title": "find the highest altitude", "number": 1732, "acceptance": 0.787, "difficulty": "Easy", "__index_level_0__": 24968, "question": "There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.\nYou are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point.\n Example 1:\nInput: gain = [-5,1,5,0,-7]\nOutput: 1\nExplanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.\nExample 2:\nInput: gain = [-4,-3,-2,-1,4,3,2]\nOutput: 0\nExplanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.\n Constraints:\nn == gain.length\n1 <= n <= 100\n-100 <= gain[i] <= 100" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-people-to-teach/discuss/1059885/Python3-count-properly", "python_solutions": "class Solution:\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n m = len(languages)\n languages = [set(x) for x in languages]\n \n mp = {}\n for u, v in friendships: \n if not languages[u-1] & languages[v-1]: \n for i in range(n):\n if i+1 not in languages[u-1]: mp.setdefault(u-1, set()).add(i)\n if i+1 not in languages[v-1]: mp.setdefault(v-1, set()).add(i)\n \n ans = inf\n for i in range(n): \n val = 0\n for k in range(m): \n if i in mp.get(k, set()): val += 1\n ans = min(ans, val)\n return ans", "slug": "minimum-number-of-people-to-teach", "post_title": "[Python3] count properly", "user": "ye15", "upvotes": 1, "views": 107, "problem_title": "minimum number of people to teach", "number": 1733, "acceptance": 0.418, "difficulty": "Medium", "__index_level_0__": 25014, "question": "On a social network consisting of m users and some friendships between users, two users can communicate with each other if they know a common language.\nYou are given an integer n, an array languages, and an array friendships where:\nThere are n languages numbered 1 through n,\nlanguages[i] is the set of languages the ith user knows, and\nfriendships[i] = [ui, vi] denotes a friendship between the users ui and vi.\nYou can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.\nNote that friendships are not transitive, meaning if x is a friend of y and y is a friend of z, this doesn't guarantee that x is a friend of z.\n Example 1:\nInput: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]\nOutput: 1\nExplanation: You can either teach user 1 the second language or user 2 the first language.\nExample 2:\nInput: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]\nOutput: 2\nExplanation: Teach the third language to users 1 and 3, yielding two users to teach.\n Constraints:\n2 <= n <= 500\nlanguages.length == m\n1 <= m <= 500\n1 <= languages[i].length <= n\n1 <= languages[i][j] <= n\n1 <= ui < vi <= languages.length\n1 <= friendships.length <= 500\nAll tuples (ui, vi) are unique\nlanguages[i] contains only unique values" }, { "post_href": "https://leetcode.com/problems/decode-xored-permutation/discuss/1031227/Python-or-Detailed-Exeplanation-by-finding-the-first-one", "python_solutions": "class Solution:\n def decode(self, encoded: List[int]) -> List[int]:\n n = len(encoded)+1\n XOR = 0\n for i in range(1,n+1):\n XOR = XOR^i\n \n s = 0\n for i in range(1,n,2):\n s = s^encoded[i]\n res = [0]*n\n res[0] = XOR^s\n \n for j in range(1,n):\n res[j] = res[j-1]^encoded[j-1]\n return res", "slug": "decode-xored-permutation", "post_title": "Python | Detailed Exeplanation by finding the first one", "user": "jmin3", "upvotes": 1, "views": 111, "problem_title": "decode xored permutation", "number": 1734, "acceptance": 0.624, "difficulty": "Medium", "__index_level_0__": 25017, "question": "There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.\nIt was encoded into another integer array encoded of length n - 1, such that encoded[i] = perm[i] XOR perm[i + 1]. For example, if perm = [1,3,2], then encoded = [2,1].\nGiven the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.\n Example 1:\nInput: encoded = [3,1]\nOutput: [1,2,3]\nExplanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]\nExample 2:\nInput: encoded = [6,5,4,6]\nOutput: [2,4,1,5,3]\n Constraints:\n3 <= n < 105\nn is odd.\nencoded.length == n - 1" }, { "post_href": "https://leetcode.com/problems/count-ways-to-make-array-with-product/discuss/1355240/No-Maths-Just-Recursion-DP-we-can-come-up-with-in-interviews-greater-WA", "python_solutions": "class Solution:\n def waysToFillArray(self, queries: List[List[int]]) -> List[int]:\n # brute DP O(NK) where N is max(q[0]) and K is max(q[1])\n @cache\n def dp(n,k):\n \n if k == 1 or n == 1: return 1\n ways = 0\n for factor in range(1, k+1):\n if k % factor == 0:\n ways += dp(n-1, k//factor) # or take the '3' part\n ways %= (10**9+7)\n return ways % (10**9+7)\n \n res = [0] * len(queries)\n for i,(n, k) in enumerate(queries):\n res[i] = dp(n,k)\n \n return res\n \n # better solution -> find out how many prime factors a number has.\n # how many ways to group P numbers into N groups (since array has N values only)\n # but you can group in lesser groups and keep 1 1 1 1 as padding in array :(", "slug": "count-ways-to-make-array-with-product", "post_title": "No Maths Just Recursion DP we can come up with in interviews -> WA", "user": "yozaam", "upvotes": 1, "views": 326, "problem_title": "count ways to make array with product", "number": 1735, "acceptance": 0.506, "difficulty": "Hard", "__index_level_0__": 25020, "question": "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.\nReturn an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.\n Example 1:\nInput: queries = [[2,6],[5,1],[73,660]]\nOutput: [4,1,50734910]\nExplanation: Each query is independent.\n[2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n[5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n[73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.\nExample 2:\nInput: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput: [1,2,3,10,5]\n Constraints:\n1 <= queries.length <= 104 \n1 <= ni, ki <= 104" }, { "post_href": "https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/discuss/1032030/Python3-if-elif", "python_solutions": "class Solution:\n def maximumTime(self, time: str) -> str:\n time = list(time)\n for i in range(len(time)): \n if time[i] == \"?\": \n if i == 0: time[i] = \"2\" if time[i+1] in \"?0123\" else \"1\"\n elif i == 1: time[i] = \"3\" if time[0] == \"2\" else \"9\"\n elif i == 3: time[i] = \"5\"\n else: time[i] = \"9\"\n return \"\".join(time)", "slug": "latest-time-by-replacing-hidden-digits", "post_title": "[Python3] if-elif", "user": "ye15", "upvotes": 27, "views": 1500, "problem_title": "latest time by replacing hidden digits", "number": 1736, "acceptance": 0.422, "difficulty": "Easy", "__index_level_0__": 25025, "question": "You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).\nThe valid times are those inclusively between 00:00 and 23:59.\nReturn the latest valid time you can get from time by replacing the hidden digits.\n Example 1:\nInput: time = \"2?:?0\"\nOutput: \"23:50\"\nExplanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.\nExample 2:\nInput: time = \"0?:3?\"\nOutput: \"09:39\"\nExample 3:\nInput: time = \"1?:22\"\nOutput: \"19:22\"\n Constraints:\ntime is in the format hh:mm.\nIt is guaranteed that you can produce a valid time from the given string." }, { "post_href": "https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/discuss/1032055/Python3-scan-through-a-z-w-prefix", "python_solutions": "class Solution:\n def minCharacters(self, a: str, b: str) -> int:\n pa, pb = [0]*26, [0]*26\n for x in a: pa[ord(x)-97] += 1\n for x in b: pb[ord(x)-97] += 1\n \n ans = len(a) - max(pa) + len(b) - max(pb) # condition 3\n for i in range(25): \n pa[i+1] += pa[i]\n pb[i+1] += pb[i]\n ans = min(ans, pa[i] + len(b) - pb[i]) # condition 2\n ans = min(ans, len(a) - pa[i] + pb[i]) # condition 1\n return ans", "slug": "change-minimum-characters-to-satisfy-one-of-three-conditions", "post_title": "[Python3] scan through a-z w/ prefix", "user": "ye15", "upvotes": 1, "views": 58, "problem_title": "change minimum characters to satisfy one of three conditions", "number": 1737, "acceptance": 0.352, "difficulty": "Medium", "__index_level_0__": 25042, "question": "You are given two strings a and b that consist of lowercase letters. In one operation, you can change any character in a or b to any lowercase letter.\nYour goal is to satisfy one of the following three conditions:\nEvery letter in a is strictly less than every letter in b in the alphabet.\nEvery letter in b is strictly less than every letter in a in the alphabet.\nBoth a and b consist of only one distinct letter.\nReturn the minimum number of operations needed to achieve your goal.\n Example 1:\nInput: a = \"aba\", b = \"caa\"\nOutput: 2\nExplanation: Consider the best way to make each condition true:\n1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\nThe best way was done in 2 operations (either condition 1 or condition 3).\nExample 2:\nInput: a = \"dabadd\", b = \"cda\"\nOutput: 3\nExplanation: The best way is to make condition 1 true by changing b to \"eee\".\n Constraints:\n1 <= a.length, b.length <= 105\na and b consist only of lowercase letters." }, { "post_href": "https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/discuss/1032117/Python3-compute-xor-O(MNlog(MN))-or-O(MNlogK)-or-O(MN)", "python_solutions": "class Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n m, n = len(matrix), len(matrix[0]) # dimensions \n \n ans = []\n for i in range(m): \n for j in range(n): \n if i: matrix[i][j] ^= matrix[i-1][j]\n if j: matrix[i][j] ^= matrix[i][j-1]\n if i and j: matrix[i][j] ^= matrix[i-1][j-1]\n ans.append(matrix[i][j])\n return sorted(ans)[-k]", "slug": "find-kth-largest-xor-coordinate-value", "post_title": "[Python3] compute xor O(MNlog(MN)) | O(MNlogK) | O(MN)", "user": "ye15", "upvotes": 15, "views": 936, "problem_title": "find kth largest xor coordinate value", "number": 1738, "acceptance": 0.613, "difficulty": "Medium", "__index_level_0__": 25043, "question": "You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.\nThe value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed).\nFind the kth largest value (1-indexed) of all the coordinates of matrix.\n Example 1:\nInput: matrix = [[5,2],[1,6]], k = 1\nOutput: 7\nExplanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.\nExample 2:\nInput: matrix = [[5,2],[1,6]], k = 2\nOutput: 5\nExplanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.\nExample 3:\nInput: matrix = [[5,2],[1,6]], k = 3\nOutput: 4\nExplanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.\n Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 1000\n0 <= matrix[i][j] <= 106\n1 <= k <= m * n" }, { "post_href": "https://leetcode.com/problems/building-boxes/discuss/1032104/Python3-math", "python_solutions": "class Solution:\n def minimumBoxes(self, n: int) -> int:\n x = int((6*n)**(1/3))\n if x*(x+1)*(x+2) > 6*n: x -= 1\n \n ans = x*(x+1)//2\n n -= x*(x+1)*(x+2)//6\n k = 1\n while n > 0: \n ans += 1\n n -= k\n k += 1\n return ans", "slug": "building-boxes", "post_title": "[Python3] math", "user": "ye15", "upvotes": 12, "views": 371, "problem_title": "building boxes", "number": 1739, "acceptance": 0.519, "difficulty": "Hard", "__index_level_0__": 25050, "question": "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:\nYou can place the boxes anywhere on the floor.\nIf 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.\nGiven an integer n, return the minimum possible number of boxes touching the floor.\n Example 1:\nInput: n = 3\nOutput: 3\nExplanation: The figure above is for the placement of the three boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\nExample 2:\nInput: n = 4\nOutput: 3\nExplanation: The figure above is for the placement of the four boxes.\nThese boxes are placed in the corner of the room, where the corner is on the left side.\nExample 3:\nInput: n = 10\nOutput: 6\nExplanation: The figure above is for the placement of the ten boxes.\nThese boxes are placed in the corner of the room, where the corner is on the back side.\n Constraints:\n1 <= n <= 109" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-balls-in-a-box/discuss/1042922/Python3-freq-table", "python_solutions": "class Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n freq = defaultdict(int)\n for x in range(lowLimit, highLimit+1):\n freq[sum(int(xx) for xx in str(x))] += 1\n return max(freq.values())", "slug": "maximum-number-of-balls-in-a-box", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 11, "views": 1300, "problem_title": "maximum number of balls in a box", "number": 1742, "acceptance": 0.7390000000000001, "difficulty": "Easy", "__index_level_0__": 25056, "question": "You are working in a ball factory where you have n balls numbered from lowLimit up to highLimit inclusive (i.e., n == highLimit - lowLimit + 1), and an infinite number of boxes numbered from 1 to infinity.\nYour job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number 321 will be put in the box number 3 + 2 + 1 = 6 and the ball number 10 will be put in the box number 1 + 0 = 1.\nGiven two integers lowLimit and highLimit, return the number of balls in the box with the most balls.\n Example 1:\nInput: lowLimit = 1, highLimit = 10\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 2 1 1 1 1 1 1 1 1 0 0 ...\nBox 1 has the most number of balls with 2 balls.\nExample 2:\nInput: lowLimit = 5, highLimit = 15\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 ...\nBall Count: 1 1 1 1 2 2 1 1 1 0 0 ...\nBoxes 5 and 6 have the most number of balls with 2 balls in each.\nExample 3:\nInput: lowLimit = 19, highLimit = 28\nOutput: 2\nExplanation:\nBox Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\nBall Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\nBox 10 has the most number of balls with 2 balls.\n Constraints:\n1 <= lowLimit <= highLimit <= 105" }, { "post_href": "https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/discuss/1042939/Python3-graph", "python_solutions": "class Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n graph = {}\n for u, v in adjacentPairs: \n graph.setdefault(u, []).append(v)\n graph.setdefault(v, []).append(u)\n \n ans = []\n seen = set()\n stack = [next(x for x in graph if len(graph[x]) == 1)]\n while stack: \n n = stack.pop()\n ans.append(n)\n seen.add(n)\n for nn in graph[n]: \n if nn not in seen: stack.append(nn)\n return ans", "slug": "restore-the-array-from-adjacent-pairs", "post_title": "[Python3] graph", "user": "ye15", "upvotes": 14, "views": 1300, "problem_title": "restore the array from adjacent pairs", "number": 1743, "acceptance": 0.687, "difficulty": "Medium", "__index_level_0__": 25076, "question": "There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums.\nYou are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that the elements ui and vi are adjacent in nums.\nIt is guaranteed that every adjacent pair of elements nums[i] and nums[i+1] will exist in adjacentPairs, either as [nums[i], nums[i+1]] or [nums[i+1], nums[i]]. The pairs can appear in any order.\nReturn the original array nums. If there are multiple solutions, return any of them.\n Example 1:\nInput: adjacentPairs = [[2,1],[3,4],[3,2]]\nOutput: [1,2,3,4]\nExplanation: This array has all its adjacent pairs in adjacentPairs.\nNotice that adjacentPairs[i] may not be in left-to-right order.\nExample 2:\nInput: adjacentPairs = [[4,-2],[1,4],[-3,1]]\nOutput: [-2,4,1,-3]\nExplanation: There can be negative numbers.\nAnother solution is [-3,1,4,-2], which would also be accepted.\nExample 3:\nInput: adjacentPairs = [[100000,-100000]]\nOutput: [100000,-100000]\n Constraints:\nnums.length == n\nadjacentPairs.length == n - 1\nadjacentPairs[i].length == 2\n2 <= n <= 105\n-105 <= nums[i], ui, vi <= 105\nThere exists some nums that has adjacentPairs as its pairs." }, { "post_href": "https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/discuss/1042952/Python3-greedy", "python_solutions": "class Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = [0]\n for x in candiesCount: prefix.append(prefix[-1] + x) # prefix sum \n return [prefix[t] < (day+1)*cap and day < prefix[t+1] for t, day, cap in queries]", "slug": "can-you-eat-your-favorite-candy-on-your-favorite-day", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 6, "views": 279, "problem_title": "can you eat your favorite candy on your favorite day", "number": 1744, "acceptance": 0.3289999999999999, "difficulty": "Medium", "__index_level_0__": 25089, "question": "You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi].\nYou play a game with the following rules:\nYou start eating candies on day 0.\nYou cannot eat any candy of type i unless you have eaten all candies of type i - 1.\nYou must eat at least one candy per day until you have eaten all the candies.\nConstruct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2.\nReturn the constructed array answer.\n Example 1:\nInput: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]\nOutput: [true,false,true]\nExplanation:\n1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2.\n2- You can eat at most 4 candies each day.\n If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1.\n On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2.\n3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.\nExample 2:\nInput: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]\nOutput: [false,true,true,false,false]\n Constraints:\n1 <= candiesCount.length <= 105\n1 <= candiesCount[i] <= 105\n1 <= queries.length <= 105\nqueries[i].length == 3\n0 <= favoriteTypei < candiesCount.length\n0 <= favoriteDayi <= 109\n1 <= dailyCapi <= 109" }, { "post_href": "https://leetcode.com/problems/palindrome-partitioning-iv/discuss/1042964/Python3-dp", "python_solutions": "class Solution:\n def checkPartitioning(self, s: str) -> bool:\n mp = {}\n for i in range(2*len(s)-1): \n lo, hi = i//2, (i+1)//2\n while 0 <= lo <= hi < len(s) and s[lo] == s[hi]: \n mp.setdefault(lo, set()).add(hi)\n lo -= 1\n hi += 1\n \n @lru_cache(None)\n def fn(i, k): \n \"\"\"Return True if s[i:] can be split into k palindromic substrings.\"\"\"\n if k < 0: return False \n if i == len(s): return k == 0\n return any(fn(ii+1, k-1) for ii in mp[i])\n \n return fn(0, 3)", "slug": "palindrome-partitioning-iv", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 10, "views": 725, "problem_title": "palindrome partitioning iv", "number": 1745, "acceptance": 0.4589999999999999, "difficulty": "Hard", "__index_level_0__": 25090, "question": "Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.\nA string is said to be palindrome if it the same string when reversed.\n Example 1:\nInput: s = \"abcbdd\"\nOutput: true\nExplanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\nExample 2:\nInput: s = \"bcbddxy\"\nOutput: false\nExplanation: s cannot be split into 3 palindromes.\n Constraints:\n3 <= s.length <= 2000\ns consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/sum-of-unique-elements/discuss/1103188/Runtime-97-or-Python-easy-hashmap-solution", "python_solutions": "class Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n hashmap = {}\n for i in nums:\n if i in hashmap.keys():\n hashmap[i] += 1\n else:\n hashmap[i] = 1\n sum = 0\n for k, v in hashmap.items():\n if v == 1: sum += k\n return sum", "slug": "sum-of-unique-elements", "post_title": "Runtime 97% | Python easy hashmap solution", "user": "vanigupta20024", "upvotes": 19, "views": 1900, "problem_title": "sum of unique elements", "number": 1748, "acceptance": 0.757, "difficulty": "Easy", "__index_level_0__": 25095, "question": "You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.\nReturn the sum of all the unique elements of nums.\n Example 1:\nInput: nums = [1,2,3,2]\nOutput: 4\nExplanation: The unique elements are [1,3], and the sum is 4.\nExample 2:\nInput: nums = [1,1,1,1,1]\nOutput: 0\nExplanation: There are no unique elements, and the sum is 0.\nExample 3:\nInput: nums = [1,2,3,4,5]\nOutput: 15\nExplanation: The unique elements are [1,2,3,4,5], and the sum is 15.\n Constraints:\n1 <= nums.length <= 100\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-absolute-sum-of-any-subarray/discuss/1056653/Python3-Kadane's-algo", "python_solutions": "class Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n ans = mx = mn = 0\n for x in nums: \n mx = max(mx + x, 0)\n mn = min(mn + x, 0)\n ans = max(ans, mx, -mn)\n return ans", "slug": "maximum-absolute-sum-of-any-subarray", "post_title": "[Python3] Kadane's algo", "user": "ye15", "upvotes": 10, "views": 329, "problem_title": "maximum absolute sum of any subarray", "number": 1749, "acceptance": 0.583, "difficulty": "Medium", "__index_level_0__": 25141, "question": "You are given an integer array nums. The absolute sum of a subarray [numsl, numsl+1, ..., numsr-1, numsr] is abs(numsl + numsl+1 + ... + numsr-1 + numsr).\nReturn the maximum absolute sum of any (possibly empty) subarray of nums.\nNote that abs(x) is defined as follows:\nIf x is a negative integer, then abs(x) = -x.\nIf x is a non-negative integer, then abs(x) = x.\n Example 1:\nInput: nums = [1,-3,2,3,-4]\nOutput: 5\nExplanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.\nExample 2:\nInput: nums = [2,-5,1,-4,3,-2]\nOutput: 8\nExplanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.\n Constraints:\n1 <= nums.length <= 105\n-104 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/discuss/1056664/Python3-3-approaches", "python_solutions": "class Solution:\n def minimumLength(self, s: str) -> int:\n dd = deque(s)\n while len(dd) >= 2 and dd[0] == dd[-1]:\n ch = dd[0]\n while dd and dd[0] == ch: dd.popleft()\n while dd and dd[-1] == ch: dd.pop()\n return len(dd)", "slug": "minimum-length-of-string-after-deleting-similar-ends", "post_title": "[Python3] 3 approaches", "user": "ye15", "upvotes": 2, "views": 74, "problem_title": "minimum length of string after deleting similar ends", "number": 1750, "acceptance": 0.436, "difficulty": "Medium", "__index_level_0__": 25156, "question": "Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:\nPick a non-empty prefix from the string s where all the characters in the prefix are equal.\nPick a non-empty suffix from the string s where all the characters in this suffix are equal.\nThe prefix and the suffix should not intersect at any index.\nThe characters from the prefix and suffix must be the same.\nDelete both the prefix and the suffix.\nReturn the minimum length of s after performing the above operation any number of times (possibly zero times).\n Example 1:\nInput: s = \"ca\"\nOutput: 2\nExplanation: You can't remove any characters, so the string stays as is.\nExample 2:\nInput: s = \"cabaabac\"\nOutput: 0\nExplanation: An optimal sequence of operations is:\n- Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n- Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n- Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".\nExample 3:\nInput: s = \"aabccabba\"\nOutput: 3\nExplanation: An optimal sequence of operations is:\n- Take prefix = \"aa\" and suffix = \"a\" and remove them, s = \"bccabb\".\n- Take prefix = \"b\" and suffix = \"bb\" and remove them, s = \"cca\".\n Constraints:\n1 <= s.length <= 105\ns only consists of characters 'a', 'b', and 'c'." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended-ii/discuss/1103634/Python3-(DP)-Simple-Solution-Explained", "python_solutions": "class Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n \n # The number of events\n n = len(events)\n # Sort the events in chronological order\n events.sort()\n \n # k is the number of events we can attend\n # end is the last event we attended's END TIME\n # event_index is the current event we are checking\n @lru_cache(None)\n def dp(end: int, event_index: int, k: int):\n \n # No more events left or we have checked all possible events\n if k == 0 or event_index == n:\n return 0\n \n event = events[event_index]\n event_start, event_end, event_value = event\n # Can we attend this event?\n # Does its start time conflict with the previous events end time?\n # If the start time is the same as the end time we cannot end as well (view example 2)\n if event_start <= end:\n # Could not attend, check the next event\n return dp(end, event_index + 1, k)\n \n # We made it here, so we can attend!\n # Two possible options, we either attend (add the value) or do not attend this event\n # Value for attending versus the value for skipping\n attend = event_value + dp(event_end, event_index + 1, k - 1)\n skip = dp(end, event_index + 1, k)\n \n # Get the best option\n return max(attend, skip)\n \n # Clear cache to save memory\n dp.cache_clear()\n return dp(0, 0, k)", "slug": "maximum-number-of-events-that-can-be-attended-ii", "post_title": "[Python3] (DP) Simple Solution Explained", "user": "scornz", "upvotes": 11, "views": 637, "problem_title": "maximum number of events that can be attended ii", "number": 1751, "acceptance": 0.56, "difficulty": "Hard", "__index_level_0__": 25167, "question": "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.\nYou can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\nReturn the maximum sum of values that you can receive by attending events.\n Example 1:\nInput: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\nOutput: 7\nExplanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\nExample 2:\nInput: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\nOutput: 10\nExplanation: Choose event 2 for a total value of 10.\nNotice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\nExample 3:\nInput: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\nOutput: 9\nExplanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n Constraints:\n1 <= k <= events.length\n1 <= k * events.length <= 106\n1 <= startDayi <= endDayi <= 109\n1 <= valuei <= 106" }, { "post_href": "https://leetcode.com/problems/check-if-array-is-sorted-and-rotated/discuss/1053871/Python-Slicing-(easy-to-understand)", "python_solutions": "class Solution:\n def check(self, nums: List[int]) -> bool:\n i = 0\n while inums[i+1]: break # used to find the rotated position\n i+=1\n \n rotated = nums[i+1:]+nums[:i+1]\n for i,e in enumerate(rotated):\n if irotated[i+1]: # check that rerotated array sorted or not\n return False\n return True", "slug": "check-if-array-is-sorted-and-rotated", "post_title": "Python - Slicing (easy to understand)", "user": "qwe9", "upvotes": 12, "views": 966, "problem_title": "check if array is sorted and rotated", "number": 1752, "acceptance": 0.493, "difficulty": "Easy", "__index_level_0__": 25172, "question": "Given an array nums, return true if the array was originally sorted in non-decreasing order, then rotated some number of positions (including zero). Otherwise, return false.\nThere may be duplicates in the original array.\nNote: An array A rotated by x positions results in an array B of the same length such that A[i] == B[(i+x) % A.length], where % is the modulo operation.\n Example 1:\nInput: nums = [3,4,5,1,2]\nOutput: true\nExplanation: [1,2,3,4,5] is the original sorted array.\nYou can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].\nExample 2:\nInput: nums = [2,1,3,4]\nOutput: false\nExplanation: There is no sorted array once rotated that can make nums.\nExample 3:\nInput: nums = [1,2,3]\nOutput: true\nExplanation: [1,2,3] is the original sorted array.\nYou can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n Constraints:\n1 <= nums.length <= 100\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/maximum-score-from-removing-stones/discuss/1053645/Python3-math", "python_solutions": "class Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n a, b, c = sorted((a, b, c))\n if a + b < c: return a + b\n return (a + b + c)//2", "slug": "maximum-score-from-removing-stones", "post_title": "[Python3] math", "user": "ye15", "upvotes": 15, "views": 745, "problem_title": "maximum score from removing stones", "number": 1753, "acceptance": 0.662, "difficulty": "Medium", "__index_level_0__": 25209, "question": "You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).\nGiven three integers a, b, and c, return the maximum score you can get.\n Example 1:\nInput: a = 2, b = 4, c = 6\nOutput: 6\nExplanation: The starting state is (2, 4, 6). One optimal set of moves is:\n- Take from 1st and 3rd piles, state is now (1, 4, 5)\n- Take from 1st and 3rd piles, state is now (0, 4, 4)\n- Take from 2nd and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 6 points.\nExample 2:\nInput: a = 4, b = 4, c = 6\nOutput: 7\nExplanation: The starting state is (4, 4, 6). One optimal set of moves is:\n- Take from 1st and 2nd piles, state is now (3, 3, 6)\n- Take from 1st and 3rd piles, state is now (2, 3, 5)\n- Take from 1st and 3rd piles, state is now (1, 3, 4)\n- Take from 1st and 3rd piles, state is now (0, 3, 3)\n- Take from 2nd and 3rd piles, state is now (0, 2, 2)\n- Take from 2nd and 3rd piles, state is now (0, 1, 1)\n- Take from 2nd and 3rd piles, state is now (0, 0, 0)\nThere are fewer than two non-empty piles, so the game ends. Total: 7 points.\nExample 3:\nInput: a = 1, b = 8, c = 8\nOutput: 8\nExplanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\nAfter that, there are fewer than two non-empty piles, so the game ends.\n Constraints:\n1 <= a, b, c <= 105" }, { "post_href": "https://leetcode.com/problems/largest-merge-of-two-strings/discuss/1053605/Python3-greedy", "python_solutions": "class Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n ans = []\n i1 = i2 = 0\n while i1 < len(word1) and i2 < len(word2): \n if word1[i1:] > word2[i2:]: \n ans.append(word1[i1])\n i1 += 1\n else: \n ans.append(word2[i2])\n i2 += 1\n return \"\".join(ans) + word1[i1:] + word2[i2:]", "slug": "largest-merge-of-two-strings", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 6, "views": 251, "problem_title": "largest merge of two strings", "number": 1754, "acceptance": 0.451, "difficulty": "Medium", "__index_level_0__": 25223, "question": "You are given two strings word1 and word2. You want to construct a string merge in the following way: while either word1 or word2 are non-empty, choose one of the following options:\nIf word1 is non-empty, append the first character in word1 to merge and delete it from word1.\nFor example, if word1 = \"abc\" and merge = \"dv\", then after choosing this operation, word1 = \"bc\" and merge = \"dva\".\nIf word2 is non-empty, append the first character in word2 to merge and delete it from word2.\nFor example, if word2 = \"abc\" and merge = \"\", then after choosing this operation, word2 = \"bc\" and merge = \"a\".\nReturn the lexicographically largest merge you can construct.\nA string a is lexicographically larger than a string b (of the same length) if in the first position where a and b differ, a has a character strictly larger than the corresponding character in b. For example, \"abcd\" is lexicographically larger than \"abcc\" because the first position they differ is at the fourth character, and d is greater than c.\n Example 1:\nInput: word1 = \"cabaa\", word2 = \"bcaaa\"\nOutput: \"cbcabaaaaa\"\nExplanation: One way to get the lexicographically largest merge is:\n- Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n- Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n- Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n- Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n- Append the remaining 5 a's from word1 and word2 at the end of merge.\nExample 2:\nInput: word1 = \"abcabc\", word2 = \"abdcaba\"\nOutput: \"abdcabcabcaba\"\n Constraints:\n1 <= word1.length, word2.length <= 3000\nword1 and word2 consist only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/closest-subsequence-sum/discuss/1053790/Python3-divide-in-half", "python_solutions": "class Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n \n def fn(nums):\n ans = {0}\n for x in nums: \n ans |= {x + y for y in ans}\n return ans \n \n nums0 = sorted(fn(nums[:len(nums)//2]))\n \n ans = inf\n for x in fn(nums[len(nums)//2:]): \n k = bisect_left(nums0, goal - x)\n if k < len(nums0): ans = min(ans, nums0[k] + x - goal)\n if 0 < k: ans = min(ans, goal - x - nums0[k-1])\n return ans", "slug": "closest-subsequence-sum", "post_title": "[Python3] divide in half", "user": "ye15", "upvotes": 28, "views": 1400, "problem_title": "closest subsequence sum", "number": 1755, "acceptance": 0.364, "difficulty": "Hard", "__index_level_0__": 25230, "question": "You are given an integer array nums and an integer goal.\nYou want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).\nReturn the minimum possible value of abs(sum - goal).\nNote that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.\n Example 1:\nInput: nums = [5,-7,3,5], goal = 6\nOutput: 0\nExplanation: Choose the whole array as a subsequence, with a sum of 6.\nThis is equal to the goal, so the absolute difference is 0.\nExample 2:\nInput: nums = [7,-9,15,-2], goal = -5\nOutput: 1\nExplanation: Choose the subsequence [7,-9,-2], with a sum of -4.\nThe absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\nExample 3:\nInput: nums = [1,2,3], goal = -7\nOutput: 7\n Constraints:\n1 <= nums.length <= 40\n-107 <= nums[i] <= 107\n-109 <= goal <= 109" }, { "post_href": "https://leetcode.com/problems/minimum-changes-to-make-alternating-binary-string/discuss/1437401/Python3-solution-or-O(n)-or-Explained", "python_solutions": "class Solution:\n def minOperations(self, s: str) -> int:\n count = 0\n count1 = 0\n for i in range(len(s)):\n if i % 2 == 0:\n if s[i] == '1':\n count += 1\n if s[i] == '0':\n count1 += 1\n else:\n if s[i] == '0':\n count += 1\n if s[i] == '1':\n count1 += 1\n return min(count, count1)", "slug": "minimum-changes-to-make-alternating-binary-string", "post_title": "Python3 solution | O(n) | Explained", "user": "FlorinnC1", "upvotes": 10, "views": 425, "problem_title": "minimum changes to make alternating binary string", "number": 1758, "acceptance": 0.583, "difficulty": "Easy", "__index_level_0__": 25233, "question": "You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.\nThe string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not.\nReturn the minimum number of operations needed to make s alternating.\n Example 1:\nInput: s = \"0100\"\nOutput: 1\nExplanation: If you change the last character to '1', s will be \"0101\", which is alternating.\nExample 2:\nInput: s = \"10\"\nOutput: 0\nExplanation: s is already alternating.\nExample 3:\nInput: s = \"1111\"\nOutput: 2\nExplanation: You need two operations to reach \"0101\" or \"1010\".\n Constraints:\n1 <= s.length <= 104\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/count-number-of-homogenous-substrings/discuss/1064598/Python-one-pass-with-explanation", "python_solutions": "class Solution:\n def countHomogenous(self, s: str) -> int:\n res, count, n = 0, 1, len(s)\n for i in range(1,n):\n if s[i]==s[i-1]:\n count+=1\n else:\n if count>1:\n res+=(count*(count-1)//2)\n count=1 \n if count>1:\n res+=(count*(count-1)//2)\n return (res+n)%(10**9+7)", "slug": "count-number-of-homogenous-substrings", "post_title": "Python - one pass - with explanation", "user": "ajith6198", "upvotes": 6, "views": 353, "problem_title": "count number of homogenous substrings", "number": 1759, "acceptance": 0.48, "difficulty": "Medium", "__index_level_0__": 25256, "question": "Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.\nA string is homogenous if all the characters of the string are the same.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: s = \"abbcccaa\"\nOutput: 13\nExplanation: The homogenous substrings are listed as below:\n\"a\" appears 3 times.\n\"aa\" appears 1 time.\n\"b\" appears 2 times.\n\"bb\" appears 1 time.\n\"c\" appears 3 times.\n\"cc\" appears 2 times.\n\"ccc\" appears 1 time.\n3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\nExample 2:\nInput: s = \"xy\"\nOutput: 2\nExplanation: The homogenous substrings are \"x\" and \"y\".\nExample 3:\nInput: s = \"zzzzz\"\nOutput: 15\n Constraints:\n1 <= s.length <= 105\ns consists of lowercase letters." }, { "post_href": "https://leetcode.com/problems/minimum-limit-of-balls-in-a-bag/discuss/1064572/Python3-binary-search", "python_solutions": "class Solution:\n def minimumSize(self, nums: List[int], maxOperations: int) -> int:\n lo, hi = 1, 1_000_000_000\n while lo < hi: \n mid = lo + hi >> 1\n if sum((x-1)//mid for x in nums) <= maxOperations: hi = mid\n else: lo = mid + 1\n return lo", "slug": "minimum-limit-of-balls-in-a-bag", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 2, "views": 238, "problem_title": "minimum limit of balls in a bag", "number": 1760, "acceptance": 0.603, "difficulty": "Medium", "__index_level_0__": 25271, "question": "You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.\nYou can perform the following operation at most maxOperations times:\nTake any bag of balls and divide it into two new bags with a positive number of balls.\nFor example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.\nYour penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.\nReturn the minimum possible penalty after performing the operations.\n Example 1:\nInput: nums = [9], maxOperations = 2\nOutput: 3\nExplanation: \n- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].\n- Divide the bag with 6 balls into two bags of sizes 3 and 3. [6,3] -> [3,3,3].\nThe bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\nExample 2:\nInput: nums = [2,4,8,2], maxOperations = 4\nOutput: 2\nExplanation:\n- Divide the bag with 8 balls into two bags of sizes 4 and 4. [2,4,8,2] -> [2,4,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,4,4,4,2] -> [2,2,2,4,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,4,4,2] -> [2,2,2,2,2,4,2].\n- Divide the bag with 4 balls into two bags of sizes 2 and 2. [2,2,2,2,2,4,2] -> [2,2,2,2,2,2,2,2].\nThe bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.\n Constraints:\n1 <= nums.length <= 105\n1 <= maxOperations, nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/discuss/1065724/Python3-brute-force", "python_solutions": "class Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n graph = [[False]*n for _ in range(n)]\n degree = [0]*n\n \n for u, v in edges: \n graph[u-1][v-1] = graph[v-1][u-1] = True\n degree[u-1] += 1\n degree[v-1] += 1\n \n ans = inf\n for i in range(n): \n for j in range(i+1, n):\n if graph[i][j]: \n for k in range(j+1, n):\n if graph[j][k] and graph[k][i]: \n ans = min(ans, degree[i] + degree[j] + degree[k] - 6)\n return ans if ans < inf else -1", "slug": "minimum-degree-of-a-connected-trio-in-a-graph", "post_title": "[Python3] brute-force", "user": "ye15", "upvotes": 6, "views": 389, "problem_title": "minimum degree of a connected trio in a graph", "number": 1761, "acceptance": 0.417, "difficulty": "Hard", "__index_level_0__": 25276, "question": "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.\nA connected trio is a set of three nodes where there is an edge between every pair of them.\nThe degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\nReturn the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.\n Example 1:\nInput: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\nOutput: 3\nExplanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\nExample 2:\nInput: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\nOutput: 0\nExplanation: There are exactly three trios:\n1) [1,4,3] with degree 0.\n2) [2,5,6] with degree 2.\n3) [5,6,7] with degree 2.\n Constraints:\n2 <= n <= 400\nedges[i].length == 2\n1 <= edges.length <= n * (n-1) / 2\n1 <= ui, vi <= n\nui != vi\nThere are no repeated edges." }, { "post_href": "https://leetcode.com/problems/longest-nice-substring/discuss/1074546/Python3-brute-force-and-divide-and-conquer", "python_solutions": "class Solution:\n def longestNiceSubstring(self, s: str) -> str:\n ans = \"\"\n for i in range(len(s)):\n for ii in range(i+1, len(s)+1):\n if all(s[k].swapcase() in s[i:ii] for k in range(i, ii)): \n ans = max(ans, s[i:ii], key=len)\n return ans", "slug": "longest-nice-substring", "post_title": "[Python3] brute-force & divide and conquer", "user": "ye15", "upvotes": 65, "views": 4800, "problem_title": "longest nice substring", "number": 1763, "acceptance": 0.616, "difficulty": "Easy", "__index_level_0__": 25279, "question": "A string s is nice if, for every letter of the alphabet that s contains, it appears both in uppercase and lowercase. For example, \"abABB\" is nice because 'A' and 'a' appear, and 'B' and 'b' appear. However, \"abA\" is not because 'b' appears, but 'B' does not.\nGiven a string s, return the longest substring of s that is nice. If there are multiple, return the substring of the earliest occurrence. If there are none, return an empty string.\n Example 1:\nInput: s = \"YazaAay\"\nOutput: \"aAa\"\nExplanation: \"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n\"aAa\" is the longest nice substring.\nExample 2:\nInput: s = \"Bb\"\nOutput: \"Bb\"\nExplanation: \"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\nExample 3:\nInput: s = \"c\"\nOutput: \"\"\nExplanation: There are no nice substrings.\n Constraints:\n1 <= s.length <= 100\ns consists of uppercase and lowercase English letters." }, { "post_href": "https://leetcode.com/problems/form-array-by-concatenating-subarrays-of-another-array/discuss/1074555/Python3-check-group-one-by-one", "python_solutions": "class Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n i = 0\n for grp in groups: \n for ii in range(i, len(nums)):\n if nums[ii:ii+len(grp)] == grp: \n i = ii + len(grp)\n break \n else: return False\n return True", "slug": "form-array-by-concatenating-subarrays-of-another-array", "post_title": "[Python3] check group one-by-one", "user": "ye15", "upvotes": 28, "views": 1300, "problem_title": "form array by concatenating subarrays of another array", "number": 1764, "acceptance": 0.527, "difficulty": "Medium", "__index_level_0__": 25297, "question": "You are given a 2D integer array groups of length n. You are also given an integer array nums.\nYou are asked if you can choose n disjoint subarrays from the array nums such that the ith subarray is equal to groups[i] (0-indexed), and if i > 0, the (i-1)th subarray appears before the ith subarray in nums (i.e. the subarrays must be in the same order as groups).\nReturn true if you can do this task, and false otherwise.\nNote that the subarrays are disjoint if and only if there is no index k such that nums[k] belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.\n Example 1:\nInput: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\nOutput: true\nExplanation: You can choose the 0th subarray as [1,-1,0,1,-1,-1,3,-2,0] and the 1st one as [1,-1,0,1,-1,-1,3,-2,0].\nThese subarrays are disjoint as they share no common nums[k] element.\nExample 2:\nInput: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\nOutput: false\nExplanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n[10,-2] must come before [1,2,3,4].\nExample 3:\nInput: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\nOutput: false\nExplanation: Note that choosing the subarrays [7,7,1,2,3,4,7,7] and [7,7,1,2,3,4,7,7] is invalid because they are not disjoint.\nThey share a common elements nums[4] (0-indexed).\n Constraints:\ngroups.length == n\n1 <= n <= 103\n1 <= groups[i].length, sum(groups[i].length) <= 103\n1 <= nums.length <= 103\n-107 <= groups[i][j], nums[k] <= 107" }, { "post_href": "https://leetcode.com/problems/map-of-highest-peak/discuss/1074561/Python3-bfs", "python_solutions": "class Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n m, n = len(isWater), len(isWater[0]) # dimensions \n queue = [(i, j) for i in range(m) for j in range(n) if isWater[i][j]]\n \n ht = 0\n ans = [[0]*n for _ in range(m)]\n seen = set(queue)\n \n while queue: \n newq = []\n for i, j in queue: \n ans[i][j] = ht\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in seen: \n newq.append((ii, jj))\n seen.add((ii, jj))\n queue = newq\n ht += 1\n return ans", "slug": "map-of-highest-peak", "post_title": "[Python3] bfs", "user": "ye15", "upvotes": 7, "views": 349, "problem_title": "map of highest peak", "number": 1765, "acceptance": 0.604, "difficulty": "Medium", "__index_level_0__": 25304, "question": "You are given an integer matrix isWater of size m x n that represents a map of land and water cells.\nIf isWater[i][j] == 0, cell (i, j) is a land cell.\nIf isWater[i][j] == 1, cell (i, j) is a water cell.\nYou must assign each cell a height in a way that follows these rules:\nThe height of each cell must be non-negative.\nIf the cell is a water cell, its height must be 0.\nAny two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\nFind an assignment of heights such that the maximum height in the matrix is maximized.\nReturn an integer matrix height of size m x n where height[i][j] is cell (i, j)'s height. If there are multiple solutions, return any of them.\n Example 1:\nInput: isWater = [[0,1],[0,0]]\nOutput: [[1,0],[2,1]]\nExplanation: The image shows the assigned heights of each cell.\nThe blue cell is the water cell, and the green cells are the land cells.\nExample 2:\nInput: isWater = [[0,0,1],[1,0,0],[0,0,0]]\nOutput: [[1,1,0],[0,1,1],[1,2,2]]\nExplanation: A height of 2 is the maximum possible height of any assignment.\nAny height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.\n Constraints:\nm == isWater.length\nn == isWater[i].length\n1 <= m, n <= 1000\nisWater[i][j] is 0 or 1.\nThere is at least one water cell." }, { "post_href": "https://leetcode.com/problems/tree-of-coprimes/discuss/1074565/Python3-dfs", "python_solutions": "class Solution:\n def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n tree = {} # tree as adjacency list \n for u, v in edges: \n tree.setdefault(u, []).append(v)\n tree.setdefault(v, []).append(u)\n \n ans = [-1]*len(nums)\n path = {} # val -> list of position & depth \n seen = {0}\n \n def fn(k, i): \n \"\"\"Populate ans via dfs.\"\"\"\n ii = -1 \n for x in path:\n if gcd(nums[k], x) == 1: # coprime \n if path[x] and path[x][-1][1] > ii: \n ans[k] = path[x][-1][0]\n ii = path[x][-1][1]\n \n path.setdefault(nums[k], []).append((k, i))\n for kk in tree.get(k, []): \n if kk not in seen: \n seen.add(kk)\n fn(kk, i+1)\n path[nums[k]].pop()\n \n \n fn(0, 0)\n return ans", "slug": "tree-of-coprimes", "post_title": "[Python3] dfs", "user": "ye15", "upvotes": 10, "views": 702, "problem_title": "tree of coprimes", "number": 1766, "acceptance": 0.392, "difficulty": "Hard", "__index_level_0__": 25312, "question": "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.\nTo represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.\nTwo values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.\nAn ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.\nReturn an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.\n Example 1:\nInput: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\nOutput: [-1,0,0,1]\nExplanation: In the above figure, each node's value is in parentheses.\n- Node 0 has no coprime ancestors.\n- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.\nExample 2:\nInput: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\nOutput: [-1,0,-1,0,0,0,-1]\n Constraints:\nnums.length == n\n1 <= nums[i] <= 50\n1 <= n <= 105\nedges.length == n - 1\nedges[j].length == 2\n0 <= uj, vj < n\nuj != vj" }, { "post_href": "https://leetcode.com/problems/merge-strings-alternately/discuss/1075531/Simple-Python-Solution", "python_solutions": "class Solution:\n def mergeAlternately(self, word1: str, word2: str) -> str:\n \n res=''\n \n for i in range(min(len(word1),len(word2))):\n res += word1[i] + word2[i]\n \n return res + word1[i+1:] + word2[i+1:]", "slug": "merge-strings-alternately", "post_title": "Simple Python Solution", "user": "lokeshsenthilkumar", "upvotes": 36, "views": 2500, "problem_title": "merge strings alternately", "number": 1768, "acceptance": 0.7609999999999999, "difficulty": "Easy", "__index_level_0__": 25315, "question": "You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.\nReturn the merged string.\n Example 1:\nInput: word1 = \"abc\", word2 = \"pqr\"\nOutput: \"apbqcr\"\nExplanation: The merged string will be merged as so:\nword1: a b c\nword2: p q r\nmerged: a p b q c r\nExample 2:\nInput: word1 = \"ab\", word2 = \"pqrs\"\nOutput: \"apbqrs\"\nExplanation: Notice that as word2 is longer, \"rs\" is appended to the end.\nword1: a b \nword2: p q r s\nmerged: a p b q r s\nExample 3:\nInput: word1 = \"abcd\", word2 = \"pq\"\nOutput: \"apbqcd\"\nExplanation: Notice that as word1 is longer, \"cd\" is appended to the end.\nword1: a b c d\nword2: p q \nmerged: a p b q c d\n Constraints:\n1 <= word1.length, word2.length <= 100\nword1 and word2 consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/discuss/1075895/Easy-Python-beats-100-time-and-space", "python_solutions": "class Solution:\n def minOperations(self, boxes: str) -> List[int]:\n ans = [0]*len(boxes)\n leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)\n for i in range(1, n):\n if boxes[i-1] == '1': leftCount += 1\n leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left\n ans[i] = leftCost\n for i in range(n-2, -1, -1):\n if boxes[i+1] == '1': rightCount += 1\n rightCost += rightCount\n ans[i] += rightCost\n return ans", "slug": "minimum-number-of-operations-to-move-all-balls-to-each-box", "post_title": "Easy Python beats 100% time and space", "user": "trungnguyen276", "upvotes": 126, "views": 6000, "problem_title": "minimum number of operations to move all balls to each box", "number": 1769, "acceptance": 0.852, "difficulty": "Medium", "__index_level_0__": 25363, "question": "You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball.\nIn one operation, you can move one ball from a box to an adjacent box. Box i is adjacent to box j if abs(i - j) == 1. Note that after doing so, there may be more than one ball in some boxes.\nReturn an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box.\nEach answer[i] is calculated considering the initial state of the boxes.\n Example 1:\nInput: boxes = \"110\"\nOutput: [1,1,3]\nExplanation: The answer for each box is as follows:\n1) First box: you will have to move one ball from the second box to the first box in one operation.\n2) Second box: you will have to move one ball from the first box to the second box in one operation.\n3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\nExample 2:\nInput: boxes = \"001011\"\nOutput: [11,8,5,4,3,4]\n Constraints:\nn == boxes.length\n1 <= n <= 2000\nboxes[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/discuss/1075495/Python3-bottom-up-dp", "python_solutions": "class Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n n, m = len(nums), len(multipliers)\n dp = [[0]*m for _ in range(m+1)]\n \n for i in reversed(range(m)):\n for j in range(i, m): \n k = i + m - j - 1\n dp[i][j] = max(nums[i] * multipliers[k] + dp[i+1][j], nums[j-m+n] * multipliers[k] + dp[i][j-1])\n \n return dp[0][-1]", "slug": "maximum-score-from-performing-multiplication-operations", "post_title": "[Python3] bottom-up dp", "user": "ye15", "upvotes": 64, "views": 5800, "problem_title": "maximum score from performing multiplication operations", "number": 1770, "acceptance": 0.366, "difficulty": "Hard", "__index_level_0__": 25400, "question": "You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m.\nYou begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will:\nChoose one integer x from either the start or the end of the array nums.\nAdd multipliers[i] * x to your score.\nNote that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on.\nRemove x from nums.\nReturn the maximum score after performing m operations.\n Example 1:\nInput: nums = [1,2,3], multipliers = [3,2,1]\nOutput: 14\nExplanation: An optimal solution is as follows:\n- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.\n- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.\n- Choose from the end, [1], adding 1 * 1 = 1 to the score.\nThe total score is 9 + 4 + 1 = 14.\nExample 2:\nInput: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\nOutput: 102\nExplanation: An optimal solution is as follows:\n- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.\n- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.\n- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.\n- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.\n- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. \nThe total score is 50 + 15 - 9 + 4 + 42 = 102.\n Constraints:\nn == nums.length\nm == multipliers.length\n1 <= m <= 300\nm <= n <= 105 \n-1000 <= nums[i], multipliers[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/maximize-palindrome-length-from-subsequences/discuss/1075709/Python3-top-down-dp", "python_solutions": "class Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n \n @cache\n def fn(lo, hi):\n \"\"\"Return length of longest palindromic subsequence.\"\"\"\n if lo >= hi: return int(lo == hi)\n if word[lo] == word[hi]: return 2 + fn(lo+1, hi-1)\n return max(fn(lo+1, hi), fn(lo, hi-1))\n \n ans = 0\n word = word1 + word2\n for x in ascii_lowercase: \n i = word1.find(x) \n j = word2.rfind(x)\n if i != -1 and j != -1: ans = max(ans, fn(i, j + len(word1)))\n return ans", "slug": "maximize-palindrome-length-from-subsequences", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 13, "views": 425, "problem_title": "maximize palindrome length from subsequences", "number": 1771, "acceptance": 0.352, "difficulty": "Hard", "__index_level_0__": 25423, "question": "You are given two strings, word1 and word2. You want to construct a string in the following manner:\nChoose some non-empty subsequence subsequence1 from word1.\nChoose some non-empty subsequence subsequence2 from word2.\nConcatenate the subsequences: subsequence1 + subsequence2, to make the string.\nReturn the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0.\nA subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.\nA palindrome is a string that reads the same forward as well as backward.\n Example 1:\nInput: word1 = \"cacb\", word2 = \"cbba\"\nOutput: 5\nExplanation: Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.\nExample 2:\nInput: word1 = \"ab\", word2 = \"ab\"\nOutput: 3\nExplanation: Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.\nExample 3:\nInput: word1 = \"aa\", word2 = \"bb\"\nOutput: 0\nExplanation: You cannot construct a palindrome from the described method, so return 0.\n Constraints:\n1 <= word1.length, word2.length <= 1000\nword1 and word2 consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/count-items-matching-a-rule/discuss/1085906/Python-3-or-2-liner-or-Explanation", "python_solutions": "class Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n d = {'type': 0, 'color': 1, 'name': 2}\n return sum(1 for item in items if item[d[ruleKey]] == ruleValue)", "slug": "count-items-matching-a-rule", "post_title": "Python 3 | 2-liner | Explanation", "user": "idontknoooo", "upvotes": 46, "views": 3200, "problem_title": "count items matching a rule", "number": 1773, "acceptance": 0.843, "difficulty": "Easy", "__index_level_0__": 25426, "question": "You are given an array items, where each items[i] = [typei, colori, namei] describes the type, color, and name of the ith item. You are also given a rule represented by two strings, ruleKey and ruleValue.\nThe ith item is said to match the rule if one of the following is true:\nruleKey == \"type\" and ruleValue == typei.\nruleKey == \"color\" and ruleValue == colori.\nruleKey == \"name\" and ruleValue == namei.\nReturn the number of items that match the given rule.\n Example 1:\nInput: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"color\", ruleValue = \"silver\"\nOutput: 1\nExplanation: There is only one item matching the given rule, which is [\"computer\",\"silver\",\"lenovo\"].\nExample 2:\nInput: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"type\", ruleValue = \"phone\"\nOutput: 2\nExplanation: There are only two items matching the given rule, which are [\"phone\",\"blue\",\"pixel\"] and [\"phone\",\"gold\",\"iphone\"]. Note that the item [\"computer\",\"silver\",\"phone\"] does not match.\n Constraints:\n1 <= items.length <= 104\n1 <= typei.length, colori.length, namei.length, ruleValue.length <= 10\nruleKey is equal to either \"type\", \"color\", or \"name\".\nAll strings consist only of lowercase letters." }, { "post_href": "https://leetcode.com/problems/closest-dessert-cost/discuss/1085820/Python3-top-down-dp", "python_solutions": "class Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n toppingCosts *= 2\n \n @cache\n def fn(i, x):\n \"\"\"Return sum of subsequence of toppingCosts[i:] closest to x.\"\"\"\n if x < 0 or i == len(toppingCosts): return 0\n return min(fn(i+1, x), toppingCosts[i] + fn(i+1, x-toppingCosts[i]), key=lambda y: (abs(y-x), y))\n \n ans = inf\n for bc in baseCosts: \n ans = min(ans, bc + fn(0, target - bc), key=lambda x: (abs(x-target), x))\n return ans", "slug": "closest-dessert-cost", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 18, "views": 3000, "problem_title": "closest dessert cost", "number": 1774, "acceptance": 0.4679999999999999, "difficulty": "Medium", "__index_level_0__": 25471, "question": "You would like to make dessert and are preparing to buy the ingredients. You have n ice cream base flavors and m types of toppings to choose from. You must follow these rules when making your dessert:\nThere must be exactly one ice cream base.\nYou can add one or more types of topping or have no toppings at all.\nThere are at most two of each type of topping.\nYou are given three inputs:\nbaseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.\ntoppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.\ntarget, an integer representing your target price for dessert.\nYou want to make a dessert with a total cost as close to target as possible.\nReturn the closest possible cost of the dessert to target. If there are multiple, return the lower one.\n Example 1:\nInput: baseCosts = [1,7], toppingCosts = [3,4], target = 10\nOutput: 10\nExplanation: Consider the following combination (all 0-indexed):\n- Choose base 1: cost 7\n- Take 1 of topping 0: cost 1 x 3 = 3\n- Take 0 of topping 1: cost 0 x 4 = 0\nTotal: 7 + 3 + 0 = 10.\nExample 2:\nInput: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\nOutput: 17\nExplanation: Consider the following combination (all 0-indexed):\n- Choose base 1: cost 3\n- Take 1 of topping 0: cost 1 x 4 = 4\n- Take 2 of topping 1: cost 2 x 5 = 10\n- Take 0 of topping 2: cost 0 x 100 = 0\nTotal: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.\nExample 3:\nInput: baseCosts = [3,10], toppingCosts = [2,5], target = 9\nOutput: 8\nExplanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.\n Constraints:\nn == baseCosts.length\nm == toppingCosts.length\n1 <= n, m <= 10\n1 <= baseCosts[i], toppingCosts[i] <= 104\n1 <= target <= 104" }, { "post_href": "https://leetcode.com/problems/equal-sum-arrays-with-minimum-number-of-operations/discuss/1085806/Python3-two-heaps", "python_solutions": "class Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n if 6*len(nums1) < len(nums2) or 6*len(nums2) < len(nums1): return -1 # impossible \n \n if sum(nums1) < sum(nums2): nums1, nums2 = nums2, nums1\n s1, s2 = sum(nums1), sum(nums2)\n \n nums1 = [-x for x in nums1] # max-heap \n heapify(nums1)\n heapify(nums2)\n \n ans = 0\n while s1 > s2: \n x1, x2 = nums1[0], nums2[0]\n if -1-x1 > 6-x2: # change x1 to 1\n s1 += x1 + 1\n heapreplace(nums1, -1)\n else: \n s2 += 6 - x2\n heapreplace(nums2, 6)\n ans += 1\n return ans", "slug": "equal-sum-arrays-with-minimum-number-of-operations", "post_title": "[Python3] two heaps", "user": "ye15", "upvotes": 18, "views": 848, "problem_title": "equal sum arrays with minimum number of operations", "number": 1775, "acceptance": 0.527, "difficulty": "Medium", "__index_level_0__": 25483, "question": "You are given two arrays of integers nums1 and nums2, possibly of different lengths. The values in the arrays are between 1 and 6, inclusive.\nIn one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.\nReturn the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1 if it is not possible to make the sum of the two arrays equal.\n Example 1:\nInput: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n- Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n- Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n- Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\nExample 2:\nInput: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\nOutput: -1\nExplanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.\nExample 3:\nInput: nums1 = [6,6], nums2 = [1]\nOutput: 3\nExplanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed. \n- Change nums1[0] to 2. nums1 = [2,6], nums2 = [1].\n- Change nums1[1] to 2. nums1 = [2,2], nums2 = [1].\n- Change nums2[0] to 4. nums1 = [2,2], nums2 = [4].\n Constraints:\n1 <= nums1.length, nums2.length <= 105\n1 <= nums1[i], nums2[i] <= 6" }, { "post_href": "https://leetcode.com/problems/car-fleet-ii/discuss/1557743/Python3-Stack-Time%3A-O(n)-and-Space%3A-O(n)", "python_solutions": "class Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n # Stack: go from back and use stack to get ans\n # Time: O(n)\n # Space: O(n)\n \n stack = [] # index\n ans = [-1] * len(cars)\n for i in range(len(cars)-1,-1,-1):\n # remove cars that are faster than current car since it will never collide\n while stack and cars[i][1] <= cars[stack[-1]][1]: \n stack.pop()\n\n while stack: # if car left, we can compute collide time with current car. \n collision_t = (cars[stack[-1]][0] - cars[i][0]) / (cars[i][1] - cars[stack[-1]][1])\n # if current car's collide time is greater than previous car's collide time \n # (previous collided before current), then we have to find previous car's previous car\n # to compute collide time with that car, so we pop from stack and re-process\n # Otherwise, we add that collide time to answer and break\n if ans[stack[-1]] == -1 or collision_t <= ans[stack[-1]]:\n ans[i] = collision_t\n break\n stack.pop()\n stack.append(i)\n return ans", "slug": "car-fleet-ii", "post_title": "[Python3] Stack - Time: O(n) & Space: O(n)", "user": "jae2021", "upvotes": 4, "views": 261, "problem_title": "car fleet ii", "number": 1776, "acceptance": 0.534, "difficulty": "Hard", "__index_level_0__": 25493, "question": "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:\npositioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.\nspeedi is the initial speed of the ith car in meters per second.\nFor simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.\nReturn an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.\n Example 1:\nInput: cars = [[1,2],[2,1],[4,3],[7,2]]\nOutput: [1.00000,-1.00000,3.00000,-1.00000]\nExplanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\nExample 2:\nInput: cars = [[3,4],[5,4],[6,3],[9,1]]\nOutput: [2.00000,1.00000,1.50000,-1.00000]\n Constraints:\n1 <= cars.length <= 105\n1 <= positioni, speedi <= 106\npositioni < positioni+1" }, { "post_href": "https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate/discuss/1229047/Python-Easy-solution", "python_solutions": "class Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n minDist = math.inf\n ans = -1\n for i in range(len(points)):\n if points[i][0]==x or points[i][1]==y:\n manDist = abs(points[i][0]-x)+abs(points[i][1]-y)\n if manDist bool:\n while n:\n n, rem = divmod(n, 3)\n if rem == 2:\n return False\n return True", "slug": "check-if-number-is-a-sum-of-powers-of-three", "post_title": "While loop, 99% speed", "user": "EvgenySH", "upvotes": 3, "views": 245, "problem_title": "check if number is a sum of powers of three", "number": 1780, "acceptance": 0.654, "difficulty": "Medium", "__index_level_0__": 25543, "question": "Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.\nAn integer y is a power of three if there exists an integer x such that y == 3x.\n Example 1:\nInput: n = 12\nOutput: true\nExplanation: 12 = 31 + 32\nExample 2:\nInput: n = 91\nOutput: true\nExplanation: 91 = 30 + 32 + 34\nExample 3:\nInput: n = 21\nOutput: false\n Constraints:\n1 <= n <= 107" }, { "post_href": "https://leetcode.com/problems/sum-of-beauty-of-all-substrings/discuss/1096392/Python3-freq-table", "python_solutions": "class Solution:\n def beautySum(self, s: str) -> int:\n ans = 0 \n for i in range(len(s)):\n freq = [0]*26\n for j in range(i, len(s)):\n freq[ord(s[j])-97] += 1\n ans += max(freq) - min(x for x in freq if x)\n return ans", "slug": "sum-of-beauty-of-all-substrings", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 41, "views": 2800, "problem_title": "sum of beauty of all substrings", "number": 1781, "acceptance": 0.605, "difficulty": "Medium", "__index_level_0__": 25556, "question": "The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.\nFor example, the beauty of \"abaacc\" is 3 - 1 = 2.\nGiven a string s, return the sum of beauty of all of its substrings.\n Example 1:\nInput: s = \"aabcb\"\nOutput: 5\nExplanation: The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.\nExample 2:\nInput: s = \"aabcbaa\"\nOutput: 17\n Constraints:\n1 <= s.length <= 500\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/count-pairs-of-nodes/discuss/1096612/Python3-2-pointer", "python_solutions": "class Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n degree = [0]*n\n freq = defaultdict(int)\n for u, v in edges: \n degree[u-1] += 1\n degree[v-1] += 1\n freq[min(u-1, v-1), max(u-1, v-1)] += 1\n \n vals = sorted(degree)\n \n ans = []\n for query in queries: \n cnt = 0 \n lo, hi = 0, n-1\n while lo < hi: \n if query < vals[lo] + vals[hi]: \n cnt += hi - lo # (lo, hi), (lo+1, hi), ..., (hi-1, hi) all valid\n hi -= 1\n else: lo += 1\n for u, v in freq: \n if degree[u] + degree[v] - freq[u, v] <= query < degree[u] + degree[v]: cnt -= 1\n ans.append(cnt)\n return ans", "slug": "count-pairs-of-nodes", "post_title": "[Python3] 2-pointer", "user": "ye15", "upvotes": 14, "views": 352, "problem_title": "count pairs of nodes", "number": 1782, "acceptance": 0.38, "difficulty": "Hard", "__index_level_0__": 25564, "question": "You are given an undirected graph defined by an integer n, the number of nodes, and a 2D integer array edges, the edges in the graph, where edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi. You are also given an integer array queries.\nLet incident(a, b) be defined as the number of edges that are connected to either node a or b.\nThe answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:\na < b\nincident(a, b) > queries[j]\nReturn an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.\nNote that there can be multiple edges between the same two nodes.\n Example 1:\nInput: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\nOutput: [6,5]\nExplanation: The calculations for incident(a, b) are shown in the table above.\nThe answers for each of the queries are as follows:\n- answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n- answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.\nExample 2:\nInput: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\nOutput: [10,10,9,8,6]\n Constraints:\n2 <= n <= 2 * 104\n1 <= edges.length <= 105\n1 <= ui, vi <= n\nui != vi\n1 <= queries.length <= 20\n0 <= queries[j] < edges.length" }, { "post_href": "https://leetcode.com/problems/check-if-binary-string-has-at-most-one-segment-of-ones/discuss/1097225/Python-3-Check-for-%2201%22-(1-Liner)", "python_solutions": "class Solution:\n def checkOnesSegment(self, s: str) -> bool:\n return \"01\" not in s", "slug": "check-if-binary-string-has-at-most-one-segment-of-ones", "post_title": "[Python 3] - Check for \"01\" (1 Liner)", "user": "mb557x", "upvotes": 32, "views": 977, "problem_title": "check if binary string has at most one segment of ones", "number": 1784, "acceptance": 0.4039999999999999, "difficulty": "Easy", "__index_level_0__": 25565, "question": "Given a binary string s without leading zeros, return true if s contains at most one contiguous segment of ones. Otherwise, return false.\n Example 1:\nInput: s = \"1001\"\nOutput: false\nExplanation: The ones do not form a contiguous segment.\nExample 2:\nInput: s = \"110\"\nOutput: true\n Constraints:\n1 <= s.length <= 100\ns[i] is either '0' or '1'.\ns[0] is '1'." }, { "post_href": "https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/discuss/1121048/Python-3-or-1-liner-or-Explanation", "python_solutions": "class Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n return math.ceil(abs(goal - sum(nums)) / limit)", "slug": "minimum-elements-to-add-to-form-a-given-sum", "post_title": "Python 3 | 1-liner | Explanation", "user": "idontknoooo", "upvotes": 6, "views": 285, "problem_title": "minimum elements to add to form a given sum", "number": 1785, "acceptance": 0.424, "difficulty": "Medium", "__index_level_0__": 25592, "question": "You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.\nReturn the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.\nNote that abs(x) equals x if x >= 0, and -x otherwise.\n Example 1:\nInput: nums = [1,-1,1], limit = 3, goal = -4\nOutput: 2\nExplanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.\nExample 2:\nInput: nums = [1,-10,9,1], limit = 100, goal = 0\nOutput: 1\n Constraints:\n1 <= nums.length <= 105\n1 <= limit <= 106\n-limit <= nums[i] <= limit\n-109 <= goal <= 109" }, { "post_href": "https://leetcode.com/problems/number-of-restricted-paths-from-first-to-last-node/discuss/1097219/Python3-Dijkstra-%2B-dp", "python_solutions": "class Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = {} # graph as adjacency list \n for u, v, w in edges: \n graph.setdefault(u, []).append((v, w))\n graph.setdefault(v, []).append((u, w))\n \n queue = [n]\n dist = {n: 0}\n while queue: \n newq = []\n for u in queue: \n for v, w in graph[u]:\n if v not in dist or dist[u] + w < dist[v]: \n dist[v] = dist[u] + w\n newq.append(v)\n queue = newq\n \n @cache\n def fn(u): \n \"\"\"Return number of restricted paths from u to n.\"\"\"\n if u == n: return 1 # boundary condition \n ans = 0\n for v, _ in graph[u]: \n if dist[u] > dist[v]: ans += fn(v)\n return ans \n \n return fn(1) % 1_000_000_007", "slug": "number-of-restricted-paths-from-first-to-last-node", "post_title": "[Python3] Dijkstra + dp", "user": "ye15", "upvotes": 4, "views": 401, "problem_title": "number of restricted paths from first to last node", "number": 1786, "acceptance": 0.3929999999999999, "difficulty": "Medium", "__index_level_0__": 25603, "question": "There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.\nA path from node start to node end is a sequence of nodes [z0, z1, z2, ..., zk] such that z0 = start and zk = end and there is an edge between zi and zi+1 where 0 <= i <= k-1.\nThe distance of a path is the sum of the weights on the edges of the path. Let distanceToLastNode(x) denote the shortest distance of a path between node n and node x. A restricted path is a path that also satisfies that distanceToLastNode(zi) > distanceToLastNode(zi+1) where 0 <= i <= k-1.\nReturn the number of restricted paths from node 1 to node n. Since that number may be too large, return it modulo 109 + 7.\n Example 1:\nInput: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\nOutput: 3\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n1) 1 --> 2 --> 5\n2) 1 --> 2 --> 3 --> 5\n3) 1 --> 3 --> 5\nExample 2:\nInput: n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]\nOutput: 1\nExplanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.\n Constraints:\n1 <= n <= 2 * 104\nn - 1 <= edges.length <= 4 * 104\nedges[i].length == 3\n1 <= ui, vi <= n\nui != vi\n1 <= weighti <= 105\nThere is at most one edge between any two nodes.\nThere is at least one path between any two nodes." }, { "post_href": "https://leetcode.com/problems/make-the-xor-of-all-segments-equal-to-zero/discuss/1100417/Python3-dp", "python_solutions": "class Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n freq = defaultdict(lambda: defaultdict(int))\n for i, x in enumerate(nums): freq[i%k][x] += 1 # freq by row\n \n n = 1 << 10\n dp = [0] + [-inf]*(n-1)\n for i in range(k): \n mx = max(dp)\n tmp = [0]*n\n for x, c in enumerate(dp): \n for xx, cc in freq[i].items(): \n tmp[x^xx] = max(tmp[x^xx], c + cc, mx)\n dp = tmp \n return len(nums) - dp[0]", "slug": "make-the-xor-of-all-segments-equal-to-zero", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 3, "views": 184, "problem_title": "make the xor of all segments equal to zero", "number": 1787, "acceptance": 0.395, "difficulty": "Hard", "__index_level_0__": 25608, "question": "You are given an array nums and an integer k. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].\nReturn the minimum number of elements to change in the array such that the XOR of all segments of size k is equal to zero.\n Example 1:\nInput: nums = [1,2,0,3,0], k = 1\nOutput: 3\nExplanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\nExample 2:\nInput: nums = [3,4,5,2,1,7,3,4,7], k = 3\nOutput: 3\nExplanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\nExample 3:\nInput: nums = [1,2,4,1,2,5,1,2,6], k = 3\nOutput: 3\nExplanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n Constraints:\n1 <= k <= nums.length <= 2000\n0 <= nums[i] < 210" }, { "post_href": "https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/discuss/1108295/Python3-check-diff", "python_solutions": "class Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n diff = [[x, y] for x, y in zip(s1, s2) if x != y]\n return not diff or len(diff) == 2 and diff[0][::-1] == diff[1]", "slug": "check-if-one-string-swap-can-make-strings-equal", "post_title": "[Python3] check diff", "user": "ye15", "upvotes": 67, "views": 5900, "problem_title": "check if one string swap can make strings equal", "number": 1790, "acceptance": 0.456, "difficulty": "Easy", "__index_level_0__": 25609, "question": "You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.\nReturn true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.\n Example 1:\nInput: s1 = \"bank\", s2 = \"kanb\"\nOutput: true\nExplanation: For example, swap the first character with the last character of s2 to make \"bank\".\nExample 2:\nInput: s1 = \"attack\", s2 = \"defend\"\nOutput: false\nExplanation: It is impossible to make them equal with one string swap.\nExample 3:\nInput: s1 = \"kelb\", s2 = \"kelb\"\nOutput: true\nExplanation: The two strings are already equal, so no string swap operation is required.\n Constraints:\n1 <= s1.length, s2.length <= 100\ns1.length == s2.length\ns1 and s2 consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/find-center-of-star-graph/discuss/1568945/Beginner-Friendly-solution-in-O(1)-time-with-detailed-explanation", "python_solutions": "class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n \n \"\"\" From the Constraints: A valid STAR GRAPH is confirmed. \n\t\tThat means the center will be common to every edges. \n\t\tTherefore we can get the center by comparing only first 2 elements\"\"\"\n \n for i in range (1):\n \n # Check if first element of first edge mathches with any element of second edges\n \n if edges[i][0] == edges [i+1][0] or edges[i][0] == edges[i+1][1]:\n return edges[i][0]\n \n #Otherwise second element of first edge will be the answer\n else:\n return edges[i][1]", "slug": "find-center-of-star-graph", "post_title": "Beginner Friendly solution in O(1) time with detailed explanation", "user": "stormbreaker_x", "upvotes": 4, "views": 331, "problem_title": "find center of star graph", "number": 1791, "acceptance": 0.835, "difficulty": "Easy", "__index_level_0__": 25648, "question": "There is an undirected star graph consisting of n nodes labeled from 1 to n. A star graph is a graph where there is one center node and exactly n - 1 edges that connect the center node with every other node.\nYou are given a 2D integer array edges where each edges[i] = [ui, vi] indicates that there is an edge between the nodes ui and vi. Return the center of the given star graph.\n Example 1:\nInput: edges = [[1,2],[2,3],[4,2]]\nOutput: 2\nExplanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.\nExample 2:\nInput: edges = [[1,2],[5,1],[1,3],[1,4]]\nOutput: 1\n Constraints:\n3 <= n <= 105\nedges.length == n - 1\nedges[i].length == 2\n1 <= ui, vi <= n\nui != vi\nThe given edges represent a valid star graph." }, { "post_href": "https://leetcode.com/problems/maximum-average-pass-ratio/discuss/1108491/Python-100-Efficient-solution-easy-to-understand-with-comments-and-explanation", "python_solutions": "class Solution:\n\tdef maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:\n\t\t\n\t\tn = len(classes)\n\t\t\n\t\timpacts = [0]*n\n\t\tminRatioIndex = 0\n\t\t\n\t\t# calculate and store impacts for each class in form of tuples -> (-impactValue, passCount, totalCount)\n\t\tfor i in range(n):\n\t\t\tpassCount = classes[i][0]\n\t\t\ttotalCount = classes[i][1]\n\t\t\t\n\t\t\t# calculate the impact for class i\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\timpacts[i] = (-impact, passCount, totalCount) # note the - sign for impact\n\t\t\t\n\t\theapq.heapify(impacts)\n\t\t\n\t\twhile(extraStudents > 0):\n\t\t\t# pick the next class with greatest impact \n\t\t\t_, passCount, totalCount = heapq.heappop(impacts)\n\t\t\t\n\t\t\t# assign a student to the class\n\t\t\tpassCount+=1\n\t\t\ttotalCount+=1\n\t\t\t\n\t\t\t# calculate the updated impact for current class\n\t\t\tcurrentRatio = passCount/totalCount\n\t\t\texpectedRatioAfterUpdate = (passCount+1)/(totalCount+1)\n\t\t\timpact = expectedRatioAfterUpdate - currentRatio\n\t\t\t\n\t\t\t# insert updated impact back into the heap\n\t\t\theapq.heappush(impacts, (-impact, passCount, totalCount))\n\t\t\textraStudents -= 1\n\t\t\n\t\tresult = 0\n\t\t\t\n\t\t# for all the updated classes calculate the total passRatio \n\t\tfor _, passCount, totalCount in impacts:\n\t\t\tresult += passCount/totalCount\n\t\t\t\n\t\t# return the average pass ratio\n\t\treturn result/n", "slug": "maximum-average-pass-ratio", "post_title": "[Python] 100% Efficient solution, easy to understand with comments and explanation", "user": "CaptainX", "upvotes": 14, "views": 1000, "problem_title": "maximum average pass ratio", "number": 1792, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 25697, "question": "There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array classes, where classes[i] = [passi, totali]. You know beforehand that in the ith class, there are totali total students, but only passi number of students will pass the exam.\nYou are also given an integer extraStudents. There are another extraStudents brilliant students that are guaranteed to pass the exam of any class they are assigned to. You want to assign each of the extraStudents students to a class in a way that maximizes the average pass ratio across all the classes.\nThe pass ratio of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes.\nReturn the maximum possible average pass ratio after assigning the extraStudents students. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\nInput: classes = [[1,2],[3,5],[2,2]], extraStudents = 2\nOutput: 0.78333\nExplanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.\nExample 2:\nInput: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4\nOutput: 0.53485\n Constraints:\n1 <= classes.length <= 105\nclasses[i].length == 2\n1 <= passi <= totali <= 105\n1 <= extraStudents <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-score-of-a-good-subarray/discuss/1108326/Python3-greedy-(2-pointer)", "python_solutions": "class Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n ans = mn = nums[k]\n lo = hi = k\n while 0 <= lo-1 or hi+1 < len(nums): \n if lo == 0 or hi+1 < len(nums) and nums[lo-1] < nums[hi+1]: \n hi += 1\n mn = min(mn, nums[hi])\n else: \n lo -= 1\n mn = min(mn, nums[lo])\n ans = max(ans, mn * (hi-lo+1))\n return ans", "slug": "maximum-score-of-a-good-subarray", "post_title": "[Python3 ] greedy (2-pointer)", "user": "ye15", "upvotes": 9, "views": 300, "problem_title": "maximum score of a good subarray", "number": 1793, "acceptance": 0.535, "difficulty": "Hard", "__index_level_0__": 25705, "question": "You are given an array of integers nums (0-indexed) and an integer k.\nThe score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.\nReturn the maximum possible score of a good subarray.\n Example 1:\nInput: nums = [1,4,3,7,4,5], k = 3\nOutput: 15\nExplanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \nExample 2:\nInput: nums = [5,5,4,5,4,1,1,1], k = 0\nOutput: 20\nExplanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 2 * 104\n0 <= k < nums.length" }, { "post_href": "https://leetcode.com/problems/second-largest-digit-in-a-string/discuss/1739076/Python3-or-Faster-Solution-or-Easiest-or-brute-force", "python_solutions": "class Solution:\n def secondHighest(self, s: str) -> int:\n s=set(s)\n a=[]\n for i in s:\n if i.isnumeric() :\n a.append(int(i))\n a.sort()\n if len(a)<2:\n return -1\n return a[len(a)-2]", "slug": "second-largest-digit-in-a-string", "post_title": "\u2714 Python3 | Faster Solution | Easiest | brute force", "user": "Anilchouhan181", "upvotes": 5, "views": 184, "problem_title": "second largest digit in a string", "number": 1796, "acceptance": 0.491, "difficulty": "Easy", "__index_level_0__": 25711, "question": "Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.\nAn alphanumeric string is a string consisting of lowercase English letters and digits.\n Example 1:\nInput: s = \"dfa12321afd\"\nOutput: 2\nExplanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.\nExample 2:\nInput: s = \"abc1111\"\nOutput: -1\nExplanation: The digits that appear in s are [1]. There is no second largest digit. \n Constraints:\n1 <= s.length <= 500\ns consists of only lowercase English letters and/or digits." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/discuss/1153726/Python3-Simple-Solution", "python_solutions": "class Solution:\n def getMaximumConsecutive(self, coins: List[int]) -> int:\n coins.sort()\n \n res = 1\n \n for coin in coins:\n if (res >= coin):\n res += coin\n \n return res", "slug": "maximum-number-of-consecutive-values-you-can-make", "post_title": "Python3 Simple Solution", "user": "victor72", "upvotes": 1, "views": 154, "problem_title": "maximum number of consecutive values you can make", "number": 1798, "acceptance": 0.545, "difficulty": "Medium", "__index_level_0__": 25744, "question": "You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.\nReturn the maximum number of consecutive integer values that you can make with your coins starting from and including 0.\nNote that you may have multiple coins of the same value.\n Example 1:\nInput: coins = [1,3]\nOutput: 2\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\nYou can make 2 consecutive integer values starting from 0.\nExample 2:\nInput: coins = [1,1,1,4]\nOutput: 8\nExplanation: You can make the following values:\n- 0: take []\n- 1: take [1]\n- 2: take [1,1]\n- 3: take [1,1,1]\n- 4: take [4]\n- 5: take [4,1]\n- 6: take [4,1,1]\n- 7: take [4,1,1,1]\nYou can make 8 consecutive integer values starting from 0.\nExample 3:\nInput: nums = [1,4,10,3,1]\nOutput: 20\n Constraints:\ncoins.length == n\n1 <= n <= 4 * 104\n1 <= coins[i] <= 4 * 104" }, { "post_href": "https://leetcode.com/problems/maximize-score-after-n-operations/discuss/1118782/Python3-dp", "python_solutions": "class Solution:\n def maxScore(self, nums: List[int]) -> int:\n \n @cache\n def fn(nums, k): \n \"\"\"Return max score from nums at kth step.\"\"\"\n if not nums: return 0 # boundary condition \n ans = 0 \n for i in range(len(nums)):\n for j in range(i+1, len(nums)): \n rest = nums[:i] + nums[i+1:j] + nums[j+1:]\n ans = max(ans, k*gcd(nums[i], nums[j]) + fn(tuple(rest), k+1))\n return ans\n \n return fn(tuple(nums), 1)", "slug": "maximize-score-after-n-operations", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 17, "views": 1500, "problem_title": "maximize score after n operations", "number": 1799, "acceptance": 0.4579999999999999, "difficulty": "Hard", "__index_level_0__": 25747, "question": "You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.\nIn the ith operation (1-indexed), you will:\nChoose two elements, x and y.\nReceive a score of i * gcd(x, y).\nRemove x and y from nums.\nReturn the maximum score you can receive after performing n operations.\nThe function gcd(x, y) is the greatest common divisor of x and y.\n Example 1:\nInput: nums = [1,2]\nOutput: 1\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 2)) = 1\nExample 2:\nInput: nums = [3,4,6,8]\nOutput: 11\nExplanation: The optimal choice of operations is:\n(1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\nExample 3:\nInput: nums = [1,2,3,4,5,6]\nOutput: 14\nExplanation: The optimal choice of operations is:\n(1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n Constraints:\n1 <= n <= 7\nnums.length == 2 * n\n1 <= nums[i] <= 106" }, { "post_href": "https://leetcode.com/problems/maximum-ascending-subarray-sum/discuss/1119686/Python3-line-sweep", "python_solutions": "class Solution:\n def maxAscendingSum(self, nums: List[int]) -> int:\n ans = 0\n for i, x in enumerate(nums): \n if not i or nums[i-1] >= nums[i]: val = 0 # reset val \n val += nums[i]\n ans = max(ans, val)\n return ans", "slug": "maximum-ascending-subarray-sum", "post_title": "[Python3] line sweep", "user": "ye15", "upvotes": 6, "views": 617, "problem_title": "maximum ascending subarray sum", "number": 1800, "acceptance": 0.637, "difficulty": "Easy", "__index_level_0__": 25751, "question": "Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.\nA subarray is defined as a contiguous sequence of numbers in an array.\nA subarray [numsl, numsl+1, ..., numsr-1, numsr] is ascending if for all i where l <= i < r, numsi < numsi+1. Note that a subarray of size 1 is ascending.\n Example 1:\nInput: nums = [10,20,30,5,10,50]\nOutput: 65\nExplanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\nExample 2:\nInput: nums = [10,20,30,40,50]\nOutput: 150\nExplanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\nExample 3:\nInput: nums = [12,17,15,13,10,11,12]\nOutput: 33\nExplanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n Constraints:\n1 <= nums.length <= 100\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/number-of-orders-in-the-backlog/discuss/1119692/Python3-priority-queue", "python_solutions": "class Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n ans = 0\n buy, sell = [], [] # max-heap & min-heap \n \n for p, q, t in orders: \n ans += q\n if t: # sell order\n while q and buy and -buy[0][0] >= p: # match \n pb, qb = heappop(buy)\n ans -= 2*min(q, qb)\n if q < qb: \n heappush(buy, (pb, qb-q))\n q = 0 \n else: q -= qb \n if q: heappush(sell, (p, q))\n else: # buy order \n while q and sell and sell[0][0] <= p: # match \n ps, qs = heappop(sell)\n ans -= 2*min(q, qs)\n if q < qs: \n heappush(sell, (ps, qs-q))\n q = 0 \n else: q -= qs \n if q: heappush(buy, (-p, q))\n \n return ans % 1_000_000_007", "slug": "number-of-orders-in-the-backlog", "post_title": "[Python3] priority queue", "user": "ye15", "upvotes": 6, "views": 596, "problem_title": "number of orders in the backlog", "number": 1801, "acceptance": 0.474, "difficulty": "Medium", "__index_level_0__": 25778, "question": "You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:\n0 if it is a batch of buy orders, or\n1 if it is a batch of sell orders.\nNote that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.\nThere is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:\nIf the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order's price is smaller than or equal to the current buy order's price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.\nVice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order's price is larger than or equal to the current sell order's price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.\nReturn the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.\n Example 1:\nInput: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\nOutput: 6\nExplanation: Here is what happens with the orders:\n- 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog.\n- 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog.\n- 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog.\n- 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog.\nFinally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6.\nExample 2:\nInput: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\nOutput: 999999984\nExplanation: Here is what happens with the orders:\n- 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog.\n- 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog.\n- 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog.\n- 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog.\nFinally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7).\n Constraints:\n1 <= orders.length <= 105\norders[i].length == 3\n1 <= pricei, amounti <= 109\norderTypei is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/maximum-value-at-a-given-index-in-a-bounded-array/discuss/1119650/Growing-A-HillPyramid-with-Visualization-in-Python3", "python_solutions": "class Solution:\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n res_i, crr_sum = 0, n\n l, r, w_hill = index + 1, index - 1, 1 # left/right indices and width of the hill\n while crr_sum <= maxSum:\n l -= 1\n r += 1\n if l == index and r == index:\n crr_sum += w_hill\n else:\n l_, r_ = max(l, 0), min(r, n - 1)\n\t\t\t\t'''\n\t\t\t\twhen the hill has the same width as the ground, \n\t\t\t\tsimply just speed up growing by adding the result \n\t\t\t\tof dividing (maxSum - crr_sum) by w_hill\n\t\t\t\t'''\n if l < l_ and r > r_:\n rm = maxSum - crr_sum\n res_i += int(rm / w_hill) + 1\n break\n else:\n w_hill = r_ - l_ + 1\n crr_sum += w_hill\n res_i += 1\n return res_i", "slug": "maximum-value-at-a-given-index-in-a-bounded-array", "post_title": "Growing A [Hill/Pyramid] with Visualization in [Python3]", "user": "BryanBoCao", "upvotes": 5, "views": 396, "problem_title": "maximum value at a given index in a bounded array", "number": 1802, "acceptance": 0.319, "difficulty": "Medium", "__index_level_0__": 25784, "question": "You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:\nnums.length == n\nnums[i] is a positive integer where 0 <= i < n.\nabs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.\nThe sum of all the elements of nums does not exceed maxSum.\nnums[index] is maximized.\nReturn nums[index] of the constructed array.\nNote that abs(x) equals x if x >= 0, and -x otherwise.\n Example 1:\nInput: n = 4, index = 2, maxSum = 6\nOutput: 2\nExplanation: nums = [1,2,2,1] is one array that satisfies all the conditions.\nThere are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].\nExample 2:\nInput: n = 6, index = 1, maxSum = 10\nOutput: 3\n Constraints:\n1 <= n <= maxSum <= 109\n0 <= index < n" }, { "post_href": "https://leetcode.com/problems/number-of-different-integers-in-a-string/discuss/1491046/Python-3-Short-and-easy-to-understand", "python_solutions": "class Solution:\n def numDifferentIntegers(self, word: str) -> int:\n \n word = re.findall('(\\d+)', word)\n numbers = [int(i) for i in word]\n \n return len(set(numbers))", "slug": "number-of-different-integers-in-a-string", "post_title": "Python 3 Short and easy to understand", "user": "frolovdmn", "upvotes": 5, "views": 313, "problem_title": "number of different integers in a string", "number": 1805, "acceptance": 0.362, "difficulty": "Easy", "__index_level_0__": 25788, "question": "You are given a string word that consists of digits and lowercase English letters.\nYou will replace every non-digit character with a space. For example, \"a123bc34d8ef34\" will become \" 123 34 8 34\". Notice that you are left with some integers that are separated by at least one space: \"123\", \"34\", \"8\", and \"34\".\nReturn the number of different integers after performing the replacement operations on word.\nTwo integers are considered different if their decimal representations without any leading zeros are different.\n Example 1:\nInput: word = \"a123bc34d8ef34\"\nOutput: 3\nExplanation: The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.\nExample 2:\nInput: word = \"leet1234code234\"\nOutput: 2\nExample 3:\nInput: word = \"a1b01c001\"\nOutput: 1\nExplanation: The three integers \"1\", \"01\", and \"001\" all represent the same integer because\nthe leading zeros are ignored when comparing their decimal values.\n Constraints:\n1 <= word.length <= 1000\nword consists of digits and lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-reinitialize-a-permutation/discuss/1130760/Python3-simulation", "python_solutions": "class Solution:\n def reinitializePermutation(self, n: int) -> int:\n ans = 0\n perm = list(range(n))\n while True: \n ans += 1\n perm = [perm[n//2+(i-1)//2] if i&1 else perm[i//2] for i in range(n)]\n if all(perm[i] == i for i in range(n)): return ans", "slug": "minimum-number-of-operations-to-reinitialize-a-permutation", "post_title": "[Python3] simulation", "user": "ye15", "upvotes": 4, "views": 217, "problem_title": "minimum number of operations to reinitialize a permutation", "number": 1806, "acceptance": 0.7140000000000001, "difficulty": "Medium", "__index_level_0__": 25827, "question": "You are given an even integer n. You initially have a permutation perm of size n where perm[i] == i (0-indexed).\nIn one operation, you will create a new array arr, and for each i:\nIf i % 2 == 0, then arr[i] = perm[i / 2].\nIf i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].\nYou will then assign arr to perm.\nReturn the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.\n Example 1:\nInput: n = 2\nOutput: 1\nExplanation: perm = [0,1] initially.\nAfter the 1st operation, perm = [0,1]\nSo it takes only 1 operation.\nExample 2:\nInput: n = 4\nOutput: 2\nExplanation: perm = [0,1,2,3] initially.\nAfter the 1st operation, perm = [0,2,1,3]\nAfter the 2nd operation, perm = [0,1,2,3]\nSo it takes only 2 operations.\nExample 3:\nInput: n = 6\nOutput: 4\n Constraints:\n2 <= n <= 1000\nn is even." }, { "post_href": "https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/discuss/1286887/Python-or-Dictionary-or-Simple-Solution", "python_solutions": "class Solution:\n def evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n knowledge = dict(knowledge)\n answer, start = [], None\n for i, char in enumerate(s):\n if char == '(': \n start = i + 1\n elif char == ')':\n answer.append(knowledge.get(s[start:i], '?'))\n start = None\n elif start is None: \n answer.append(char)\n return ''.join(answer)", "slug": "evaluate-the-bracket-pairs-of-a-string", "post_title": "Python | Dictionary | Simple Solution", "user": "leeteatsleep", "upvotes": 2, "views": 102, "problem_title": "evaluate the bracket pairs of a string", "number": 1807, "acceptance": 0.667, "difficulty": "Medium", "__index_level_0__": 25831, "question": "You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.\nFor example, in the string \"(name)is(age)yearsold\", there are two bracket pairs that contain the keys \"name\" and \"age\".\nYou know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.\nYou are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:\nReplace keyi and the bracket pair with the key's corresponding valuei.\nIf you do not know the value of the key, you will replace keyi and the bracket pair with a question mark \"?\" (without the quotation marks).\nEach key will appear at most once in your knowledge. There will not be any nested brackets in s.\nReturn the resulting string after evaluating all of the bracket pairs.\n Example 1:\nInput: s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\nOutput: \"bobistwoyearsold\"\nExplanation:\nThe key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\nThe key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".\nExample 2:\nInput: s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\nOutput: \"hi?\"\nExplanation: As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".\nExample 3:\nInput: s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\nOutput: \"yesyesyesaaa\"\nExplanation: The same key can appear multiple times.\nThe key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\nNotice that the \"a\"s not in a bracket pair are not evaluated.\n Constraints:\n1 <= s.length <= 105\n0 <= knowledge.length <= 105\nknowledge[i].length == 2\n1 <= keyi.length, valuei.length <= 10\ns consists of lowercase English letters and round brackets '(' and ')'.\nEvery open bracket '(' in s will have a corresponding close bracket ')'.\nThe key in each bracket pair of s will be non-empty.\nThere will not be any nested bracket pairs in s.\nkeyi and valuei consist of lowercase English letters.\nEach keyi in knowledge is unique." }, { "post_href": "https://leetcode.com/problems/maximize-number-of-nice-divisors/discuss/1130780/Python3-math", "python_solutions": "class Solution:\n def maxNiceDivisors(self, primeFactors: int) -> int:\n mod = 1_000_000_007\n if primeFactors % 3 == 0: return pow(3, primeFactors//3, mod)\n if primeFactors % 3 == 1: return 1 if primeFactors == 1 else 4*pow(3, (primeFactors-4)//3, mod) % mod\n return 2*pow(3, primeFactors//3, mod) % mod", "slug": "maximize-number-of-nice-divisors", "post_title": "[Python3] math", "user": "ye15", "upvotes": 2, "views": 74, "problem_title": "maximize number of nice divisors", "number": 1808, "acceptance": 0.313, "difficulty": "Hard", "__index_level_0__": 25846, "question": "You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:\nThe number of prime factors of n (not necessarily distinct) is at most primeFactors.\nThe 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.\nReturn the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7.\nNote that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.\n Example 1:\nInput: primeFactors = 5\nOutput: 6\nExplanation: 200 is a valid value of n.\nIt has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\nThere is not other value of n that has at most 5 prime factors and more nice divisors.\nExample 2:\nInput: primeFactors = 8\nOutput: 18\n Constraints:\n1 <= primeFactors <= 109" }, { "post_href": "https://leetcode.com/problems/determine-color-of-a-chessboard-square/discuss/1140948/PythonPython3-or-Simple-and-Easy-code-or-self-explanatory", "python_solutions": "class Solution:\n def squareIsWhite(self, c: str) -> bool:\n if c[0] in 'aceg':\n return int(c[1])%2==0\n elif c[0] in 'bdfh':\n return int(c[1])%2==1\n return False", "slug": "determine-color-of-a-chessboard-square", "post_title": "[Python/Python3 | Simple and Easy code | self-explanatory", "user": "Sukhdev_143", "upvotes": 12, "views": 513, "problem_title": "determine color of a chessboard square", "number": 1812, "acceptance": 0.774, "difficulty": "Easy", "__index_level_0__": 25847, "question": "You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.\nReturn true if the square is white, and false if the square is black.\nThe coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.\n Example 1:\nInput: coordinates = \"a1\"\nOutput: false\nExplanation: From the chessboard above, the square with coordinates \"a1\" is black, so return false.\nExample 2:\nInput: coordinates = \"h3\"\nOutput: true\nExplanation: From the chessboard above, the square with coordinates \"h3\" is white, so return true.\nExample 3:\nInput: coordinates = \"c7\"\nOutput: false\n Constraints:\ncoordinates.length == 2\n'a' <= coordinates[0] <= 'h'\n'1' <= coordinates[1] <= '8'" }, { "post_href": "https://leetcode.com/problems/sentence-similarity-iii/discuss/1461165/PYTHON3-Easy-Peezy-code-using-Stack-crisp-and-clear", "python_solutions": "class Solution:\n def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:\n if len(sentence2)>len(sentence1):\n return self.areSentencesSimilar(sentence2,sentence1)\n sentence1=sentence1.split(\" \")\n sentence2=sentence2.split(\" \")\n s1=sentence1[:]\n s2=sentence2[:]\n while s1[0]==s2[0]:\n s1.pop(0)\n s2.pop(0)\n if not s2:\n return True\n if not s2:\n return True\n while s1[-1]==s2[-1]:\n s1.pop()\n s2.pop()\n if not s2:\n return True\n if not s2:\n return True\n return False", "slug": "sentence-similarity-iii", "post_title": "PYTHON3 Easy Peezy code using Stack crisp and clear", "user": "mathur17021play", "upvotes": 2, "views": 102, "problem_title": "sentence similarity iii", "number": 1813, "acceptance": 0.331, "difficulty": "Medium", "__index_level_0__": 25887, "question": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, \"Hello World\", \"HELLO\", \"hello world hello world\" are all sentences. Words consist of only uppercase and lowercase English letters.\nTwo sentences sentence1 and sentence2 are similar if it is possible to insert an arbitrary sentence (possibly empty) inside one of these sentences such that the two sentences become equal. For example, sentence1 = \"Hello my name is Jane\" and sentence2 = \"Hello Jane\" can be made equal by inserting \"my name is\" between \"Hello\" and \"Jane\" in sentence2.\nGiven two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.\n Example 1:\nInput: sentence1 = \"My name is Haley\", sentence2 = \"My Haley\"\nOutput: true\nExplanation: sentence2 can be turned to sentence1 by inserting \"name is\" between \"My\" and \"Haley\".\nExample 2:\nInput: sentence1 = \"of\", sentence2 = \"A lot of words\"\nOutput: false\nExplanation: No single sentence can be inserted inside one of the sentences to make it equal to the other.\nExample 3:\nInput: sentence1 = \"Eating right now\", sentence2 = \"Eating\"\nOutput: true\nExplanation: sentence2 can be turned to sentence1 by inserting \"right now\" at the end of the sentence.\n Constraints:\n1 <= sentence1.length, sentence2.length <= 100\nsentence1 and sentence2 consist of lowercase and uppercase English letters and spaces.\nThe words in sentence1 and sentence2 are separated by a single space." }, { "post_href": "https://leetcode.com/problems/count-nice-pairs-in-an-array/discuss/1140577/Accepted-Python-simple-and-easy-to-understand-solution-with-comments", "python_solutions": "class Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n \n # define constants\n n = len(nums)\n MOD = 10**9 + 7\n \n # handle scenario for no pairs\n if n<=1:\n return 0\n \n # utility method to calculate reverse of a number\n # e.g. rev(123) -> 321\n def rev(i):\n new = 0\n while(i!=0):\n r = i%10\n new = new*10+r\n i = i//10\n return new\n \n # calculate frequency of all the diffs\n freq_counter = defaultdict(int)\n for num in nums:\n freq_counter[num-rev(num)] += 1\n \n # for all the frequencies calculate the number of paris\n # which is basically nC2 (read as - \"n choose 2\") -> n*(n-1)/2\n answer = 0\n for freq in freq_counter.keys():\n count = freq_counter[freq]\n # note the modulo operation being performed to handle large answer\n answer = (answer + (count*(count-1))//2)%MOD\n \n return answer", "slug": "count-nice-pairs-in-an-array", "post_title": "[Accepted] Python simple and easy to understand solution with comments", "user": "CaptainX", "upvotes": 5, "views": 502, "problem_title": "count nice pairs in an array", "number": 1814, "acceptance": 0.42, "difficulty": "Medium", "__index_level_0__": 25894, "question": "You are given an array nums that consists of non-negative integers. Let us define rev(x) as the reverse of the non-negative integer x. For example, rev(123) = 321, and rev(120) = 21. A pair of indices (i, j) is nice if it satisfies all of the following conditions:\n0 <= i < j < nums.length\nnums[i] + rev(nums[j]) == nums[j] + rev(nums[i])\nReturn the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.\n Example 1:\nInput: nums = [42,11,1,97]\nOutput: 2\nExplanation: The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.\nExample 2:\nInput: nums = [13,10,35,24,76]\nOutput: 4\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-groups-getting-fresh-donuts/discuss/1140716/Python3-Fastest-solution-with-explanation", "python_solutions": "class Solution:\n def maxHappyGroups(self, bs: int, gs: List[int]) -> int:\n c = {i: 0 for i in range(bs)}\n for g in gs:\n c[g % bs] += 1\n ret = c[0]\n c[0] = 0\n \n \n def get_keys(num):\n keys = []\n def rec(stack):\n if len(stack) == num:\n if sum(stack) % bs == 0:\n keys.append(Counter(stack))\n else:\n for i in range(stack[-1] if stack else bs - 1, - 1, - 1):\n stack.append(i)\n rec(stack)\n stack.pop()\n rec([])\n return keys\n \n def get_diff_keys(num):\n keys = []\n def rec(stack):\n if len(stack) == num:\n if sum(stack) % bs == 0:\n keys.append(Counter(stack))\n else:\n for i in range(stack[-1] - 1 if stack else bs - 1, - 1, - 1):\n stack.append(i)\n rec(stack)\n stack.pop()\n rec([])\n return keys\n \n for tc in range(2, bs):\n for keys in get_diff_keys(tc):\n add = min(c[key] // keys[key] for key in keys)\n if add == 0: continue\n ret += add\n for key in keys:\n c[key] -= add * keys[key]\n tc = 2\n while True:\n for keys in get_keys(tc):\n add = min(c[key] // keys[key] for key in keys)\n if add == 0: continue\n ret += add\n for key in keys:\n c[key] -= add * keys[key]\n if tc > sum(c.values()): break\n tc += 1\n return ret + bool(sum(c.values()))\n \n ```", "slug": "maximum-number-of-groups-getting-fresh-donuts", "post_title": "[Python3] Fastest solution with explanation", "user": "timetoai", "upvotes": 0, "views": 102, "problem_title": "maximum number of groups getting fresh donuts", "number": 1815, "acceptance": 0.402, "difficulty": "Hard", "__index_level_0__": 25900, "question": "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.\nWhen a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.\nYou can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.\n Example 1:\nInput: batchSize = 3, groups = [1,2,3,4,5,6]\nOutput: 4\nExplanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.\nExample 2:\nInput: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\nOutput: 4\n Constraints:\n1 <= batchSize <= 9\n1 <= groups.length <= 30\n1 <= groups[i] <= 109" }, { "post_href": "https://leetcode.com/problems/truncate-sentence/discuss/1142293/2-lines-of-code-with-100-less-space-used", "python_solutions": "class Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n words = s.split(\" \")\n return \" \".join(words[0:k])", "slug": "truncate-sentence", "post_title": "2 lines of code with 100% less space used", "user": "vashisht7", "upvotes": 15, "views": 1000, "problem_title": "truncate sentence", "number": 1816, "acceptance": 0.821, "difficulty": "Easy", "__index_level_0__": 25901, "question": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of only uppercase and lowercase English letters (no punctuation).\nFor example, \"Hello World\", \"HELLO\", and \"hello world hello world\" are all sentences.\nYou are given a sentence s and an integer k. You want to truncate s such that it contains only the first k words. Return s after truncating it.\n Example 1:\nInput: s = \"Hello how are you Contestant\", k = 4\nOutput: \"Hello how are you\"\nExplanation:\nThe words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\nThe first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\nHence, you should return \"Hello how are you\".\nExample 2:\nInput: s = \"What is the solution to this problem\", k = 4\nOutput: \"What is the solution\"\nExplanation:\nThe words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\nThe first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\nHence, you should return \"What is the solution\".\nExample 3:\nInput: s = \"chopper is not a tanuki\", k = 5\nOutput: \"chopper is not a tanuki\"\n Constraints:\n1 <= s.length <= 500\nk is in the range [1, the number of words in s].\ns consist of only lowercase and uppercase English letters and spaces.\nThe words in s are separated by a single space.\nThere are no leading or trailing spaces." }, { "post_href": "https://leetcode.com/problems/finding-the-users-active-minutes/discuss/1141356/Python3-hash-map", "python_solutions": "class Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n mp = {}\n for i, t in logs: \n mp.setdefault(i, set()).add(t)\n \n ans = [0]*k\n for v in mp.values(): \n if len(v) <= k: \n ans[len(v)-1] += 1\n return ans", "slug": "finding-the-users-active-minutes", "post_title": "[Python3] hash map", "user": "ye15", "upvotes": 9, "views": 597, "problem_title": "finding the users active minutes", "number": 1817, "acceptance": 0.807, "difficulty": "Medium", "__index_level_0__": 25949, "question": "You are given the logs for users' actions on LeetCode, and an integer k. The logs are represented by a 2D integer array logs where each logs[i] = [IDi, timei] indicates that the user with IDi performed an action at the minute timei.\nMultiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.\nThe user active minutes (UAM) for a given user is defined as the number of unique minutes in which the user performed an action on LeetCode. A minute can only be counted once, even if multiple actions occur during it.\nYou are to calculate a 1-indexed array answer of size k such that, for each j (1 <= j <= k), answer[j] is the number of users whose UAM equals j.\nReturn the array answer as described above.\n Example 1:\nInput: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\nOutput: [0,2,0,0,0]\nExplanation:\nThe user with ID=0 performed actions at minutes 5, 2, and 5 again. Hence, they have a UAM of 2 (minute 5 is only counted once).\nThe user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nSince both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\nExample 2:\nInput: logs = [[1,1],[2,2],[2,3]], k = 4\nOutput: [1,1,0,0]\nExplanation:\nThe user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\nThe user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\nThere is one user with a UAM of 1 and one with a UAM of 2.\nHence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n Constraints:\n1 <= logs.length <= 104\n0 <= IDi <= 109\n1 <= timei <= 105\nk is in the range [The maximum UAM for a user, 105]." }, { "post_href": "https://leetcode.com/problems/minimum-absolute-sum-difference/discuss/1715575/Python-%2B-Fully-Explained-%2B-Best-Solution", "python_solutions": "class Solution:\n\tdef minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n\t\tn = len(nums1)\n\t\tdiff = []\n\t\tsum = 0\n\t\tfor i in range(n):\n\t\t\ttemp = abs(nums1[i]-nums2[i])\n\t\t\tdiff.append(temp)\n\t\t\tsum += temp\n\t\tnums1.sort()\n\t\tbest_diff = []\n\t\tfor i in range(n):\n\t\t\tidx = bisect.bisect_left(nums1, nums2[i])\n\t\t\tif idx != 0 and idx != n:\n\t\t\t\tbest_diff.append(\n\t\t\t\t\tmin(abs(nums2[i]-nums1[idx]), abs(nums2[i]-nums1[idx-1])))\n\t\t\telif idx == 0:\n\t\t\t\tbest_diff.append(abs(nums2[i]-nums1[idx]))\n\t\t\telse:\n\t\t\t\tbest_diff.append(abs(nums2[i]-nums1[idx-1]))\n\t\tsaved = 0\n\t\tfor i in range(n):\n\t\t\tsaved = max(saved, diff[i]-best_diff[i])\n\t\treturn (sum-saved) % ((10**9)+(7))", "slug": "minimum-absolute-sum-difference", "post_title": "[Python] + Fully Explained + Best Solution \u2714", "user": "leet_satyam", "upvotes": 10, "views": 540, "problem_title": "minimum absolute sum difference", "number": 1818, "acceptance": 0.302, "difficulty": "Medium", "__index_level_0__": 25970, "question": "You are given two positive integer arrays nums1 and nums2, both of length n.\nThe absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).\nYou can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.\nReturn the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.\n|x| is defined as:\nx if x >= 0, or\n-x if x < 0.\n Example 1:\nInput: nums1 = [1,7,5], nums2 = [2,3,5]\nOutput: 3\nExplanation: There are two possible optimal solutions:\n- Replace the second element with the first: [1,7,5] => [1,1,5], or\n- Replace the second element with the third: [1,7,5] => [1,5,5].\nBoth will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.\nExample 2:\nInput: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\nOutput: 0\nExplanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \nabsolute sum difference of 0.\nExample 3:\nInput: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\nOutput: 20\nExplanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\nThis yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n Constraints:\nn == nums1.length\nn == nums2.length\n1 <= n <= 105\n1 <= nums1[i], nums2[i] <= 105" }, { "post_href": "https://leetcode.com/problems/number-of-different-subsequences-gcds/discuss/1144445/Python3-enumerate-all-possibilities", "python_solutions": "class Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n nums = set(nums)\n \n ans = 0\n m = max(nums)\n for x in range(1, m+1): \n g = 0\n for xx in range(x, m+1, x): \n if xx in nums: \n g = gcd(g, xx)\n if g == x: ans += 1\n return ans", "slug": "number-of-different-subsequences-gcds", "post_title": "[Python3] enumerate all possibilities", "user": "ye15", "upvotes": 4, "views": 234, "problem_title": "number of different subsequences gcds", "number": 1819, "acceptance": 0.385, "difficulty": "Hard", "__index_level_0__": 25978, "question": "You are given an array nums that consists of positive integers.\nThe GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.\nFor example, the GCD of the sequence [4,6,16] is 2.\nA subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\nFor example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\nReturn the number of different GCDs among all non-empty subsequences of nums.\n Example 1:\nInput: nums = [6,10,3]\nOutput: 5\nExplanation: The figure shows all the non-empty subsequences and their GCDs.\nThe different GCDs are 6, 10, 3, 2, and 1.\nExample 2:\nInput: nums = [5,15,40,5,6]\nOutput: 7\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 2 * 105" }, { "post_href": "https://leetcode.com/problems/sign-of-the-product-of-an-array/discuss/1152412/Python3-line-sweep", "python_solutions": "class Solution:\n def arraySign(self, nums: List[int]) -> int:\n ans = 1\n for x in nums: \n if x == 0: return 0 \n if x < 0: ans *= -1\n return ans", "slug": "sign-of-the-product-of-an-array", "post_title": "[Python3] line sweep", "user": "ye15", "upvotes": 58, "views": 6300, "problem_title": "sign of the product of an array", "number": 1822, "acceptance": 0.66, "difficulty": "Easy", "__index_level_0__": 25979, "question": "There is a function signFunc(x) that returns:\n1 if x is positive.\n-1 if x is negative.\n0 if x is equal to 0.\nYou are given an integer array nums. Let product be the product of all values in the array nums.\nReturn signFunc(product).\n Example 1:\nInput: nums = [-1,-2,-3,-4,3,2,1]\nOutput: 1\nExplanation: The product of all values in the array is 144, and signFunc(144) = 1\nExample 2:\nInput: nums = [1,5,0,2,-3]\nOutput: 0\nExplanation: The product of all values in the array is 0, and signFunc(0) = 0\nExample 3:\nInput: nums = [-1,1,-1,1,-1]\nOutput: -1\nExplanation: The product of all values in the array is -1, and signFunc(-1) = -1\n Constraints:\n1 <= nums.length <= 1000\n-100 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/find-the-winner-of-the-circular-game/discuss/1152420/Python3-simulation", "python_solutions": "class Solution:\n def findTheWinner(self, n: int, k: int) -> int:\n nums = list(range(n))\n i = 0 \n while len(nums) > 1: \n i = (i + k-1) % len(nums)\n nums.pop(i)\n return nums[0] + 1", "slug": "find-the-winner-of-the-circular-game", "post_title": "[Python3] simulation", "user": "ye15", "upvotes": 16, "views": 1900, "problem_title": "find the winner of the circular game", "number": 1823, "acceptance": 0.779, "difficulty": "Medium", "__index_level_0__": 26018, "question": "There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.\nThe rules of the game are as follows:\nStart at the 1st friend.\nCount the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.\nThe last friend you counted leaves the circle and loses the game.\nIf there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat.\nElse, the last friend in the circle wins the game.\nGiven the number of friends, n, and an integer k, return the winner of the game.\n Example 1:\nInput: n = 5, k = 2\nOutput: 3\nExplanation: Here are the steps of the game:\n1) Start at friend 1.\n2) Count 2 friends clockwise, which are friends 1 and 2.\n3) Friend 2 leaves the circle. Next start is friend 3.\n4) Count 2 friends clockwise, which are friends 3 and 4.\n5) Friend 4 leaves the circle. Next start is friend 5.\n6) Count 2 friends clockwise, which are friends 5 and 1.\n7) Friend 1 leaves the circle. Next start is friend 3.\n8) Count 2 friends clockwise, which are friends 3 and 5.\n9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\nExample 2:\nInput: n = 6, k = 5\nOutput: 1\nExplanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n Constraints:\n1 <= k <= n <= 500\n Follow up:\nCould you solve this problem in linear time with constant space?" }, { "post_href": "https://leetcode.com/problems/minimum-sideway-jumps/discuss/1480131/Python-3-or-DP-or-Explanation", "python_solutions": "class Solution:\n def minSideJumps(self, obstacles: List[int]) -> int:\n n = len(obstacles)\n dp = [[sys.maxsize] * n for _ in range(3)]\n dp[0][0]= 1\n dp[1][0]= 0\n dp[2][0]= 1\n for i in range(1, n):\n dp[0][i] = dp[0][i-1] if obstacles[i] != 1 else sys.maxsize\n dp[1][i] = dp[1][i-1] if obstacles[i] != 2 else sys.maxsize\n dp[2][i] = dp[2][i-1] if obstacles[i] != 3 else sys.maxsize\n if obstacles[i] != 1:\n for j in [1, 2]:\n dp[0][i] = min(dp[0][i], dp[j][i] + 1 if obstacles[i] != j+1 else sys.maxsize)\n if obstacles[i] != 2:\n for j in [0, 2]:\n dp[1][i] = min(dp[1][i], dp[j][i] + 1 if obstacles[i] != j+1 else sys.maxsize)\n if obstacles[i] != 3:\n for j in [0, 1]:\n dp[2][i] = min(dp[2][i], dp[j][i] + 1 if obstacles[i] != j+1 else sys.maxsize)\n return min(dp[0][-1], dp[1][-1], dp[2][-1])", "slug": "minimum-sideway-jumps", "post_title": "Python 3 | DP | Explanation", "user": "idontknoooo", "upvotes": 4, "views": 539, "problem_title": "minimum sideway jumps", "number": 1824, "acceptance": 0.495, "difficulty": "Medium", "__index_level_0__": 26045, "question": "There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.\nYou are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.\nFor example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.\nThe frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.\nFor example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.\nReturn the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.\nNote: There will be no obstacles on points 0 and n.\n Example 1:\nInput: obstacles = [0,1,2,3,0]\nOutput: 2 \nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\nNote that the frog can jump over obstacles only when making side jumps (as shown at point 2).\nExample 2:\nInput: obstacles = [0,1,1,3,3,0]\nOutput: 0\nExplanation: There are no obstacles on lane 2. No side jumps are required.\nExample 3:\nInput: obstacles = [0,2,1,0,3,0]\nOutput: 2\nExplanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n Constraints:\nobstacles.length == n + 1\n1 <= n <= 5 * 105\n0 <= obstacles[i] <= 3\nobstacles[0] == obstacles[n] == 0" }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing/discuss/1178397/Python3-simple-solution-beats-90-users", "python_solutions": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n count = 0\n for i in range(1,len(nums)):\n if nums[i] <= nums[i-1]:\n x = nums[i]\n nums[i] += (nums[i-1] - nums[i]) + 1\n count += nums[i] - x\n return count", "slug": "minimum-operations-to-make-the-array-increasing", "post_title": "Python3 simple solution beats 90% users", "user": "EklavyaJoshi", "upvotes": 8, "views": 764, "problem_title": "minimum operations to make the array increasing", "number": 1827, "acceptance": 0.782, "difficulty": "Easy", "__index_level_0__": 26056, "question": "You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1.\nFor example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].\nReturn the minimum number of operations needed to make nums strictly increasing.\nAn array nums is strictly increasing if nums[i] < nums[i+1] for all 0 <= i < nums.length - 1. An array of length 1 is trivially strictly increasing.\n Example 1:\nInput: nums = [1,1,1]\nOutput: 3\nExplanation: You can do the following operations:\n1) Increment nums[2], so nums becomes [1,1,2].\n2) Increment nums[1], so nums becomes [1,2,2].\n3) Increment nums[2], so nums becomes [1,2,3].\nExample 2:\nInput: nums = [1,5,2,4,1]\nOutput: 14\nExample 3:\nInput: nums = [8]\nOutput: 0\n Constraints:\n1 <= nums.length <= 5000\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle/discuss/1163133/Python-One-liner", "python_solutions": "class Solution:\n def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:\n return [sum(math.sqrt((x0-x1)**2 + (y0-y1)**2) <= r for x1, y1 in points) for x0, y0, r in queries]", "slug": "queries-on-number-of-points-inside-a-circle", "post_title": "Python One-liner", "user": "Black_Pegasus", "upvotes": 21, "views": 4000, "problem_title": "queries on number of points inside a circle", "number": 1828, "acceptance": 0.8640000000000001, "difficulty": "Medium", "__index_level_0__": 26091, "question": "You are given an array points where points[i] = [xi, yi] is the coordinates of the ith point on a 2D plane. Multiple points can have the same coordinates.\nYou are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.\nFor each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.\nReturn an array answer, where answer[j] is the answer to the jth query.\n Example 1:\nInput: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\nOutput: [3,2,2]\nExplanation: The points and circles are shown above.\nqueries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.\nExample 2:\nInput: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\nOutput: [2,3,2,4]\nExplanation: The points and circles are shown above.\nqueries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.\n Constraints:\n1 <= points.length <= 500\npoints[i].length == 2\n0 <= xi, yi <= 500\n1 <= queries.length <= 500\nqueries[j].length == 3\n0 <= xj, yj <= 500\n1 <= rj <= 500\nAll coordinates are integers.\n Follow up: Could you find the answer for each query in better complexity than O(n)?" }, { "post_href": "https://leetcode.com/problems/maximum-xor-for-each-query/discuss/1281679/Python3-solution-using-single-for-loop", "python_solutions": "class Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n res = []\n for i in range(1,len(nums)):\n res.append(2**maximumBit - 1 - nums[i-1])\n nums[i] = nums[i-1]^nums[i]\n res.append(2**maximumBit - 1 - nums[-1])\n return res[::-1]", "slug": "maximum-xor-for-each-query", "post_title": "Python3 solution using single for loop", "user": "EklavyaJoshi", "upvotes": 3, "views": 111, "problem_title": "maximum xor for each query", "number": 1829, "acceptance": 0.769, "difficulty": "Medium", "__index_level_0__": 26116, "question": "You are given a sorted array nums of n non-negative integers and an integer maximumBit. You want to perform the following query n times:\nFind a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query.\nRemove the last element from the current array nums.\nReturn an array answer, where answer[i] is the answer to the ith query.\n Example 1:\nInput: nums = [0,1,1,3], maximumBit = 2\nOutput: [0,3,2,3]\nExplanation: The queries are answered as follows:\n1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n4th query: nums = [0], k = 3 since 0 XOR 3 = 3.\nExample 2:\nInput: nums = [2,3,4,7], maximumBit = 3\nOutput: [5,2,6,5]\nExplanation: The queries are answered as follows:\n1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n4th query: nums = [2], k = 5 since 2 XOR 5 = 7.\nExample 3:\nInput: nums = [0,1,2,2,5,7], maximumBit = 3\nOutput: [4,3,6,4,6,7]\n Constraints:\nnums.length == n\n1 <= n <= 105\n1 <= maximumBit <= 20\n0 <= nums[i] < 2maximumBit\nnums is sorted in ascending order." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/discuss/1202007/Python3-math-solution", "python_solutions": "class Solution:\n def makeStringSorted(self, s: str) -> int:\n freq = [0]*26\n for c in s: freq[ord(c) - 97] += 1\n \n MOD = 1_000_000_007\n fac = cache(lambda x: x*fac(x-1)%MOD if x else 1)\n ifac = cache(lambda x: pow(fac(x), MOD-2, MOD)) # Fermat's little theorem (a**(p-1) = 1 (mod p))\n \n ans, n = 0, len(s)\n for c in s: \n val = ord(c) - 97\n mult = fac(n-1)\n for k in range(26): mult *= ifac(freq[k])\n for k in range(val): ans += freq[k] * mult\n n -= 1\n freq[val] -= 1\n return ans % MOD", "slug": "minimum-number-of-operations-to-make-string-sorted", "post_title": "[Python3] math solution", "user": "ye15", "upvotes": 1, "views": 240, "problem_title": "minimum number of operations to make string sorted", "number": 1830, "acceptance": 0.491, "difficulty": "Hard", "__index_level_0__": 26131, "question": "You are given a string s (0-indexed). You are asked to perform the following operation on s until you get a sorted string:\nFind the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].\nFind the largest index j such that i <= j < s.length and s[k] < s[i - 1] for all the possible values of k in the range [i, j] inclusive.\nSwap the two characters at indices i - 1 and j.\nReverse the suffix starting at index i.\nReturn the number of operations needed to make the string sorted. Since the answer can be too large, return it modulo 109 + 7.\n Example 1:\nInput: s = \"cba\"\nOutput: 5\nExplanation: The simulation goes as follows:\nOperation 1: i=2, j=2. Swap s[1] and s[2] to get s=\"cab\", then reverse the suffix starting at 2. Now, s=\"cab\".\nOperation 2: i=1, j=2. Swap s[0] and s[2] to get s=\"bac\", then reverse the suffix starting at 1. Now, s=\"bca\".\nOperation 3: i=2, j=2. Swap s[1] and s[2] to get s=\"bac\", then reverse the suffix starting at 2. Now, s=\"bac\".\nOperation 4: i=1, j=1. Swap s[0] and s[1] to get s=\"abc\", then reverse the suffix starting at 1. Now, s=\"acb\".\nOperation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".\nExample 2:\nInput: s = \"aabaa\"\nOutput: 2\nExplanation: The simulation goes as follows:\nOperation 1: i=3, j=4. Swap s[2] and s[4] to get s=\"aaaab\", then reverse the substring starting at 3. Now, s=\"aaaba\".\nOperation 2: i=4, j=4. Swap s[3] and s[4] to get s=\"aaaab\", then reverse the substring starting at 4. Now, s=\"aaaab\".\n Constraints:\n1 <= s.length <= 3000\ns consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/check-if-the-sentence-is-pangram/discuss/2712076/Multiple-solution-in-python", "python_solutions": "class Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n lst=[0]*26\n for i in sentence:\n lst[ord(i)-ord('a')]+=1\n return 0 not in lst", "slug": "check-if-the-sentence-is-pangram", "post_title": "Multiple solution in python", "user": "shubham_1307", "upvotes": 19, "views": 732, "problem_title": "check if the sentence is pangram", "number": 1832, "acceptance": 0.8390000000000001, "difficulty": "Easy", "__index_level_0__": 26132, "question": "A pangram is a sentence where every letter of the English alphabet appears at least once.\nGiven a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.\n Example 1:\nInput: sentence = \"thequickbrownfoxjumpsoverthelazydog\"\nOutput: true\nExplanation: sentence contains at least one of every letter of the English alphabet.\nExample 2:\nInput: sentence = \"leetcode\"\nOutput: false\n Constraints:\n1 <= sentence.length <= 1000\nsentence consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-ice-cream-bars/discuss/1165500/Python3-with-Explanation-100-faster-and-100-memory-efficient", "python_solutions": "class Solution:\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n '''\n 1. If the minimum of all costs is greater than amount of coins, the boy can't buy any bar, return 0\n 2. Else, sort the list of costs in a non-decreasing order\n 3. For each 'cost' in costs, if the cost is less than current coins\n -increase the count of ice cream bars that can be bought by 1\n -decrease the current coins amount by 'cost'\n 4. If the cost is greater than current coins, return the ice cream bar count value\n '''\n \n if min(costs)>coins: #minimum cost is greater than the coins available \n return 0 #can't buy any ice cream bar\n \n costs=sorted(costs) #sort the list of costs in a non-decreasing order\n res = 0 #the resultant count of ice cream bars that can be bought\n for cost in costs:\n if cost<=coins: #in this case, the boy can buy the ice cream bar\n res+=1 #increase the ice cream bar count\n coins-=cost #spent an amount equal to 'cost', decrease current coins amount by cost\n else:\n break #not enough coins, return the bars count\n \n return res", "slug": "maximum-ice-cream-bars", "post_title": "Python3 with Explanation, 100% faster and 100% memory efficient", "user": "bPapan", "upvotes": 3, "views": 279, "problem_title": "maximum ice cream bars", "number": 1833, "acceptance": 0.6559999999999999, "difficulty": "Medium", "__index_level_0__": 26180, "question": "It is a sweltering summer day, and a boy wants to buy some ice cream bars.\nAt the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible. \nNote: The boy can buy the ice cream bars in any order.\nReturn the maximum number of ice cream bars the boy can buy with coins coins.\nYou must solve the problem by counting sort.\n Example 1:\nInput: costs = [1,3,2,4,1], coins = 7\nOutput: 4\nExplanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.\nExample 2:\nInput: costs = [10,6,8,7,7,8], coins = 5\nOutput: 0\nExplanation: The boy cannot afford any of the ice cream bars.\nExample 3:\nInput: costs = [1,6,3,1,2,5], coins = 20\nOutput: 6\nExplanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n Constraints:\ncosts.length == n\n1 <= n <= 105\n1 <= costs[i] <= 105\n1 <= coins <= 108" }, { "post_href": "https://leetcode.com/problems/single-threaded-cpu/discuss/2004757/Python-or-Priority-Queue", "python_solutions": "class Solution:\n def getOrder(self, tasks: List[List[int]]) -> List[int]:\n dic=defaultdict(list)\n \n for i in range(len(tasks)):\n dic[tasks[i][0]].append((tasks[i][1],i))\n \n \n ans=[]\n keys=sorted(dic.keys())\n \n while keys:\n k=keys.pop(0)\n pq=dic[k]\n heapq.heapify(pq)\n time=k\n \n while pq:\n p_time,ind=heapq.heappop(pq)\n ans.append(ind)\n time+=p_time\n while keys:\n if keys[0]>time:\n break\n for item in dic[keys.pop(0)]:\n heapq.heappush(pq,item)\n return ans", "slug": "single-threaded-cpu", "post_title": "Python | Priority Queue", "user": "heckt27", "upvotes": 1, "views": 83, "problem_title": "single threaded cpu", "number": 1834, "acceptance": 0.42, "difficulty": "Medium", "__index_level_0__": 26202, "question": "You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.\nYou have a single-threaded CPU that can process at most one task at a time and will act in the following way:\nIf the CPU is idle and there are no available tasks to process, the CPU remains idle.\nIf the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.\nOnce a task is started, the CPU will process the entire task without stopping.\nThe CPU can finish a task then start a new one instantly.\nReturn the order in which the CPU will process the tasks.\n Example 1:\nInput: tasks = [[1,2],[2,4],[3,2],[4,1]]\nOutput: [0,2,3,1]\nExplanation: The events go as follows: \n- At time = 1, task 0 is available to process. Available tasks = {0}.\n- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n- At time = 2, task 1 is available to process. Available tasks = {1}.\n- At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n- At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n- At time = 10, the CPU finishes task 1 and becomes idle.\nExample 2:\nInput: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\nOutput: [4,3,2,0,1]\nExplanation: The events go as follows:\n- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.\n- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.\n- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.\n- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.\n- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.\n- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.\n- At time = 40, the CPU finishes task 1 and becomes idle.\n Constraints:\ntasks.length == n\n1 <= n <= 105\n1 <= enqueueTimei, processingTimei <= 109" }, { "post_href": "https://leetcode.com/problems/find-xor-sum-of-all-pairs-bitwise-and/discuss/2724403/Simple-python-code-with-explanation", "python_solutions": "class Solution:\n #example 1 \n #result =[(1&6)^(1&5)^(2&6)^(2&5)^(3&6)^(3&5)]\n \\ / \\ / \\ /\n # (1&(6^5)) ^ (2&(6^5)) ^ (3&(6^5)) \n \\ | /\n \\ | /\n \\ | /\n \\ | /\n # ((1^2^3) & (6^5))\n def getXORSum(self, a, b):\n x = 0 \n for i in range(len(a)):\n x = x ^ a[i]\n y = 0 \n for j in range(len(b)):\n y = y ^ b[j]\n return x & y", "slug": "find-xor-sum-of-all-pairs-bitwise-and", "post_title": "Simple python code with explanation", "user": "thomanani", "upvotes": 1, "views": 23, "problem_title": "find xor sum of all pairs bitwise and", "number": 1835, "acceptance": 0.601, "difficulty": "Hard", "__index_level_0__": 26211, "question": "The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.\nFor example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.\nYou are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.\nConsider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.\nReturn the XOR sum of the aforementioned list.\n Example 1:\nInput: arr1 = [1,2,3], arr2 = [6,5]\nOutput: 0\nExplanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].\nThe XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.\nExample 2:\nInput: arr1 = [12], arr2 = [4]\nOutput: 4\nExplanation: The list = [12 AND 4] = [4]. The XOR sum = 4.\n Constraints:\n1 <= arr1.length, arr2.length <= 105\n0 <= arr1[i], arr2[j] <= 109" }, { "post_href": "https://leetcode.com/problems/sum-of-digits-in-base-k/discuss/1175067/Python3-self-explained", "python_solutions": "class Solution:\n def sumBase(self, n: int, k: int) -> int:\n ans = 0\n while n: \n n, x = divmod(n, k)\n ans += x\n return ans", "slug": "sum-of-digits-in-base-k", "post_title": "[Python3] self-explained", "user": "ye15", "upvotes": 12, "views": 1200, "problem_title": "sum of digits in base k", "number": 1837, "acceptance": 0.768, "difficulty": "Easy", "__index_level_0__": 26219, "question": "Given an integer n (in base 10) and a base k, return the sum of the digits of n after converting n from base 10 to base k.\nAfter converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.\n Example 1:\nInput: n = 34, k = 6\nOutput: 9\nExplanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.\nExample 2:\nInput: n = 10, k = 10\nOutput: 1\nExplanation: n is already in base 10. 1 + 0 = 1.\n Constraints:\n1 <= n <= 100\n2 <= k <= 10" }, { "post_href": "https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/1179374/Python-3-Sliding-Window-Explanation-with-Code", "python_solutions": "class Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n nums.sort()\n n = len(nums)\n sum_s_w = nums[0]\n fin = 1\n i=0\n for j in range(1,n):\n sum_s_w+=nums[j]\n mx = nums[j]\n while sum_s_w+k int:\n vowels = \"aeiou\"\n ans = 0\n cnt = prev = -1 \n for i, x in enumerate(word): \n curr = vowels.index(x)\n if cnt >= 0: # in the middle of counting \n if 0 <= curr - prev <= 1: \n cnt += 1\n if x == \"u\": ans = max(ans, cnt)\n elif x == \"a\": cnt = 1\n else: cnt = -1 \n elif x == \"a\": cnt = 1\n prev = curr \n return ans", "slug": "longest-substring-of-all-vowels-in-order", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 9, "views": 703, "problem_title": "longest substring of all vowels in order", "number": 1839, "acceptance": 0.486, "difficulty": "Medium", "__index_level_0__": 26248, "question": "A string is considered beautiful if it satisfies the following conditions:\nEach of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.\nThe letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).\nFor example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful, but \"uaeio\", \"aeoiu\", and \"aaaeeeooo\" are not beautiful.\nGiven a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.\nA substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\nOutput: 13\nExplanation: The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.\nExample 2:\nInput: word = \"aeeeiiiioooauuuaeiou\"\nOutput: 5\nExplanation: The longest beautiful substring in word is \"aeiou\" of length 5.\nExample 3:\nInput: word = \"a\"\nOutput: 0\nExplanation: There is no beautiful substring, so return 0.\n Constraints:\n1 <= word.length <= 5 * 105\nword consists of characters 'a', 'e', 'i', 'o', and 'u'." }, { "post_href": "https://leetcode.com/problems/maximum-building-height/discuss/1175057/Python3-greedy", "python_solutions": "class Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n restrictions.extend([[1, 0], [n, n-1]])\n restrictions.sort()\n \n for i in reversed(range(len(restrictions)-1)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0])\n \n ans = 0 \n for i in range(1, len(restrictions)): \n restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0])\n ans = max(ans, (restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0] + restrictions[i][1])//2)\n return ans", "slug": "maximum-building-height", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 2, "views": 257, "problem_title": "maximum building height", "number": 1840, "acceptance": 0.353, "difficulty": "Hard", "__index_level_0__": 26270, "question": "You want to build n new buildings in a city. The new buildings will be built in a line and are labeled from 1 to n.\nHowever, there are city restrictions on the heights of the new buildings:\nThe height of each building must be a non-negative integer.\nThe height of the first building must be 0.\nThe height difference between any two adjacent buildings cannot exceed 1.\nAdditionally, there are city restrictions on the maximum height of specific buildings. These restrictions are given as a 2D integer array restrictions where restrictions[i] = [idi, maxHeighti] indicates that building idi must have a height less than or equal to maxHeighti.\nIt is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.\nReturn the maximum possible height of the tallest building.\n Example 1:\nInput: n = 5, restrictions = [[2,1],[4,1]]\nOutput: 2\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.\nExample 2:\nInput: n = 6, restrictions = []\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.\nExample 3:\nInput: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\nOutput: 5\nExplanation: The green area in the image indicates the maximum allowed height for each building.\nWe can build the buildings with heights [0,1,2,3,3,4,4,5,4,3], and the tallest building has a height of 5.\n Constraints:\n2 <= n <= 109\n0 <= restrictions.length <= min(n - 1, 105)\n2 <= idi <= n\nidi is unique.\n0 <= maxHeighti <= 109" }, { "post_href": "https://leetcode.com/problems/replace-all-digits-with-characters/discuss/1243646/Python3-simple-code-96-time-with-explanation", "python_solutions": "class Solution:\n def replaceDigits(self, s: str) -> str:\n\n ans = \"\"\n\n def shift(char, num):\n return chr(ord(char) + int(num))\n\n for index in range(len(s)):\n ans += shift(s[index-1], s[index]) if index % 2 else s[index]\n\n return ans", "slug": "replace-all-digits-with-characters", "post_title": "Python3 simple code 96% time, with explanation", "user": "albezx0", "upvotes": 5, "views": 327, "problem_title": "replace all digits with characters", "number": 1844, "acceptance": 0.7979999999999999, "difficulty": "Easy", "__index_level_0__": 26272, "question": "You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.\nThere is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.\nFor example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.\nFor every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).\nReturn s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.\n Example 1:\nInput: s = \"a1c1e1\"\nOutput: \"abcdef\"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('c',1) = 'd'\n- s[5] -> shift('e',1) = 'f'\nExample 2:\nInput: s = \"a1b2c3d4e\"\nOutput: \"abbdcfdhe\"\nExplanation: The digits are replaced as follows:\n- s[1] -> shift('a',1) = 'b'\n- s[3] -> shift('b',2) = 'd'\n- s[5] -> shift('c',3) = 'f'\n- s[7] -> shift('d',4) = 'h'\n Constraints:\n1 <= s.length <= 100\ns consists only of lowercase English letters and digits.\nshift(s[i-1], s[i]) <= 'z' for all odd indices i." }, { "post_href": "https://leetcode.com/problems/maximum-element-after-decreasing-and-rearranging/discuss/1503918/Python-O(N)-Time-and-Space.-Easy-to-understand", "python_solutions": "class Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n\t\tcounter = collections.Counter(arr)\n available = sum(n > len(arr) for n in arr)\n i = ans = len(arr)\n while i > 0:\n # This number is not in arr\n if not counter[i]:\n # Use another number to fill in its place. If we cannot, we have to decrease our max\n if available: available -= 1 \n else: ans -= 1\n # Other occurences can be used for future.\n else:\n available += counter[i] - 1\n i -= 1\n return ans", "slug": "maximum-element-after-decreasing-and-rearranging", "post_title": "[Python] O(N) Time and Space. Easy to understand", "user": "JummyEgg", "upvotes": 1, "views": 205, "problem_title": "maximum element after decreasing and rearranging", "number": 1846, "acceptance": 0.591, "difficulty": "Medium", "__index_level_0__": 26310, "question": "You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:\nThe value of the first element in arr must be 1.\nThe absolute difference between any 2 adjacent elements must be less than or equal to 1. In other words, abs(arr[i] - arr[i - 1]) <= 1 for each i where 1 <= i < arr.length (0-indexed). abs(x) is the absolute value of x.\nThere are 2 types of operations that you can perform any number of times:\nDecrease the value of any element of arr to a smaller positive integer.\nRearrange the elements of arr to be in any order.\nReturn the maximum possible value of an element in arr after performing the operations to satisfy the conditions.\n Example 1:\nInput: arr = [2,2,1,2,1]\nOutput: 2\nExplanation: \nWe can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].\nThe largest element in arr is 2.\nExample 2:\nInput: arr = [100,1,1000]\nOutput: 3\nExplanation: \nOne possible way to satisfy the conditions is by doing the following:\n1. Rearrange arr so it becomes [1,100,1000].\n2. Decrease the value of the second element to 2.\n3. Decrease the value of the third element to 3.\nNow arr = [1,2,3], which satisfies the conditions.\nThe largest element in arr is 3.\nExample 3:\nInput: arr = [1,2,3,4,5]\nOutput: 5\nExplanation: The array already satisfies the conditions, and the largest element is 5.\n Constraints:\n1 <= arr.length <= 105\n1 <= arr[i] <= 109" }, { "post_href": "https://leetcode.com/problems/closest-room/discuss/1186155/Python-3-Aggregate-sorted-list-detailed-explanation-(2080-ms)", "python_solutions": "class Solution:\n def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:\n ans = [0] * len(queries)\n \n # sort queries to handle largest size queries first\n q = deque(sorted([(size, room, i) for i, (room, size) in enumerate(queries)], key=lambda a: (-a[0], a[1], a[2])))\n\n # sort rooms by descending size\n rooms = deque(sorted(rooms, key=lambda x: -x[1]))\n\n # current available room ids\n cands = []\n \n \n while q:\n size, room, i = q.popleft()\n # add room ids to candidates as long as top of room size meet the requirements\n while rooms and rooms[0][1] >= size:\n bisect.insort(cands, rooms.popleft()[0])\n \n # if no room size available, return -1\n if not cands: ans[i] = -1\n \n # else use bisect to find optimal room ids\n else:\n loc = bisect.bisect_left(cands, room)\n if loc == 0: ans[i] = cands[loc]\n elif loc == len(cands): ans[i] = cands[-1]\n else: ans[i] = cands[loc - 1] if room - cands[loc - 1] <= cands[loc] - room else cands[loc]\n \n return ans", "slug": "closest-room", "post_title": "[Python 3] Aggregate sorted list, detailed explanation (2080 ms)", "user": "chestnut890123", "upvotes": 1, "views": 111, "problem_title": "closest room", "number": 1847, "acceptance": 0.353, "difficulty": "Hard", "__index_level_0__": 26320, "question": "There is a hotel with n rooms. The rooms are represented by a 2D integer array rooms where rooms[i] = [roomIdi, sizei] denotes that there is a room with room number roomIdi and size equal to sizei. Each roomIdi is guaranteed to be unique.\nYou are also given k queries in a 2D array queries where queries[j] = [preferredj, minSizej]. The answer to the jth query is the room number id of a room such that:\nThe room has a size of at least minSizej, and\nabs(id - preferredj) is minimized, where abs(x) is the absolute value of x.\nIf there is a tie in the absolute difference, then use the room with the smallest such id. If there is no such room, the answer is -1.\nReturn an array answer of length k where answer[j] contains the answer to the jth query.\n Example 1:\nInput: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\nOutput: [3,-1,3]\nExplanation: The answers to the queries are as follows:\nQuery = [3,1]: Room number 3 is the closest as abs(3 - 3) = 0, and its size of 2 is at least 1. The answer is 3.\nQuery = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\nQuery = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.\nExample 2:\nInput: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\nOutput: [2,1,3]\nExplanation: The answers to the queries are as follows:\nQuery = [2,3]: Room number 2 is the closest as abs(2 - 2) = 0, and its size of 3 is at least 3. The answer is 2.\nQuery = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\nQuery = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.\n Constraints:\nn == rooms.length\n1 <= n <= 105\nk == queries.length\n1 <= k <= 104\n1 <= roomIdi, preferredj <= 107\n1 <= sizei, minSizej <= 107" }, { "post_href": "https://leetcode.com/problems/minimum-distance-to-the-target-element/discuss/1186862/Python3-linear-sweep", "python_solutions": "class Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n ans = inf\n for i, x in enumerate(nums): \n if x == target: \n ans = min(ans, abs(i - start))\n return ans", "slug": "minimum-distance-to-the-target-element", "post_title": "[Python3] linear sweep", "user": "ye15", "upvotes": 9, "views": 302, "problem_title": "minimum distance to the target element", "number": 1848, "acceptance": 0.585, "difficulty": "Easy", "__index_level_0__": 26321, "question": "Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.\nReturn abs(i - start).\nIt is guaranteed that target exists in nums.\n Example 1:\nInput: nums = [1,2,3,4,5], target = 5, start = 3\nOutput: 1\nExplanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\nExample 2:\nInput: nums = [1], target = 1, start = 0\nOutput: 0\nExplanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.\nExample 3:\nInput: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\nOutput: 0\nExplanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.\n Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 104\n0 <= start < nums.length\ntarget is in nums." }, { "post_href": "https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/discuss/2632013/Clear-Python-DFS-with-comments", "python_solutions": "class Solution:\n def splitString(self, s: str) -> bool:\n \n \"\"\"\n Time = O(2^N)\n Space = O(N) space from stack\n \n \"\"\"\n def dfs(index: int, last: int) -> bool:\n if index == len(s):\n return True\n \n\t\t\t# j: [index, len(s)-1]\n for j in range(index, len(s)):\n\t\t\t\t# cur: [index, index] ~ [index, len(s)-1]\n cur = int(s[index:j + 1])\n\t\t\t\t# last: [...,index-1]\n\t\t\t\t# cur: [index+1, j]\n\t\t\t\t# last = cur -> next: [j+1,...)\n\t\t\t\t# DFS condition: cur = last - 1 && dfs(j+1, cur) == true\n if cur == last - 1 and dfs(j + 1, cur):\n return True\n return False\n \n for i in range(len(s) - 1):\n last = int(s[:i+1])\n if dfs(i + 1, last):\n return True\n return False", "slug": "splitting-a-string-into-descending-consecutive-values", "post_title": "Clear Python DFS with comments", "user": "changyou1009", "upvotes": 0, "views": 8, "problem_title": "splitting a string into descending consecutive values", "number": 1849, "acceptance": 0.3229999999999999, "difficulty": "Medium", "__index_level_0__": 26341, "question": "You are given a string s that consists of only digits.\nCheck if we can split s into two or more non-empty substrings such that the numerical values of the substrings are in descending order and the difference between numerical values of every two adjacent substrings is equal to 1.\nFor example, the string s = \"0090089\" can be split into [\"0090\", \"089\"] with numerical values [90,89]. The values are in descending order and adjacent values differ by 1, so this way is valid.\nAnother example, the string s = \"001\" can be split into [\"0\", \"01\"], [\"00\", \"1\"], or [\"0\", \"0\", \"1\"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.\nReturn true if it is possible to split s as described above, or false otherwise.\nA substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: s = \"1234\"\nOutput: false\nExplanation: There is no valid way to split s.\nExample 2:\nInput: s = \"050043\"\nOutput: true\nExplanation: s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\nThe values are in descending order with adjacent values differing by 1.\nExample 3:\nInput: s = \"9080701\"\nOutput: false\nExplanation: There is no valid way to split s.\n Constraints:\n1 <= s.length <= 20\ns only consists of digits." }, { "post_href": "https://leetcode.com/problems/minimum-adjacent-swaps-to-reach-the-kth-smallest-number/discuss/1186887/Python3-brute-force", "python_solutions": "class Solution:\n def getMinSwaps(self, num: str, k: int) -> int:\n num = list(num)\n orig = num.copy()\n \n for _ in range(k): \n for i in reversed(range(len(num)-1)): \n if num[i] < num[i+1]: \n ii = i+1 \n while ii < len(num) and num[i] < num[ii]: ii += 1\n num[i], num[ii-1] = num[ii-1], num[i]\n lo, hi = i+1, len(num)-1\n while lo < hi: \n num[lo], num[hi] = num[hi], num[lo]\n lo += 1\n hi -= 1\n break \n \n ans = 0\n for i in range(len(num)): \n ii = i\n while orig[i] != num[i]: \n ans += 1\n ii += 1\n num[i], num[ii] = num[ii], num[i]\n return ans", "slug": "minimum-adjacent-swaps-to-reach-the-kth-smallest-number", "post_title": "[Python3] brute-force", "user": "ye15", "upvotes": 7, "views": 803, "problem_title": "minimum adjacent swaps to reach the kth smallest number", "number": 1850, "acceptance": 0.7190000000000001, "difficulty": "Medium", "__index_level_0__": 26347, "question": "You are given a string num, representing a large integer, and an integer k.\nWe call some integer wonderful if it is a permutation of the digits in num and is greater in value than num. There can be many wonderful integers. However, we only care about the smallest-valued ones.\nFor example, when num = \"5489355142\":\nThe 1st smallest wonderful integer is \"5489355214\".\nThe 2nd smallest wonderful integer is \"5489355241\".\nThe 3rd smallest wonderful integer is \"5489355412\".\nThe 4th smallest wonderful integer is \"5489355421\".\nReturn the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.\nThe tests are generated in such a way that kth smallest wonderful integer exists.\n Example 1:\nInput: num = \"5489355142\", k = 4\nOutput: 2\nExplanation: The 4th smallest wonderful number is \"5489355421\". To get this number:\n- Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n- Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"\nExample 2:\nInput: num = \"11112\", k = 4\nOutput: 4\nExplanation: The 4th smallest wonderful number is \"21111\". To get this number:\n- Swap index 3 with index 4: \"11112\" -> \"11121\"\n- Swap index 2 with index 3: \"11121\" -> \"11211\"\n- Swap index 1 with index 2: \"11211\" -> \"12111\"\n- Swap index 0 with index 1: \"12111\" -> \"21111\"\nExample 3:\nInput: num = \"00123\", k = 1\nOutput: 1\nExplanation: The 1st smallest wonderful number is \"00132\". To get this number:\n- Swap index 3 with index 4: \"00123\" -> \"00132\"\n Constraints:\n2 <= num.length <= 1000\n1 <= k <= 1000\nnum only consists of digits." }, { "post_href": "https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/1422509/For-Beginners-oror-Easy-Approach-oror-Well-Explained-oror-Clean-and-Concise", "python_solutions": "class Solution:\ndef minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:\n \n intervals.sort(key = lambda x:x[1]-x[0])\n q = sorted([qu,i] for i,qu in enumerate(queries))\n res=[-1]*len(queries)\n\t\n for left,right in intervals:\n ind = bisect.bisect(q,[left])\n while ind int:\n # the timespan 1950-2050 covers 101 years\n\t\tdelta = [0] * 101\n\n\t\t# to make explicit the conversion from the year (1950 + i) to the ith index\n conversionDiff = 1950 \n\t\t\n for l in logs:\n\t\t\t# the log's first entry, birth, increases the population by 1\n delta[l[0] - conversionDiff] += 1 \n\t\t\t\n\t\t\t# the log's second entry, death, decreases the population by 1\n delta[l[1] - conversionDiff] -= 1\n \n runningSum = 0\n maxPop = 0\n year = 1950\n\t\t\n\t\t# find the year with the greatest population\n for i, d in enumerate(delta):\n runningSum += d\n\t\t\t\n\t\t\t# since we want the first year this population was reached, only update if strictly greater than the previous maximum population\n if runningSum > maxPop:\n maxPop = runningSum\n year = conversionDiff + i\n\t\t\t\t\n return year", "slug": "maximum-population-year", "post_title": "Python3 O(N)", "user": "signifying", "upvotes": 21, "views": 2000, "problem_title": "maximum population year", "number": 1854, "acceptance": 0.599, "difficulty": "Easy", "__index_level_0__": 26358, "question": "You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.\nThe population of some year x is the number of people alive during that year. The ith person is counted in year x's population if x is in the inclusive range [birthi, deathi - 1]. Note that the person is not counted in the year that they die.\nReturn the earliest year with the maximum population.\n Example 1:\nInput: logs = [[1993,1999],[2000,2010]]\nOutput: 1993\nExplanation: The maximum population is 1, and 1993 is the earliest year with this population.\nExample 2:\nInput: logs = [[1950,1961],[1960,1971],[1970,1981]]\nOutput: 1960\nExplanation: \nThe maximum population is 2, and it had happened in years 1960 and 1970.\nThe earlier year between them is 1960.\n Constraints:\n1 <= logs.length <= 100\n1950 <= birthi < deathi <= 2050" }, { "post_href": "https://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/2209743/Python3-simple-solution-using-two-pointers", "python_solutions": "class Solution:\n def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:\n length1, length2 = len(nums1), len(nums2)\n i,j = 0,0\n \n result = 0\n while i < length1 and j < length2:\n if nums1[i] > nums2[j]:\n i+=1\n else:\n result = max(result,j-i)\n j+=1\n \n return result", "slug": "maximum-distance-between-a-pair-of-values", "post_title": "\ud83d\udccc Python3 simple solution using two pointers", "user": "Dark_wolf_jss", "upvotes": 6, "views": 69, "problem_title": "maximum distance between a pair of values", "number": 1855, "acceptance": 0.527, "difficulty": "Medium", "__index_level_0__": 26372, "question": "You are given two non-increasing 0-indexed integer arrays nums1 and nums2.\nA pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i.\nReturn the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.\nAn array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.\n Example 1:\nInput: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\nOutput: 2\nExplanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\nThe maximum distance is 2 with pair (2,4).\nExample 2:\nInput: nums1 = [2,2,2], nums2 = [10,10,1]\nOutput: 1\nExplanation: The valid pairs are (0,0), (0,1), and (1,1).\nThe maximum distance is 1 with pair (0,1).\nExample 3:\nInput: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\nOutput: 2\nExplanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\nThe maximum distance is 2 with pair (2,4).\n Constraints:\n1 <= nums1.length, nums2.length <= 105\n1 <= nums1[i], nums2[j] <= 105\nBoth nums1 and nums2 are non-increasing." }, { "post_href": "https://leetcode.com/problems/maximum-subarray-min-product/discuss/1198800/Python3-mono-stack", "python_solutions": "class Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n prefix = [0]\n for x in nums: prefix.append(prefix[-1] + x)\n \n ans = 0 \n stack = []\n for i, x in enumerate(nums + [-inf]): # append \"-inf\" to force flush all elements\n while stack and stack[-1][1] >= x: \n _, xx = stack.pop()\n ii = stack[-1][0] if stack else -1 \n ans = max(ans, xx*(prefix[i] - prefix[ii+1]))\n stack.append((i, x))\n return ans % 1_000_000_007", "slug": "maximum-subarray-min-product", "post_title": "[Python3] mono-stack", "user": "ye15", "upvotes": 10, "views": 345, "problem_title": "maximum subarray min product", "number": 1856, "acceptance": 0.3779999999999999, "difficulty": "Medium", "__index_level_0__": 26384, "question": "The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.\nFor example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.\nGiven an array of integers nums, return the maximum min-product of any non-empty subarray of nums. Since the answer may be large, return it modulo 109 + 7.\nNote that the min-product should be maximized before performing the modulo operation. Testcases are generated such that the maximum min-product without modulo will fit in a 64-bit signed integer.\nA subarray is a contiguous part of an array.\n Example 1:\nInput: nums = [1,2,3,2]\nOutput: 14\nExplanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n2 * (2+3+2) = 2 * 7 = 14.\nExample 2:\nInput: nums = [2,3,3,1,2]\nOutput: 18\nExplanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n3 * (3+3) = 3 * 6 = 18.\nExample 3:\nInput: nums = [3,1,5,6,4,2]\nOutput: 60\nExplanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n4 * (5+6+4) = 4 * 15 = 60.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 107" }, { "post_href": "https://leetcode.com/problems/largest-color-value-in-a-directed-graph/discuss/1200668/easy-python-sol-..", "python_solutions": "class Solution(object):\n def largestPathValue(self, colors, edges):\n n=len(colors)\n graph=defaultdict(list)\n indegree=defaultdict(int)\n \n for u,v in edges:\n graph[u].append(v)\n indegree[v]+=1\n \n queue=[] \n dp=[[0]*26 for _ in range(n)]\n colorvalues=[ord(c)-ord(\"a\") for c in colors]\n for u in range(n):\n if u not in indegree:\n queue.append(u)\n dp[u][colorvalues[u]]=1\n \n visited=0\n while queue:\n u=queue.pop()\n visited+=1\n\n for v in graph[u]:\n for c in range(26):\n dp[v][c]=max(dp[v][c],dp[u][c] + (c==colorvalues[v]))\n indegree[v]-=1\n if indegree[v]==0:\n queue.append(v)\n del indegree[v]\n if visited x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.\nReturn the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.\n Example 1:\nInput: colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]\nOutput: 3\nExplanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored \"a\" (red in the above image).\nExample 2:\nInput: colors = \"a\", edges = [[0,0]]\nOutput: -1\nExplanation: There is a cycle from 0 to 0.\n Constraints:\nn == colors.length\nm == edges.length\n1 <= n <= 105\n0 <= m <= 105\ncolors consists of lowercase English letters.\n0 <= aj, bj < n" }, { "post_href": "https://leetcode.com/problems/sorting-the-sentence/discuss/1219040/Python3-99.60-Fast-Solution", "python_solutions": "class Solution:\n def sortSentence(self, s: str) -> str:\n arr = [i[-1] + i[:-1] for i in s.split()]\n \n arr.sort()\n \n ans = \"\"\n for i in arr:\n ans += i[1:] + ' '\n \n return ans[:-1]", "slug": "sorting-the-sentence", "post_title": "[Python3] 99.60% Fast Solution", "user": "VoidCupboard", "upvotes": 23, "views": 2000, "problem_title": "sorting the sentence", "number": 1859, "acceptance": 0.8440000000000001, "difficulty": "Easy", "__index_level_0__": 26394, "question": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters.\nA sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.\nFor example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\".\nGiven a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.\n Example 1:\nInput: s = \"is2 sentence4 This1 a3\"\nOutput: \"This is a sentence\"\nExplanation: Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.\nExample 2:\nInput: s = \"Myself2 Me1 I4 and3\"\nOutput: \"Me Myself and I\"\nExplanation: Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.\n Constraints:\n2 <= s.length <= 200\ns consists of lowercase and uppercase English letters, spaces, and digits from 1 to 9.\nThe number of words in s is between 1 and 9.\nThe words in s are separated by a single space.\ns contains no leading or trailing spaces." }, { "post_href": "https://leetcode.com/problems/incremental-memory-leak/discuss/1210088/JavaC%2B%2BPython-Solution", "python_solutions": "class Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n i = 1\n while max(memory1, memory2) >= i:\n if memory1 >= memory2:\n memory1 -= i\n else:\n memory2 -= i\n i += 1\n return [i, memory1, memory2]", "slug": "incremental-memory-leak", "post_title": "[Java/C++/Python] Solution", "user": "lokeshsenthilkumar", "upvotes": 27, "views": 1800, "problem_title": "incremental memory leak", "number": 1860, "acceptance": 0.718, "difficulty": "Medium", "__index_level_0__": 26438, "question": "You are given two integers memory1 and memory2 representing the available memory in bits on two memory sticks. There is currently a faulty program running that consumes an increasing amount of memory every second.\nAt the ith second (starting from 1), i bits of memory are allocated to the stick with more available memory (or from the first memory stick if both have the same available memory). If neither stick has at least i bits of available memory, the program crashes.\nReturn an array containing [crashTime, memory1crash, memory2crash], where crashTime is the time (in seconds) when the program crashed and memory1crash and memory2crash are the available bits of memory in the first and second sticks respectively.\n Example 1:\nInput: memory1 = 2, memory2 = 2\nOutput: [3,1,0]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n- At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\nExample 2:\nInput: memory1 = 8, memory2 = 11\nOutput: [6,0,4]\nExplanation: The memory is allocated as follows:\n- At the 1st second, 1 bit of memory is allocated to stick 2. The second stick now has 10 bit of available memory.\n- At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 8 bits of available memory.\n- At the 3rd second, 3 bits of memory are allocated to stick 1. The first stick now has 5 bits of available memory.\n- At the 4th second, 4 bits of memory are allocated to stick 2. The second stick now has 4 bits of available memory.\n- At the 5th second, 5 bits of memory are allocated to stick 1. The first stick now has 0 bits of available memory.\n- At the 6th second, the program crashes. The sticks have 0 and 4 bits available respectively.\n Constraints:\n0 <= memory1, memory2 <= 231 - 1" }, { "post_href": "https://leetcode.com/problems/rotating-the-box/discuss/1622675/Python-Easy-explanation", "python_solutions": "class Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n # move stones to right, row by row\n for i in range(len(box)):\n stone = 0\n for j in range(len(box[0])):\n if box[i][j] == '#': # if a stone\n stone += 1\n box[i][j] = '.'\n elif box[i][j] == '*': # if a obstacle\n for m in range(stone):\n box[i][j-m-1] = '#'\n stone = 0\n # if reaches the end of j, but still have stone\n if stone != 0:\n for m in range(stone):\n box[i][j-m] = '#'\n \n # rotate box, same as leetcode #48\n box[:] = zip(*box[::-1])\n \n return box", "slug": "rotating-the-box", "post_title": "[Python] Easy explanation", "user": "sashaxx", "upvotes": 10, "views": 1100, "problem_title": "rotating the box", "number": 1861, "acceptance": 0.647, "difficulty": "Medium", "__index_level_0__": 26444, "question": "You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:\nA stone '#'\nA stationary obstacle '*'\nEmpty '.'\nThe box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.\nIt is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.\nReturn an n x m matrix representing the box after the rotation described above.\n Example 1:\nInput: box = [[\"#\",\".\",\"#\"]]\nOutput: [[\".\"],\n [\"#\"],\n [\"#\"]]\nExample 2:\nInput: box = [[\"#\",\".\",\"*\",\".\"],\n [\"#\",\"#\",\"*\",\".\"]]\nOutput: [[\"#\",\".\"],\n [\"#\",\"#\"],\n [\"*\",\"*\"],\n [\".\",\".\"]]\nExample 3:\nInput: box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\n [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\n [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\nOutput: [[\".\",\"#\",\"#\"],\n [\".\",\"#\",\"#\"],\n [\"#\",\"#\",\"*\"],\n [\"#\",\"*\",\".\"],\n [\"#\",\".\",\"*\"],\n [\"#\",\".\",\".\"]]\n Constraints:\nm == box.length\nn == box[i].length\n1 <= m, n <= 500\nbox[i][j] is either '#', '*', or '.'." }, { "post_href": "https://leetcode.com/problems/sum-of-floored-pairs/discuss/1218305/PythonPython3-solution-BruteForce-and-Optimized-solution-using-Dictionary", "python_solutions": "class Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n sumP = 0 #To store the value of Sum of floor values\n for i in nums: #Traverse every element in nums\n for j in nums: #Traverse every element in nums\n sumP += (j//i) #Simply do floor division and add the number to sumP\n return sumP % (10**9 +7)#return the sumof the pairs", "slug": "sum-of-floored-pairs", "post_title": "Python/Python3 solution BruteForce & Optimized solution using Dictionary", "user": "prasanthksp1009", "upvotes": 7, "views": 279, "problem_title": "sum of floored pairs", "number": 1862, "acceptance": 0.282, "difficulty": "Hard", "__index_level_0__": 26463, "question": "Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 109 + 7.\nThe floor() function returns the integer part of the division.\n Example 1:\nInput: nums = [2,5,9]\nOutput: 10\nExplanation:\nfloor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\nfloor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\nfloor(5 / 2) = 2\nfloor(9 / 2) = 4\nfloor(9 / 5) = 1\nWe calculate the floor of the division for every pair of indices in the array then sum them up.\nExample 2:\nInput: nums = [7,7,7,7,7,7,7]\nOutput: 49\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/sum-of-all-subset-xor-totals/discuss/1211232/Python3-power-set", "python_solutions": "class Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n ans = 0\n for mask in range(1 << len(nums)): \n val = 0\n for i in range(len(nums)): \n if mask & 1 << i: val ^= nums[i]\n ans += val\n return ans", "slug": "sum-of-all-subset-xor-totals", "post_title": "[Python3] power set", "user": "ye15", "upvotes": 8, "views": 1100, "problem_title": "sum of all subset xor totals", "number": 1863, "acceptance": 0.79, "difficulty": "Easy", "__index_level_0__": 26466, "question": "The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.\nFor example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.\nGiven an array nums, return the sum of all XOR totals for every subset of nums. \nNote: Subsets with the same elements should be counted multiple times.\nAn array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.\n Example 1:\nInput: nums = [1,3]\nOutput: 6\nExplanation: The 4 subsets of [1,3] are:\n- The empty subset has an XOR total of 0.\n- [1] has an XOR total of 1.\n- [3] has an XOR total of 3.\n- [1,3] has an XOR total of 1 XOR 3 = 2.\n0 + 1 + 3 + 2 = 6\nExample 2:\nInput: nums = [5,1,6]\nOutput: 28\nExplanation: The 8 subsets of [5,1,6] are:\n- The empty subset has an XOR total of 0.\n- [5] has an XOR total of 5.\n- [1] has an XOR total of 1.\n- [6] has an XOR total of 6.\n- [5,1] has an XOR total of 5 XOR 1 = 4.\n- [5,6] has an XOR total of 5 XOR 6 = 3.\n- [1,6] has an XOR total of 1 XOR 6 = 7.\n- [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2.\n0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28\nExample 3:\nInput: nums = [3,4,5,6,7,8]\nOutput: 480\nExplanation: The sum of all XOR totals for every subset is 480.\n Constraints:\n1 <= nums.length <= 12\n1 <= nums[i] <= 20" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/1211146/Python3-greedy", "python_solutions": "class Solution:\n def minSwaps(self, s: str) -> int:\n ones = s.count(\"1\")\n zeros = len(s) - ones \n if abs(ones - zeros) > 1: return -1 # impossible\n \n def fn(x): \n \"\"\"Return number of swaps if string starts with x.\"\"\"\n ans = 0 \n for c in s: \n if c != x: ans += 1\n x = \"1\" if x == \"0\" else \"0\"\n return ans//2\n \n if ones > zeros: return fn(\"1\")\n elif ones < zeros: return fn(\"0\")\n else: return min(fn(\"0\"), fn(\"1\"))", "slug": "minimum-number-of-swaps-to-make-the-binary-string-alternating", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 23, "views": 963, "problem_title": "minimum number of swaps to make the binary string alternating", "number": 1864, "acceptance": 0.425, "difficulty": "Medium", "__index_level_0__": 26489, "question": "Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.\nThe string is called alternating if no two adjacent characters are equal. For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\nAny two characters may be swapped, even if they are not adjacent.\n Example 1:\nInput: s = \"111000\"\nOutput: 1\nExplanation: Swap positions 1 and 4: \"111000\" -> \"101010\"\nThe string is now alternating.\nExample 2:\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating, no swaps are needed.\nExample 3:\nInput: s = \"1110\"\nOutput: -1\n Constraints:\n1 <= s.length <= 1000\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-rearrange-sticks-with-k-sticks-visible/discuss/1211157/Python3-top-down-dp", "python_solutions": "class Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n \n @cache \n def fn(n, k): \n \"\"\"Return number of ways to rearrange n sticks to that k are visible.\"\"\"\n if n == k: return 1\n if k == 0: return 0\n return ((n-1)*fn(n-1, k) + fn(n-1, k-1)) % 1_000_000_007\n \n return fn(n, k)", "slug": "number-of-ways-to-rearrange-sticks-with-k-sticks-visible", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 4, "views": 253, "problem_title": "number of ways to rearrange sticks with k sticks visible", "number": 1866, "acceptance": 0.5579999999999999, "difficulty": "Hard", "__index_level_0__": 26498, "question": "There are n uniquely-sized sticks whose lengths are integers from 1 to n. You want to arrange the sticks such that exactly k sticks are visible from the left. A stick is visible from the left if there are no longer sticks to the left of it.\nFor example, if the sticks are arranged [1,3,2,5,4], then the sticks with lengths 1, 3, and 5 are visible from the left.\nGiven n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\nInput: n = 3, k = 2\nOutput: 3\nExplanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\nThe visible sticks are underlined.\nExample 2:\nInput: n = 5, k = 5\nOutput: 1\nExplanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\nThe visible sticks are underlined.\nExample 3:\nInput: n = 20, k = 11\nOutput: 647427950\nExplanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.\n Constraints:\n1 <= n <= 1000\n1 <= k <= n" }, { "post_href": "https://leetcode.com/problems/longer-contiguous-segments-of-ones-than-zeros/discuss/1261757/Short-O(n)-Solution(python).", "python_solutions": "class Solution:\n def checkZeroOnes(self, s: str) -> bool:\n zero_in=temp=0\n for i in s:\n if i==\"0\":\n temp+=1\n if temp>zero_in:\n zero_in=temp\n else:\n temp=0\n # Longest contiguous 0 in s is zero_in \n return \"1\"*(zero_in+1) in s #return boolean value", "slug": "longer-contiguous-segments-of-ones-than-zeros", "post_title": "Short O(n) Solution(python).", "user": "_jorjis", "upvotes": 3, "views": 183, "problem_title": "longer contiguous segments of ones than zeros", "number": 1869, "acceptance": 0.603, "difficulty": "Easy", "__index_level_0__": 26499, "question": "Given a binary string s, return true if the longest contiguous segment of 1's is strictly longer than the longest contiguous segment of 0's in s, or return false otherwise.\nFor example, in s = \"110100010\" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.\nNote that if there are no 0's, then the longest continuous segment of 0's is considered to have a length 0. The same applies if there is no 1's.\n Example 1:\nInput: s = \"1101\"\nOutput: true\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"1101\"\nThe longest contiguous segment of 0s has length 1: \"1101\"\nThe segment of 1s is longer, so return true.\nExample 2:\nInput: s = \"111000\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 3: \"111000\"\nThe longest contiguous segment of 0s has length 3: \"111000\"\nThe segment of 1s is not longer, so return false.\nExample 3:\nInput: s = \"110100010\"\nOutput: false\nExplanation:\nThe longest contiguous segment of 1s has length 2: \"110100010\"\nThe longest contiguous segment of 0s has length 3: \"110100010\"\nThe segment of 1s is not longer, so return false.\n Constraints:\n1 <= s.length <= 100\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/minimum-speed-to-arrive-on-time/discuss/1225585/Python3-Concise-binary-search-code-with-comments", "python_solutions": "class Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n\t\t# the speed upper is either the longest train ride: max(dist),\n\t\t# or the last train ride divide by 0.01: ceil(dist[-1] / 0.01).\n\t\t# notice: \"hour will have at most two digits after the decimal point\"\n upper = max(max(dist), ceil(dist[-1] / 0.01))\n # \n\t\t# the function to calcute total time consumed\n total = lambda speed: sum(map(lambda x: ceil(x / speed), dist[:-1])) + (dist[-1] / speed)\n\t\t# the case of impossible to arrive office on time\n if total(upper) > hour:\n return -1\n # \n\t\t# binary search: find the mimimal among \"all\" feasible answers\n left, right = 1, upper\n while left < right: \n mid = left + (right - left) // 2\n if total(mid) > hour:\n left = mid + 1 # should be larger\n else:\n right = mid # should explore a smaller one\n return right", "slug": "minimum-speed-to-arrive-on-time", "post_title": "[Python3] Concise binary search code with comments", "user": "macroway", "upvotes": 4, "views": 322, "problem_title": "minimum speed to arrive on time", "number": 1870, "acceptance": 0.374, "difficulty": "Medium", "__index_level_0__": 26528, "question": "You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride.\nEach train can only depart at an integer hour, so you may need to wait in between each train ride.\nFor example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.\nReturn the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time.\nTests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point.\n Example 1:\nInput: dist = [1,3,2], hour = 6\nOutput: 1\nExplanation: At speed 1:\n- The first train ride takes 1/1 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n- You will arrive at exactly the 6 hour mark.\nExample 2:\nInput: dist = [1,3,2], hour = 2.7\nOutput: 3\nExplanation: At speed 3:\n- The first train ride takes 1/3 = 0.33333 hours.\n- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n- You will arrive at the 2.66667 hour mark.\nExample 3:\nInput: dist = [1,3,2], hour = 1.9\nOutput: -1\nExplanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n Constraints:\nn == dist.length\n1 <= n <= 105\n1 <= dist[i] <= 105\n1 <= hour <= 109\nThere will be at most two digits after the decimal point in hour." }, { "post_href": "https://leetcode.com/problems/jump-game-vii/discuss/1224907/Python3-prefix-sum", "python_solutions": "class Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n prefix = [0, 1]\n for i in range(1, len(s)): \n prefix.append(prefix[-1])\n lo = max(0, i-maxJump)\n hi = max(0, i-minJump+1)\n if s[i] == \"0\" and prefix[hi] - prefix[lo] > 0: prefix[-1] += 1\n return prefix[-1] > prefix[-2]", "slug": "jump-game-vii", "post_title": "[Python3] prefix sum", "user": "ye15", "upvotes": 3, "views": 123, "problem_title": "jump game vii", "number": 1871, "acceptance": 0.251, "difficulty": "Medium", "__index_level_0__": 26539, "question": "You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled:\ni + minJump <= j <= min(i + maxJump, s.length - 1), and\ns[j] == '0'.\nReturn true if you can reach index s.length - 1 in s, or false otherwise.\n Example 1:\nInput: s = \"011010\", minJump = 2, maxJump = 3\nOutput: true\nExplanation:\nIn the first step, move from index 0 to index 3. \nIn the second step, move from index 3 to index 5.\nExample 2:\nInput: s = \"01101110\", minJump = 2, maxJump = 3\nOutput: false\n Constraints:\n2 <= s.length <= 105\ns[i] is either '0' or '1'.\ns[0] == '0'\n1 <= minJump <= maxJump < s.length" }, { "post_href": "https://leetcode.com/problems/stone-game-viii/discuss/1224872/Top-Down-and-Bottom-Up", "python_solutions": "class Solution:\n def stoneGameVIII(self, s: List[int]) -> int:\n s, res = list(accumulate(s)), 0\n for i in range(len(s) - 1, 0, -1):\n res = s[i] if i == len(s) - 1 else max(res, s[i] - res)\n return res", "slug": "stone-game-viii", "post_title": "Top-Down and Bottom-Up", "user": "votrubac", "upvotes": 49, "views": 2700, "problem_title": "stone game viii", "number": 1872, "acceptance": 0.524, "difficulty": "Hard", "__index_level_0__": 26552, "question": "Alice and Bob take turns playing a game, with Alice starting first.\nThere are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:\nChoose an integer x > 1, and remove the leftmost x stones from the row.\nAdd the sum of the removed stones' values to the player's score.\nPlace a new stone, whose value is equal to that sum, on the left side of the row.\nThe game stops when only one stone is left in the row.\nThe score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.\nGiven an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.\n Example 1:\nInput: stones = [-1,2,-3,4,-5]\nOutput: 5\nExplanation:\n- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of\n value 2 on the left. stones = [2,-5].\n- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on\n the left. stones = [-3].\nThe difference between their scores is 2 - (-3) = 5.\nExample 2:\nInput: stones = [7,-6,5,10,5,-2,-6]\nOutput: 13\nExplanation:\n- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a\n stone of value 13 on the left. stones = [13].\nThe difference between their scores is 13 - 0 = 13.\nExample 3:\nInput: stones = [-10,-12]\nOutput: -22\nExplanation:\n- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her\n score and places a stone of value -22 on the left. stones = [-22].\nThe difference between their scores is (-22) - 0 = -22.\n Constraints:\nn == stones.length\n2 <= n <= 105\n-104 <= stones[i] <= 104" }, { "post_href": "https://leetcode.com/problems/substrings-of-size-three-with-distinct-characters/discuss/1356591/Easy-Python-Solution(98.80)", "python_solutions": "class Solution:\n def countGoodSubstrings(self, s: str) -> int:\n count=0\n for i in range(len(s)-2):\n if(s[i]!=s[i+1] and s[i]!=s[i+2] and s[i+1]!=s[i+2]):\n count+=1\n return count", "slug": "substrings-of-size-three-with-distinct-characters", "post_title": "Easy Python Solution(98.80%)", "user": "Sneh17029", "upvotes": 13, "views": 878, "problem_title": "substrings of size three with distinct characters", "number": 1876, "acceptance": 0.703, "difficulty": "Easy", "__index_level_0__": 26556, "question": "A string is good if there are no repeated characters.\nGiven a string s, return the number of good substrings of length three in s.\nNote that if there are multiple occurrences of the same substring, every occurrence should be counted.\nA substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: s = \"xyzzaz\"\nOutput: 1\nExplanation: There are 4 substrings of size 3: \"xyz\", \"yzz\", \"zza\", and \"zaz\". \nThe only good substring of length 3 is \"xyz\".\nExample 2:\nInput: s = \"aababcabc\"\nOutput: 4\nExplanation: There are 7 substrings of size 3: \"aab\", \"aba\", \"bab\", \"abc\", \"bca\", \"cab\", and \"abc\".\nThe good substrings are \"abc\", \"bca\", \"cab\", and \"abc\".\n Constraints:\n1 <= s.length <= 100\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimize-maximum-pair-sum-in-array/discuss/2087728/Python-Easy-To-Understand-Code-oror-Beginner-Friendly-oror-Brute-Force", "python_solutions": "class Solution:\n def minPairSum(self, nums: List[int]) -> int:\n pair_sum = []\n nums.sort()\n for i in range(len(nums)//2):\n pair_sum.append(nums[i]+nums[len(nums)-i-1])\n return max(pair_sum)", "slug": "minimize-maximum-pair-sum-in-array", "post_title": "Python Easy To Understand Code || Beginner Friendly || Brute Force", "user": "Shivam_Raj_Sharma", "upvotes": 5, "views": 207, "problem_title": "minimize maximum pair sum in array", "number": 1877, "acceptance": 0.8029999999999999, "difficulty": "Medium", "__index_level_0__": 26606, "question": "The pair sum of a pair (a,b) is equal to a + b. The maximum pair sum is the largest pair sum in a list of pairs.\nFor example, if we have pairs (1,5), (2,3), and (4,4), the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8.\nGiven an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:\nEach element of nums is in exactly one pair, and\nThe maximum pair sum is minimized.\nReturn the minimized maximum pair sum after optimally pairing up the elements.\n Example 1:\nInput: nums = [3,5,2,3]\nOutput: 7\nExplanation: The elements can be paired up into pairs (3,3) and (5,2).\nThe maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.\nExample 2:\nInput: nums = [3,5,4,2,4,6]\nOutput: 8\nExplanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).\nThe maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.\n Constraints:\nn == nums.length\n2 <= n <= 105\nn is even.\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/get-biggest-three-rhombus-sums-in-a-grid/discuss/1239929/python-oror-100-faster-oror-well-explained-oror-Simple-approach", "python_solutions": "class Solution:\ndef getBiggestThree(self, grid: List[List[int]]) -> List[int]:\n \n def calc(l,r,u,d):\n sc=0\n c1=c2=(l+r)//2\n expand=True\n for row in range(u,d+1):\n if c1==c2:\n sc+=grid[row][c1]\n else:\n sc+=grid[row][c1]+grid[row][c2]\n \n if c1==l:\n expand=False\n \n if expand:\n c1-=1\n c2+=1\n else:\n c1+=1\n c2-=1\n return sc\n \n \n m=len(grid)\n n=len(grid[0])\n heap=[]\n for i in range(m):\n for j in range(n):\n l=r=j\n d=i\n while l>=0 and r<=n-1 and d<=m-1:\n sc=calc(l,r,i,d)\n l-=1\n r+=1\n d+=2\n if len(heap)<3:\n if sc not in heap:\n heapq.heappush(heap,sc)\n else:\n if sc not in heap and sc>heap[0]:\n heapq.heappop(heap)\n heapq.heappush(heap,sc)\n \n heap.sort(reverse=True)\n return heap", "slug": "get-biggest-three-rhombus-sums-in-a-grid", "post_title": "\ud83d\udc0d {python} || 100% faster || well-explained || Simple approach", "user": "abhi9Rai", "upvotes": 6, "views": 721, "problem_title": "get biggest three rhombus sums in a grid", "number": 1878, "acceptance": 0.4639999999999999, "difficulty": "Medium", "__index_level_0__": 26645, "question": "You are given an m x n integer matrix grid.\nA rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:\nNote that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.\nReturn the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.\n Example 1:\nInput: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]\nOutput: [228,216,211]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 20 + 3 + 200 + 5 = 228\n- Red: 200 + 2 + 10 + 4 = 216\n- Green: 5 + 200 + 4 + 2 = 211\nExample 2:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: [20,9,8]\nExplanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n- Blue: 4 + 2 + 6 + 8 = 20\n- Red: 9 (area 0 rhombus in the bottom right corner)\n- Green: 8 (area 0 rhombus in the bottom middle)\nExample 3:\nInput: grid = [[7,7,7]]\nOutput: [7]\nExplanation: All three possible rhombus sums are the same, so return [7].\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 50\n1 <= grid[i][j] <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-xor-sum-of-two-arrays/discuss/1238641/Bit-Mask", "python_solutions": "class Solution:\n def minimumXORSum(self, a: List[int], b: List[int]) -> int:\n @cache\n def dp(mask: int) -> int:\n i = bin(mask).count(\"1\")\n if i >= len(a):\n return 0\n return min((a[i] ^ b[j]) + dp(mask + (1 << j)) \n for j in range(len(b)) if mask & (1 << j) == 0)\n return dp(0)", "slug": "minimum-xor-sum-of-two-arrays", "post_title": "Bit Mask", "user": "votrubac", "upvotes": 103, "views": 6400, "problem_title": "minimum xor sum of two arrays", "number": 1879, "acceptance": 0.4479999999999999, "difficulty": "Hard", "__index_level_0__": 26651, "question": "You are given two integer arrays nums1 and nums2 of length n.\nThe XOR sum of the two integer arrays is (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (0-indexed).\nFor example, the XOR sum of [1,2,3] and [3,2,1] is equal to (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4.\nRearrange the elements of nums2 such that the resulting XOR sum is minimized.\nReturn the XOR sum after the rearrangement.\n Example 1:\nInput: nums1 = [1,2], nums2 = [2,3]\nOutput: 2\nExplanation: Rearrange nums2 so that it becomes [3,2].\nThe XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.\nExample 2:\nInput: nums1 = [1,0,3], nums2 = [5,3,4]\nOutput: 8\nExplanation: Rearrange nums2 so that it becomes [5,4,3]. \nThe XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.\n Constraints:\nn == nums1.length\nn == nums2.length\n1 <= n <= 14\n0 <= nums1[i], nums2[i] <= 107" }, { "post_href": "https://leetcode.com/problems/check-if-word-equals-summation-of-two-words/discuss/1241968/Minus-49", "python_solutions": "class Solution:\n def isSumEqual(self, first: str, second: str, target: str) -> bool:\n def op(s: str): return \"\".join(chr(ord(ch) - 49) for ch in s)\n return int(op(first)) + int(op(second)) == int(op(target))", "slug": "check-if-word-equals-summation-of-two-words", "post_title": "Minus 49", "user": "votrubac", "upvotes": 18, "views": 1200, "problem_title": "check if word equals summation of two words", "number": 1880, "acceptance": 0.738, "difficulty": "Easy", "__index_level_0__": 26653, "question": "The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).\nThe numerical value of some string of lowercase English letters s is the concatenation of the letter values of each letter in s, which is then converted into an integer.\nFor example, if s = \"acb\", we concatenate each letter's letter value, resulting in \"021\". After converting it, we get 21.\nYou are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.\nReturn true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.\n Example 1:\nInput: firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\nOutput: true\nExplanation:\nThe numerical value of firstWord is \"acb\" -> \"021\" -> 21.\nThe numerical value of secondWord is \"cba\" -> \"210\" -> 210.\nThe numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\nWe return true because 21 + 210 == 231.\nExample 2:\nInput: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\nOutput: false\nExplanation: \nThe numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aab\" -> \"001\" -> 1.\nWe return false because 0 + 0 != 1.\nExample 3:\nInput: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\nOutput: true\nExplanation: \nThe numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\nThe numerical value of secondWord is \"a\" -> \"0\" -> 0.\nThe numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\nWe return true because 0 + 0 == 0.\n Constraints:\n1 <= firstWord.length, secondWord.length, targetWord.length <= 8\nfirstWord, secondWord, and targetWord consist of lowercase English letters from 'a' to 'j' inclusive." }, { "post_href": "https://leetcode.com/problems/maximum-value-after-insertion/discuss/1240010/Python-oror-simple-O(N)-iteration", "python_solutions": "class Solution:\n def maxValue(self, n: str, x: int) -> str:\n if int(n)>0:\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])>=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n else:\n n = n[1:]\n ans = \"\"\n flag = False\n for i in range(len(n)):\n if int(n[i])<=x:\n ans += n[i]\n else:\n a = n[:i]\n b = n[i:]\n ans = a+str(x)+b\n \n flag = True\n break\n if not flag:\n ans += str(x)\n ans = \"-\"+ans\n \n return ans", "slug": "maximum-value-after-insertion", "post_title": "Python || simple O(N) iteration", "user": "harshhx", "upvotes": 5, "views": 536, "problem_title": "maximum value after insertion", "number": 1881, "acceptance": 0.366, "difficulty": "Medium", "__index_level_0__": 26701, "question": "You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.\nYou want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.\nFor example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.\nIf n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.\nReturn a string representing the maximum value of n after the insertion.\n Example 1:\nInput: n = \"99\", x = 9\nOutput: \"999\"\nExplanation: The result is the same regardless of where you insert 9.\nExample 2:\nInput: n = \"-13\", x = 2\nOutput: \"-123\"\nExplanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.\n Constraints:\n1 <= n.length <= 105\n1 <= x <= 9\nThe digits in n are in the range [1, 9].\nn is a valid representation of an integer.\nIn the case of a negative n, it will begin with '-'." }, { "post_href": "https://leetcode.com/problems/process-tasks-using-servers/discuss/1240147/Python-oror-Heap-oror-O(n%2Bmlogn)-oror-easy-and-well-explained", "python_solutions": "class Solution:\ndef assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n \n # sort the servers in order of weight, keeping index \n server_avail = [(w,i) for i,w in enumerate(servers)]\n heapify(server_avail)\n tasks_in_progress = []\n res = []\n st=0\n for j,task in enumerate(tasks):\n #starting time of task\n st = max(st,j)\n \n # if any server is not free then we can take start-time equal to end-time of task\n if not server_avail:\n st = tasks_in_progress[0][0]\n \n # pop the completed task's server and push inside the server avail\n while tasks_in_progress and tasks_in_progress[0][0]<=st:\n heapq.heappush(server_avail,heappop(tasks_in_progress)[1])\n \n # append index of used server in res\n res.append(server_avail[0][1])\n \n # push the first available server in \"server_avail\" heap to \"tasks_in_progress\" heap\n heapq.heappush(tasks_in_progress,(st+task,heappop(server_avail)))\n \n return res", "slug": "process-tasks-using-servers", "post_title": "\ud83d\udc0d {Python} || Heap || O(n+mlogn) || easy and well-explained", "user": "abhi9Rai", "upvotes": 5, "views": 227, "problem_title": "process tasks using servers", "number": 1882, "acceptance": 0.396, "difficulty": "Medium", "__index_level_0__": 26712, "question": "You are given two 0-indexed integer arrays servers and tasks of lengths n and m respectively. servers[i] is the weight of the ith server, and tasks[j] is the time needed to process the jth task in seconds.\nTasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.\nAt second j, the jth task is inserted into the queue (starting with the 0th task being inserted at second 0). As long as there are free servers and the queue is not empty, the task in the front of the queue will be assigned to a free server with the smallest weight, and in case of a tie, it is assigned to a free server with the smallest index.\nIf there are no free servers and the queue is not empty, we wait until a server becomes free and immediately assign the next task. If multiple servers become free at the same time, then multiple tasks from the queue will be assigned in order of insertion following the weight and index priorities above.\nA server that is assigned task j at second t will be free again at second t + tasks[j].\nBuild an array ans of length m, where ans[j] is the index of the server the jth task will be assigned to.\nReturn the array ans.\n Example 1:\nInput: servers = [3,3,2], tasks = [1,2,3,2,1,2]\nOutput: [2,2,0,2,1,2]\nExplanation: Events in chronological order go as follows:\n- At second 0, task 0 is added and processed using server 2 until second 1.\n- At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n- At second 2, task 2 is added and processed using server 0 until second 5.\n- At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n- At second 4, task 4 is added and processed using server 1 until second 5.\n- At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\nExample 2:\nInput: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\nOutput: [1,4,1,4,1,3,2]\nExplanation: Events in chronological order go as follows: \n- At second 0, task 0 is added and processed using server 1 until second 2.\n- At second 1, task 1 is added and processed using server 4 until second 2.\n- At second 2, servers 1 and 4 become free. Task 2 is added and processed using server 1 until second 4. \n- At second 3, task 3 is added and processed using server 4 until second 7.\n- At second 4, server 1 becomes free. Task 4 is added and processed using server 1 until second 9. \n- At second 5, task 5 is added and processed using server 3 until second 7.\n- At second 6, task 6 is added and processed using server 2 until second 7.\n Constraints:\nservers.length == n\ntasks.length == m\n1 <= n, m <= 2 * 105\n1 <= servers[i], tasks[j] <= 2 * 105" }, { "post_href": "https://leetcode.com/problems/minimum-skips-to-arrive-at-meeting-on-time/discuss/1242138/Python3-top-down-dp", "python_solutions": "class Solution:\n def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n if sum(dist)/speed > hoursBefore: return -1 # impossible \n \n @cache\n def fn(i, k): \n \"\"\"Return min time (in distance) of traveling first i roads with k skips.\"\"\"\n if k < 0: return inf # impossible \n if i == 0: return 0 \n return min(ceil((fn(i-1, k) + dist[i-1])/speed) * speed, dist[i-1] + fn(i-1, k-1))\n \n for k in range(len(dist)):\n if fn(len(dist)-1, k) + dist[-1] <= hoursBefore*speed: return k", "slug": "minimum-skips-to-arrive-at-meeting-on-time", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 1, "views": 59, "problem_title": "minimum skips to arrive at meeting on time", "number": 1883, "acceptance": 0.385, "difficulty": "Hard", "__index_level_0__": 26719, "question": "You are given an integer hoursBefore, the number of hours you have to travel to your meeting. To arrive at your meeting, you have to travel through n roads. The road lengths are given as an integer array dist of length n, where dist[i] describes the length of the ith road in kilometers. In addition, you are given an integer speed, which is the speed (in km/h) you will travel at.\nAfter you travel road i, you must rest and wait for the next integer hour before you can begin traveling on the next road. Note that you do not have to rest after traveling the last road because you are already at the meeting.\nFor example, if traveling a road takes 1.4 hours, you must wait until the 2 hour mark before traveling the next road. If traveling a road takes exactly 2 hours, you do not need to wait.\nHowever, you are allowed to skip some rests to be able to arrive on time, meaning you do not need to wait for the next integer hour. Note that this means you may finish traveling future roads at different hour marks.\nFor example, suppose traveling the first road takes 1.4 hours and traveling the second road takes 0.6 hours. Skipping the rest after the first road will mean you finish traveling the second road right at the 2 hour mark, letting you start traveling the third road immediately.\nReturn the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.\n Example 1:\nInput: dist = [1,3,2], speed = 4, hoursBefore = 2\nOutput: 1\nExplanation:\nWithout skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\nYou can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\nNote that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.\nExample 2:\nInput: dist = [7,3,5,5], speed = 2, hoursBefore = 10\nOutput: 2\nExplanation:\nWithout skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\nYou can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.\nExample 3:\nInput: dist = [7,3,5,5], speed = 1, hoursBefore = 10\nOutput: -1\nExplanation: It is impossible to arrive at the meeting on time even if you skip all the rests.\n Constraints:\nn == dist.length\n1 <= n <= 1000\n1 <= dist[i] <= 105\n1 <= speed <= 106\n1 <= hoursBefore <= 107" }, { "post_href": "https://leetcode.com/problems/egg-drop-with-2-eggs-and-n-floors/discuss/1248069/Recursive-Iterative-Generic", "python_solutions": "class Solution:\n @cache\n def twoEggDrop(self, n: int) -> int:\n return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1)", "slug": "egg-drop-with-2-eggs-and-n-floors", "post_title": "Recursive, Iterative, Generic", "user": "votrubac", "upvotes": 194, "views": 11600, "problem_title": "egg drop with 2 eggs and n floors", "number": 1884, "acceptance": 0.703, "difficulty": "Medium", "__index_level_0__": 26720, "question": "You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.\nYou know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\nIn each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\nReturn the minimum number of moves that you need to determine with certainty what the value of f is.\n Example 1:\nInput: n = 2\nOutput: 2\nExplanation: We can drop the first egg from floor 1 and the second egg from floor 2.\nIf the first egg breaks, we know that f = 0.\nIf the second egg breaks but the first egg didn't, we know that f = 1.\nOtherwise, if both eggs survive, we know that f = 2.\nExample 2:\nInput: n = 100\nOutput: 14\nExplanation: One optimal strategy is:\n- Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9.\n- If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14.\n- If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100.\nRegardless of the outcome, it takes at most 14 drops to determine f.\n Constraints:\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/discuss/1253880/Python3-rotate-matrix", "python_solutions": "class Solution:\n def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n for _ in range(4): \n if mat == target: return True\n mat = [list(x) for x in zip(*mat[::-1])]\n return False", "slug": "determine-whether-matrix-can-be-obtained-by-rotation", "post_title": "[Python3] rotate matrix", "user": "ye15", "upvotes": 86, "views": 4800, "problem_title": "determine whether matrix can be obtained by rotation", "number": 1886, "acceptance": 0.5539999999999999, "difficulty": "Easy", "__index_level_0__": 26734, "question": "Given two n x n binary matrices mat and target, return true if it is possible to make mat equal to target by rotating mat in 90-degree increments, or false otherwise.\n Example 1:\nInput: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise to make mat equal target.\nExample 2:\nInput: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\nOutput: false\nExplanation: It is impossible to make mat equal to target by rotating mat.\nExample 3:\nInput: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\nOutput: true\nExplanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.\n Constraints:\nn == mat.length == target.length\nn == mat[i].length == target[i].length\n1 <= n <= 10\nmat[i][j] and target[i][j] are either 0 or 1." }, { "post_href": "https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/discuss/1253889/Python3-greedy", "python_solutions": "class Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n ans = val = 0\n nums.sort()\n for i in range(1, len(nums)): \n if nums[i-1] < nums[i]: val += 1\n ans += val\n return ans", "slug": "reduction-operations-to-make-the-array-elements-equal", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 20, "views": 963, "problem_title": "reduction operations to make the array elements equal", "number": 1887, "acceptance": 0.624, "difficulty": "Medium", "__index_level_0__": 26759, "question": "Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:\nFind the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.\nFind the next largest value in nums strictly smaller than largest. Let its value be nextLargest.\nReduce nums[i] to nextLargest.\nReturn the number of operations to make all elements in nums equal.\n Example 1:\nInput: nums = [5,1,3]\nOutput: 3\nExplanation: It takes 3 operations to make all elements in nums equal:\n1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].\nExample 2:\nInput: nums = [1,1,1]\nOutput: 0\nExplanation: All elements in nums are already equal.\nExample 3:\nInput: nums = [1,1,2,2,3]\nOutput: 4\nExplanation: It takes 4 operations to make all elements in nums equal:\n1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].\n Constraints:\n1 <= nums.length <= 5 * 104\n1 <= nums[i] <= 5 * 104" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-flips-to-make-the-binary-string-alternating/discuss/1259837/Python-Simple-DP-(beats-99.52)", "python_solutions": "class Solution:\n def minFlips(self, s: str) -> int:\n prev = 0\n start_1, start_0, start_1_odd, start_0_odd = 0,0,sys.maxsize,sys.maxsize\n odd = len(s)%2\n for val in s:\n val = int(val)\n if val == prev:\n if odd:\n start_0_odd = min(start_0_odd, start_1)\n start_1_odd += 1\n start_1 += 1\n else:\n if odd:\n start_1_odd = min(start_1_odd, start_0)\n start_0_odd += 1\n start_0 += 1\n prev = 1 - prev\n return min([start_1, start_0, start_1_odd, start_0_odd])", "slug": "minimum-number-of-flips-to-make-the-binary-string-alternating", "post_title": "[Python] Simple DP (beats 99.52%)", "user": "cloverpku", "upvotes": 6, "views": 640, "problem_title": "minimum number of flips to make the binary string alternating", "number": 1888, "acceptance": 0.381, "difficulty": "Medium", "__index_level_0__": 26771, "question": "You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:\nType-1: Remove the character at the start of the string s and append it to the end of the string.\nType-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.\nReturn the minimum number of type-2 operations you need to perform such that s becomes alternating.\nThe string is called alternating if no two adjacent characters are equal.\nFor example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\n Example 1:\nInput: s = \"111000\"\nOutput: 2\nExplanation: Use the first operation two times to make s = \"100011\".\nThen, use the second operation on the third and sixth elements to make s = \"101010\".\nExample 2:\nInput: s = \"010\"\nOutput: 0\nExplanation: The string is already alternating.\nExample 3:\nInput: s = \"1110\"\nOutput: 1\nExplanation: Use the second operation on the second element to make s = \"1010\".\n Constraints:\n1 <= s.length <= 105\ns[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/minimum-space-wasted-from-packaging/discuss/1253918/Python3-prefix-sum-and-binary-search", "python_solutions": "class Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n packages.sort()\n prefix = [0]\n for x in packages: prefix.append(prefix[-1] + x)\n \n ans = inf \n for box in boxes: \n box.sort()\n if packages[-1] <= box[-1]: \n kk = val = 0 \n for x in box: \n k = bisect_right(packages, x)\n val += (k - kk) * x - (prefix[k] - prefix[kk])\n kk = k\n ans = min(ans, val)\n return ans % 1_000_000_007 if ans < inf else -1", "slug": "minimum-space-wasted-from-packaging", "post_title": "[Python3] prefix sum & binary search", "user": "ye15", "upvotes": 5, "views": 330, "problem_title": "minimum space wasted from packaging", "number": 1889, "acceptance": 0.307, "difficulty": "Hard", "__index_level_0__": 26780, "question": "You have n packages that you are trying to place in boxes, one package in each box. There are m suppliers that each produce boxes of different sizes (with infinite supply). A package can be placed in a box if the size of the package is less than or equal to the size of the box.\nThe package sizes are given as an integer array packages, where packages[i] is the size of the ith package. The suppliers are given as a 2D integer array boxes, where boxes[j] is an array of box sizes that the jth supplier produces.\nYou want to choose a single supplier and use boxes from them such that the total wasted space is minimized. For each package in a box, we define the space wasted to be size of the box - size of the package. The total wasted space is the sum of the space wasted in all the boxes.\nFor example, if you have to fit packages with sizes [2,3,5] and the supplier offers boxes of sizes [4,8], you can fit the packages of size-2 and size-3 into two boxes of size-4 and the package with size-5 into a box of size-8. This would result in a waste of (4-2) + (4-3) + (8-5) = 6.\nReturn the minimum total wasted space by choosing the box supplier optimally, or -1 if it is impossible to fit all the packages inside boxes. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\nInput: packages = [2,3,5], boxes = [[4,8],[2,8]]\nOutput: 6\nExplanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\nThe total waste is (4-2) + (4-3) + (8-5) = 6.\nExample 2:\nInput: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\nOutput: -1\nExplanation: There is no box that the package of size 5 can fit in.\nExample 3:\nInput: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\nOutput: 9\nExplanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\nThe total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.\n Constraints:\nn == packages.length\nm == boxes.length\n1 <= n <= 105\n1 <= m <= 105\n1 <= packages[i] <= 105\n1 <= boxes[j].length <= 105\n1 <= boxes[j][k] <= 105\nsum(boxes[j].length) <= 105\nThe elements in boxes[j] are distinct." }, { "post_href": "https://leetcode.com/problems/check-if-all-the-integers-in-a-range-are-covered/discuss/1444310/PYTHON3-Noob-Friendly-Easy-inuitive-naturally-occuring-solution", "python_solutions": "class Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n ranges = sorted(ranges)\n for s,e in ranges:\n if s<=left<=e:\n if s<=right<=e:\n return True\n else:\n left=e+1\n return False", "slug": "check-if-all-the-integers-in-a-range-are-covered", "post_title": "PYTHON3- Noob Friendly Easy inuitive naturally occuring solution", "user": "mathur17021play", "upvotes": 2, "views": 138, "problem_title": "check if all the integers in a range are covered", "number": 1893, "acceptance": 0.508, "difficulty": "Easy", "__index_level_0__": 26783, "question": "You are given a 2D integer array ranges and two integers left and right. Each ranges[i] = [starti, endi] represents an inclusive interval between starti and endi.\nReturn true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.\nAn integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.\n Example 1:\nInput: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\nOutput: true\nExplanation: Every integer between 2 and 5 is covered:\n- 2 is covered by the first range.\n- 3 and 4 are covered by the second range.\n- 5 is covered by the third range.\nExample 2:\nInput: ranges = [[1,10],[10,20]], left = 21, right = 21\nOutput: false\nExplanation: 21 is not covered by any range.\n Constraints:\n1 <= ranges.length <= 50\n1 <= starti <= endi <= 50\n1 <= left <= right <= 50" }, { "post_href": "https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/discuss/1612394/Python-oror-Prefix-Sum-and-Binary-Search-oror-O(n)-time-O(n)-space", "python_solutions": "class Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n prefix_sum = [0 for i in range(len(chalk))]\n prefix_sum[0] = chalk[0]\n for i in range(1,len(chalk)):\n prefix_sum[i] = prefix_sum[i-1] + chalk[i]\n remainder = k % prefix_sum[-1]\n \n #apply binary search on prefix_sum array, target = remainder \n start = 0\n end = len(prefix_sum) - 1\n while start <= end:\n mid = start + (end - start) // 2\n if remainder == prefix_sum[mid]:\n return mid + 1\n elif remainder < prefix_sum[mid]:\n end = mid - 1\n else:\n start = mid + 1\n return start", "slug": "find-the-student-that-will-replace-the-chalk", "post_title": "Python || Prefix Sum and Binary Search || O(n) time O(n) space", "user": "s_m_d_29", "upvotes": 4, "views": 244, "problem_title": "find the student that will replace the chalk", "number": 1894, "acceptance": 0.4379999999999999, "difficulty": "Medium", "__index_level_0__": 26806, "question": "There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.\nYou are given a 0-indexed integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is strictly less than chalk[i], then the student number i will be asked to replace the chalk.\nReturn the index of the student that will replace the chalk pieces.\n Example 1:\nInput: chalk = [5,1,5], k = 22\nOutput: 0\nExplanation: The students go in turns as follows:\n- Student number 0 uses 5 chalk, so k = 17.\n- Student number 1 uses 1 chalk, so k = 16.\n- Student number 2 uses 5 chalk, so k = 11.\n- Student number 0 uses 5 chalk, so k = 6.\n- Student number 1 uses 1 chalk, so k = 5.\n- Student number 2 uses 5 chalk, so k = 0.\nStudent number 0 does not have enough chalk, so they will have to replace it.\nExample 2:\nInput: chalk = [3,4,1,2], k = 25\nOutput: 1\nExplanation: The students go in turns as follows:\n- Student number 0 uses 3 chalk so k = 22.\n- Student number 1 uses 4 chalk so k = 18.\n- Student number 2 uses 1 chalk so k = 17.\n- Student number 3 uses 2 chalk so k = 15.\n- Student number 0 uses 3 chalk so k = 12.\n- Student number 1 uses 4 chalk so k = 8.\n- Student number 2 uses 1 chalk so k = 7.\n- Student number 3 uses 2 chalk so k = 5.\n- Student number 0 uses 3 chalk so k = 2.\nStudent number 1 does not have enough chalk, so they will have to replace it.\n Constraints:\nchalk.length == n\n1 <= n <= 105\n1 <= chalk[i] <= 105\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/largest-magic-square/discuss/1267452/Python3-prefix-sums", "python_solutions": "class Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0]) # dimensions \n rows = [[0]*(n+1) for _ in range(m)] # prefix sum along row\n cols = [[0]*n for _ in range(m+1)] # prefix sum along column\n \n for i in range(m):\n for j in range(n): \n rows[i][j+1] = grid[i][j] + rows[i][j]\n cols[i+1][j] = grid[i][j] + cols[i][j]\n \n ans = 1\n for i in range(m): \n for j in range(n): \n diag = grid[i][j]\n for k in range(min(i, j)): \n ii, jj = i-k-1, j-k-1\n diag += grid[ii][jj]\n ss = {diag}\n for r in range(ii, i+1): ss.add(rows[r][j+1] - rows[r][jj])\n for c in range(jj, j+1): ss.add(cols[i+1][c] - cols[ii][c])\n ss.add(sum(grid[ii+kk][j-kk] for kk in range(k+2))) # anti-diagonal\n if len(ss) == 1: ans = max(ans, k+2)\n return ans", "slug": "largest-magic-square", "post_title": "[Python3] prefix sums", "user": "ye15", "upvotes": 6, "views": 449, "problem_title": "largest magic square", "number": 1895, "acceptance": 0.519, "difficulty": "Medium", "__index_level_0__": 26821, "question": "A k x k magic square is a k x k grid filled with integers such that every row sum, every column sum, and both diagonal sums are all equal. The integers in the magic square do not have to be distinct. Every 1 x 1 grid is trivially a magic square.\nGiven an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.\n Example 1:\nInput: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\nOutput: 3\nExplanation: The largest magic square has a size of 3.\nEvery row sum, column sum, and diagonal sum of this magic square is equal to 12.\n- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n- Diagonal sums: 5+4+3 = 6+4+2 = 12\nExample 2:\nInput: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\nOutput: 2\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 50\n1 <= grid[i][j] <= 106" }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-change-the-final-value-of-expression/discuss/1272620/Python3-divide-and-conquer", "python_solutions": "class Solution:\n def minOperationsToFlip(self, expression: str) -> int:\n loc = {}\n stack = []\n for i in reversed(range(len(expression))):\n if expression[i] == \")\": stack.append(i)\n elif expression[i] == \"(\": loc[stack.pop()] = i \n \n def fn(lo, hi): \n \"\"\"Return value and min op to change value.\"\"\"\n if lo == hi: return int(expression[lo]), 1\n if expression[hi] == \")\" and loc[hi] == lo: return fn(lo+1, hi-1) # strip parenthesis \n mid = loc.get(hi, hi) - 1 \n v, c = fn(mid+1, hi)\n vv, cc = fn(lo, mid-1)\n if expression[mid] == \"|\": \n val = v | vv \n if v == vv == 0: chg = min(c, cc)\n elif v == vv == 1: chg = 1 + min(c, cc)\n else: chg = 1 \n else: # expression[k] == \"&\"\n val = v & vv\n if v == vv == 0: chg = 1 + min(c, cc)\n elif v == vv == 1: chg = min(c, cc)\n else: chg = 1\n return val, chg\n \n return fn(0, len(expression)-1)[1]", "slug": "minimum-cost-to-change-the-final-value-of-expression", "post_title": "[Python3] divide & conquer", "user": "ye15", "upvotes": 0, "views": 57, "problem_title": "minimum cost to change the final value of expression", "number": 1896, "acceptance": 0.5479999999999999, "difficulty": "Hard", "__index_level_0__": 26827, "question": "You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.\nFor example, \"()1|1\" and \"(1)&()\" are not valid while \"1\", \"(((1))|(0))\", and \"1|(0&(1))\" are valid expressions.\nReturn the minimum cost to change the final value of the expression.\nFor example, if expression = \"1|1|(0&0)&1\", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.\nThe cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows:\nTurn a '1' into a '0'.\nTurn a '0' into a '1'.\nTurn a '&' into a '|'.\nTurn a '|' into a '&'.\nNote: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.\n Example 1:\nInput: expression = \"1&(0|1)\"\nOutput: 1\nExplanation: We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\nThe new expression evaluates to 0. \nExample 2:\nInput: expression = \"(0&0)&(0&0&0)\"\nOutput: 3\nExplanation: We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\nThe new expression evaluates to 1.\nExample 3:\nInput: expression = \"(0|(1|0&1))\"\nOutput: 1\nExplanation: We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\nThe new expression evaluates to 0.\n Constraints:\n1 <= expression.length <= 105\nexpression only contains '1','0','&','|','(', and ')'\nAll parentheses are properly matched.\nThere will be no empty parentheses (i.e: \"()\" is not a substring of expression)." }, { "post_href": "https://leetcode.com/problems/redistribute-characters-to-make-all-strings-equal/discuss/1268522/Python-or-dictionary", "python_solutions": "class Solution:\n def makeEqual(self, words: List[str]) -> bool:\n map_ = {}\n for word in words:\n for i in word:\n if i not in map_:\n map_[i] = 1\n else:\n map_[i] += 1\n n = len(words)\n for k,v in map_.items():\n if (v%n) != 0:\n return False\n return True", "slug": "redistribute-characters-to-make-all-strings-equal", "post_title": "Python | dictionary", "user": "harshhx", "upvotes": 14, "views": 1200, "problem_title": "redistribute characters to make all strings equal", "number": 1897, "acceptance": 0.599, "difficulty": "Easy", "__index_level_0__": 26828, "question": "You are given an array of strings words (0-indexed).\nIn one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j].\nReturn true if you can make every string in words equal using any number of operations, and false otherwise.\n Example 1:\nInput: words = [\"abc\",\"aabc\",\"bc\"]\nOutput: true\nExplanation: Move the first 'a' in words[1] to the front of words[2],\nto make words[1] = \"abc\" and words[2] = \"abc\".\nAll the strings are now equal to \"abc\", so return true.\nExample 2:\nInput: words = [\"ab\",\"a\"]\nOutput: false\nExplanation: It is impossible to make all the strings equal using the operation.\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 100\nwords[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-removable-characters/discuss/1268727/Python3-binary-search", "python_solutions": "class Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n mp = {x: i for i, x in enumerate(removable)}\n \n def fn(x):\n \"\"\"Return True if p is a subseq of s after x removals.\"\"\"\n k = 0 \n for i, ch in enumerate(s): \n if mp.get(i, inf) < x: continue \n if k < len(p) and ch == p[k]: k += 1\n return k == len(p)\n \n lo, hi = -1, len(removable)\n while lo < hi: \n mid = lo + hi + 1 >> 1\n if fn(mid): lo = mid\n else: hi = mid - 1\n return lo", "slug": "maximum-number-of-removable-characters", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 10, "views": 467, "problem_title": "maximum number of removable characters", "number": 1898, "acceptance": 0.3929999999999999, "difficulty": "Medium", "__index_level_0__": 26852, "question": "You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed).\nYou want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence.\nReturn the maximum k you can choose such that p is still a subsequence of s after the removals.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\n Example 1:\nInput: s = \"abcacb\", p = \"ab\", removable = [3,1,0]\nOutput: 2\nExplanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n\"ab\" is a subsequence of \"accb\".\nIf we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\nHence, the maximum k is 2.\nExample 2:\nInput: s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]\nOutput: 1\nExplanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n\"abcd\" is a subsequence of \"abcddddd\".\nExample 3:\nInput: s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]\nOutput: 0\nExplanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.\n Constraints:\n1 <= p.length <= s.length <= 105\n0 <= removable.length < s.length\n0 <= removable[i] < s.length\np is a subsequence of s.\ns and p both consist of lowercase English letters.\nThe elements in removable are distinct." }, { "post_href": "https://leetcode.com/problems/merge-triplets-to-form-target-triplet/discuss/1268491/python-or-implementation-O(N)", "python_solutions": "class Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n i = 1\n cur = []\n for a,b,c in triplets:\n if a<=target[0] and b<=target[1] and c<= target[2]:\n cur = [a,b,c]\n break\n if not cur:\n return False\n while i List[int]:\n firstPlayer, secondPlayer = firstPlayer-1, secondPlayer-1 # 0-indexed\n \n @cache\n def fn(k, mask): \n \"\"\"Return earliest and latest rounds.\"\"\"\n can = deque()\n for i in range(n): \n if mask & (1 << i): can.append(i)\n \n cand = [] # eliminated player\n while len(can) > 1: \n p1, p2 = can.popleft(), can.pop()\n if p1 == firstPlayer and p2 == secondPlayer or p1 == secondPlayer and p2 == firstPlayer: return [k, k] # game of interest \n if p1 in (firstPlayer, secondPlayer): cand.append([p2]) # p2 eliminated \n elif p2 in (firstPlayer, secondPlayer): cand.append([p1]) # p1 eliminated \n else: cand.append([p1, p2]) # both could be elimited \n \n minn, maxx = inf, -inf\n for x in product(*cand): \n mask0 = mask\n for i in x: mask0 ^= 1 << i\n mn, mx = fn(k+1, mask0)\n minn = min(minn, mn)\n maxx = max(maxx, mx)\n return minn, maxx\n \n return fn(1, (1< List[int]:\n m, n = len(mat), len(mat[0])\n l, r = 0, n\n while l <= r:\n mid = (l + r) // 2\n cur_max, left = 0, False\n for i in range(m):\n if i > 0 and mat[i-1][mid] >= mat[i][mid]:\n continue\n if i+1 < m and mat[i+1][mid] >= mat[i][mid]: \n continue\n if mid+1 < n and mat[i][mid+1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], not mat[i][mid] > cur_max\n continue\n if mid > 0 and mat[i][mid-1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], mat[i][mid] > cur_max\n continue\n return [i, mid]\n if left:\n r = mid-1\n else:\n l = mid+1\n return []", "slug": "find-a-peak-element-ii", "post_title": "Python 3 | Binary Search | Explanation", "user": "idontknoooo", "upvotes": 17, "views": 2100, "problem_title": "find a peak element ii", "number": 1901, "acceptance": 0.532, "difficulty": "Medium", "__index_level_0__": 26880, "question": "A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom.\nGiven a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j].\nYou may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.\nYou must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.\n Example 1:\nInput: mat = [[1,4],[3,2]]\nOutput: [0,1]\nExplanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.\nExample 2:\nInput: mat = [[10,20,15],[21,30,14],[7,16,32]]\nOutput: [1,1]\nExplanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 500\n1 <= mat[i][j] <= 105\nNo two adjacent cells are equal." }, { "post_href": "https://leetcode.com/problems/largest-odd-number-in-string/discuss/1338138/PYTHON-3%3A-99.34-FASTER-EASY-EXPLANATION", "python_solutions": "class Solution:\n def largestOddNumber(self, num: str) -> str:\n \n for i in range(len(num) - 1, -1, -1) :\n if num[i] in {'1','3','5','7','9'} :\n return num[:i+1]\n return ''", "slug": "largest-odd-number-in-string", "post_title": "PYTHON 3: 99.34% FASTER, EASY EXPLANATION", "user": "rohitkhairnar", "upvotes": 30, "views": 1400, "problem_title": "largest odd number in string", "number": 1903, "acceptance": 0.557, "difficulty": "Easy", "__index_level_0__": 26893, "question": "You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string \"\" if no odd integer exists.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: num = \"52\"\nOutput: \"5\"\nExplanation: The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.\nExample 2:\nInput: num = \"4206\"\nOutput: \"\"\nExplanation: There are no odd numbers in \"4206\".\nExample 3:\nInput: num = \"35427\"\nOutput: \"35427\"\nExplanation: \"35427\" is already an odd number.\n Constraints:\n1 <= num.length <= 105\nnum only consists of digits and does not contain any leading zeros." }, { "post_href": "https://leetcode.com/problems/the-number-of-full-rounds-you-have-played/discuss/1284279/Python3-math-ish", "python_solutions": "class Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(\":\"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(\":\"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96", "slug": "the-number-of-full-rounds-you-have-played", "post_title": "[Python3] math-ish", "user": "ye15", "upvotes": 18, "views": 1300, "problem_title": "the number of full rounds you have played", "number": 1904, "acceptance": 0.456, "difficulty": "Medium", "__index_level_0__": 26928, "question": "You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts.\nFor example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30.\nYou are given two strings loginTime and logoutTime where:\nloginTime is the time you will login to the game, and\nlogoutTime is the time you will logout from the game.\nIf logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime.\nReturn the number of full chess rounds you have played in the tournament.\nNote: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.\n Example 1:\nInput: loginTime = \"09:31\", logoutTime = \"10:14\"\nOutput: 1\nExplanation: You played one full round from 09:45 to 10:00.\nYou did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\nYou did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.\nExample 2:\nInput: loginTime = \"21:30\", logoutTime = \"03:00\"\nOutput: 22\nExplanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n10 + 12 = 22.\n Constraints:\nloginTime and logoutTime are in the format hh:mm.\n00 <= hh <= 23\n00 <= mm <= 59\nloginTime and logoutTime are not equal." }, { "post_href": "https://leetcode.com/problems/count-sub-islands/discuss/1284306/98-faster-oror-Simple-approach-oror-well-explained", "python_solutions": "class Solution:\ndef countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n \n m=len(grid1)\n n=len(grid1[0])\n \n def dfs(i,j):\n if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:\n return\n \n grid2[i][j]=0\n dfs(i+1,j)\n dfs(i,j+1)\n dfs(i,j-1)\n dfs(i-1,j)\n \n # removing all the non-common sub-islands\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1 and grid1[i][j]==0:\n dfs(i,j)\n \n c=0\n\t# counting sub-islands\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1:\n dfs(i,j)\n c+=1\n return c", "slug": "count-sub-islands", "post_title": "\ud83d\udc0d 98% faster || Simple approach || well-explained \ud83d\udccc", "user": "abhi9Rai", "upvotes": 148, "views": 4900, "problem_title": "count sub islands", "number": 1905, "acceptance": 0.677, "difficulty": "Medium", "__index_level_0__": 26937, "question": "You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.\nAn island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.\nReturn the number of islands in grid2 that are considered sub-islands.\n Example 1:\nInput: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]\nOutput: 3\nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.\nExample 2:\nInput: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]\nOutput: 2 \nExplanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\nThe 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.\n Constraints:\nm == grid1.length == grid2.length\nn == grid1[i].length == grid2[i].length\n1 <= m, n <= 500\ngrid1[i][j] and grid2[i][j] are either 0 or 1." }, { "post_href": "https://leetcode.com/problems/minimum-absolute-difference-queries/discuss/1284341/Python3-binary-search", "python_solutions": "class Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n loc = {}\n for i, x in enumerate(nums): loc.setdefault(x, []).append(i)\n keys = sorted(loc)\n \n ans = []\n for l, r in queries: \n prev, val = 0, inf\n for x in keys: \n i = bisect_left(loc[x], l)\n if i < len(loc[x]) and loc[x][i] <= r: \n if prev: val = min(val, x - prev)\n prev = x \n ans.append(val if val < inf else -1)\n return ans", "slug": "minimum-absolute-difference-queries", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 8, "views": 681, "problem_title": "minimum absolute difference queries", "number": 1906, "acceptance": 0.439, "difficulty": "Medium", "__index_level_0__": 26966, "question": "The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.\nFor example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.\nYou are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).\nReturn an array ans where ans[i] is the answer to the ith query.\nA subarray is a contiguous sequence of elements in an array.\nThe value of |x| is defined as:\nx if x >= 0.\n-x if x < 0.\n Example 1:\nInput: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\nOutput: [2,1,4,1]\nExplanation: The queries are processed as follows:\n- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.\nExample 2:\nInput: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\nOutput: [-1,1,1,3]\nExplanation: The queries are processed as follows:\n- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the\n elements are the same.\n- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.\n- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.\n- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.\n Constraints:\n2 <= nums.length <= 105\n1 <= nums[i] <= 100\n1 <= queries.length <= 2 * 104\n0 <= li < ri < nums.length" }, { "post_href": "https://leetcode.com/problems/remove-one-element-to-make-the-array-strictly-increasing/discuss/1298457/Python3-collect-non-conforming-indices", "python_solutions": "class Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n stack = []\n for i in range(1, len(nums)): \n if nums[i-1] >= nums[i]: stack.append(i)\n \n if not stack: return True \n if len(stack) > 1: return False\n i = stack[0]\n return (i == 1 or nums[i-2] < nums[i]) or (i+1 == len(nums) or nums[i-1] < nums[i+1])", "slug": "remove-one-element-to-make-the-array-strictly-increasing", "post_title": "[Python3] collect non-conforming indices", "user": "ye15", "upvotes": 15, "views": 1200, "problem_title": "remove one element to make the array strictly increasing", "number": 1909, "acceptance": 0.26, "difficulty": "Easy", "__index_level_0__": 26967, "question": "Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.\nThe array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).\n Example 1:\nInput: nums = [1,2,10,5,7]\nOutput: true\nExplanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n[1,2,5,7] is strictly increasing, so return true.\nExample 2:\nInput: nums = [2,3,1,2]\nOutput: false\nExplanation:\n[3,1,2] is the result of removing the element at index 0.\n[2,1,2] is the result of removing the element at index 1.\n[2,3,2] is the result of removing the element at index 2.\n[2,3,1] is the result of removing the element at index 3.\nNo resulting array is strictly increasing, so return false.\nExample 3:\nInput: nums = [1,1,1]\nOutput: false\nExplanation: The result of removing any element is [1,1].\n[1,1] is not strictly increasing, so return false.\n Constraints:\n2 <= nums.length <= 1000\n1 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/remove-all-occurrences-of-a-substring/discuss/1298899/Python3-kmp", "python_solutions": "class Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n lps = [0]\n k = 0 \n for i in range(1, len(part)): \n while k and part[k] != part[i]: k = lps[k-1]\n if part[k] == part[i]: k += 1\n lps.append(k)\n \n stack = [(\"\", 0)]\n for ch in s: \n k = stack[-1][1]\n while k and part[k] != ch: k = lps[k-1]\n if part[k] == ch: k += 1\n stack.append((ch, k))\n if k == len(part): \n for _ in range(len(part)): stack.pop()\n return \"\".join(x for x, _ in stack)", "slug": "remove-all-occurrences-of-a-substring", "post_title": "[Python3] kmp", "user": "ye15", "upvotes": 9, "views": 955, "problem_title": "remove all occurrences of a substring", "number": 1910, "acceptance": 0.742, "difficulty": "Medium", "__index_level_0__": 26988, "question": "Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:\nFind the leftmost occurrence of the substring part and remove it from s.\nReturn s after removing all occurrences of part.\nA substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: s = \"daabcbaabcbc\", part = \"abc\"\nOutput: \"dab\"\nExplanation: The following operations are done:\n- s = \"daabcbaabcbc\", remove \"abc\" starting at index 2, so s = \"dabaabcbc\".\n- s = \"dabaabcbc\", remove \"abc\" starting at index 4, so s = \"dababc\".\n- s = \"dababc\", remove \"abc\" starting at index 3, so s = \"dab\".\nNow s has no occurrences of \"abc\".\nExample 2:\nInput: s = \"axxxxyyyyb\", part = \"xy\"\nOutput: \"ab\"\nExplanation: The following operations are done:\n- s = \"axxxxyyyyb\", remove \"xy\" starting at index 4 so s = \"axxxyyyb\".\n- s = \"axxxyyyb\", remove \"xy\" starting at index 3 so s = \"axxyyb\".\n- s = \"axxyyb\", remove \"xy\" starting at index 2 so s = \"axyb\".\n- s = \"axyb\", remove \"xy\" starting at index 1 so s = \"ab\".\nNow s has no occurrences of \"xy\".\n Constraints:\n1 <= s.length <= 1000\n1 <= part.length <= 1000\ns and part consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-alternating-subsequence-sum/discuss/1298531/4-lines-oror-96-faster-oror-Easy-approach", "python_solutions": "class Solution:\ndef maxAlternatingSum(self, nums: List[int]) -> int:\n \n ma=0\n mi=0\n for num in nums:\n ma=max(ma,num-mi)\n mi=min(mi,num-ma)\n \n return ma", "slug": "maximum-alternating-subsequence-sum", "post_title": "\ud83d\udccc 4 lines || 96% faster || Easy-approach \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 7, "views": 358, "problem_title": "maximum alternating subsequence sum", "number": 1911, "acceptance": 0.593, "difficulty": "Medium", "__index_level_0__": 27014, "question": "The alternating sum of a 0-indexed array is defined as the sum of the elements at even indices minus the sum of the elements at odd indices.\nFor example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.\nGiven an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).\nA subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\n Example 1:\nInput: nums = [4,2,5,3]\nOutput: 7\nExplanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.\nExample 2:\nInput: nums = [5,6,7,8]\nOutput: 8\nExplanation: It is optimal to choose the subsequence [8] with alternating sum 8.\nExample 3:\nInput: nums = [6,2,1,2,4,5]\nOutput: 10\nExplanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-product-difference-between-two-pairs/discuss/2822079/Python-oror-96.20-Faster-oror-2-Lines-oror-Sorting", "python_solutions": "class Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n nums.sort()\n return (nums[-1]*nums[-2])-(nums[0]*nums[1])", "slug": "maximum-product-difference-between-two-pairs", "post_title": "Python || 96.20% Faster || 2 Lines || Sorting", "user": "DareDevil_007", "upvotes": 1, "views": 44, "problem_title": "maximum product difference between two pairs", "number": 1913, "acceptance": 0.8140000000000001, "difficulty": "Easy", "__index_level_0__": 27027, "question": "The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).\nFor example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.\nGiven an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.\nReturn the maximum such product difference.\n Example 1:\nInput: nums = [5,6,2,7,4]\nOutput: 34\nExplanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\nThe product difference is (6 * 7) - (2 * 4) = 34.\nExample 2:\nInput: nums = [4,2,5,9,7,4,8]\nOutput: 64\nExplanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\nThe product difference is (9 * 8) - (2 * 4) = 64.\n Constraints:\n4 <= nums.length <= 104\n1 <= nums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/cyclically-rotating-a-grid/discuss/1299526/Python3-brute-force", "python_solutions": "class Solution:\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0]) # dimensions \n \n for r in range(min(m, n)//2): \n i = j = r\n vals = []\n for jj in range(j, n-j-1): vals.append(grid[i][jj])\n for ii in range(i, m-i-1): vals.append(grid[ii][n-j-1])\n for jj in range(n-j-1, j, -1): vals.append(grid[m-i-1][jj])\n for ii in range(m-i-1, i, -1): vals.append(grid[ii][j])\n \n kk = k % len(vals)\n vals = vals[kk:] + vals[:kk]\n \n x = 0 \n for jj in range(j, n-j-1): grid[i][jj] = vals[x]; x += 1\n for ii in range(i, m-i-1): grid[ii][n-j-1] = vals[x]; x += 1\n for jj in range(n-j-1, j, -1): grid[m-i-1][jj] = vals[x]; x += 1\n for ii in range(m-i-1, i, -1): grid[ii][j] = vals[x]; x += 1\n return grid", "slug": "cyclically-rotating-a-grid", "post_title": "[Python3] brute-force", "user": "ye15", "upvotes": 24, "views": 988, "problem_title": "cyclically rotating a grid", "number": 1914, "acceptance": 0.481, "difficulty": "Medium", "__index_level_0__": 27068, "question": "You are given an m x n integer matrix grid, where m and n are both even integers, and an integer k.\nThe matrix is composed of several layers, which is shown in the below image, where each color is its own layer:\nA cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below:\nReturn the matrix after applying k cyclic rotations to it.\n Example 1:\nInput: grid = [[40,10],[30,20]], k = 1\nOutput: [[10,20],[40,30]]\nExplanation: The figures above represent the grid at every state.\nExample 2:\nInput: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\nOutput: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\nExplanation: The figures above represent the grid at every state.\n Constraints:\nm == grid.length\nn == grid[i].length\n2 <= m, n <= 50\nBoth m and n are even integers.\n1 <= grid[i][j] <= 5000\n1 <= k <= 109" }, { "post_href": "https://leetcode.com/problems/number-of-wonderful-substrings/discuss/1299537/Python3-freq-table-w.-mask", "python_solutions": "class Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n ans = mask = 0\n freq = defaultdict(int, {0: 1})\n for ch in word: \n mask ^= 1 << ord(ch)-97\n ans += freq[mask]\n for i in range(10): ans += freq[mask ^ 1 << i]\n freq[mask] += 1\n return ans", "slug": "number-of-wonderful-substrings", "post_title": "[Python3] freq table w. mask", "user": "ye15", "upvotes": 11, "views": 678, "problem_title": "number of wonderful substrings", "number": 1915, "acceptance": 0.45, "difficulty": "Medium", "__index_level_0__": 27076, "question": "A wonderful string is a string where at most one letter appears an odd number of times.\nFor example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not.\nGiven a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately.\nA substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: word = \"aba\"\nOutput: 4\nExplanation: The four wonderful substrings are underlined below:\n- \"aba\" -> \"a\"\n- \"aba\" -> \"b\"\n- \"aba\" -> \"a\"\n- \"aba\" -> \"aba\"\nExample 2:\nInput: word = \"aabb\"\nOutput: 9\nExplanation: The nine wonderful substrings are underlined below:\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"aa\"\n- \"aabb\" -> \"aab\"\n- \"aabb\" -> \"aabb\"\n- \"aabb\" -> \"a\"\n- \"aabb\" -> \"abb\"\n- \"aabb\" -> \"b\"\n- \"aabb\" -> \"bb\"\n- \"aabb\" -> \"b\"\nExample 3:\nInput: word = \"he\"\nOutput: 2\nExplanation: The two wonderful substrings are underlined below:\n- \"he\" -> \"h\"\n- \"he\" -> \"e\"\n Constraints:\n1 <= word.length <= 105\nword consists of lowercase English letters from 'a' to 'j'." }, { "post_href": "https://leetcode.com/problems/count-ways-to-build-rooms-in-an-ant-colony/discuss/1299545/Python3-post-order-dfs", "python_solutions": "class Solution:\n def waysToBuildRooms(self, prevRoom: List[int]) -> int:\n tree = defaultdict(list)\n for i, x in enumerate(prevRoom): tree[x].append(i)\n \n def fn(n): \n \"\"\"Return number of nodes and ways to build sub-tree.\"\"\"\n if not tree[n]: return 1, 1 # leaf \n c, m = 0, 1\n for nn in tree[n]: \n cc, mm = fn(nn)\n c += cc\n m = (m * comb(c, cc) * mm) % 1_000_000_007\n return c+1, m\n \n return fn(0)[1]", "slug": "count-ways-to-build-rooms-in-an-ant-colony", "post_title": "[Python3] post-order dfs", "user": "ye15", "upvotes": 8, "views": 762, "problem_title": "count ways to build rooms in an ant colony", "number": 1916, "acceptance": 0.493, "difficulty": "Hard", "__index_level_0__": 27079, "question": "You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly. Room 0 is already built, so prevRoom[0] = -1. The expansion plan is given such that once all the rooms are built, every room will be reachable from room 0.\nYou can only build one room at a time, and you can travel freely between rooms you have already built only if they are connected. You can choose to build any room as long as its previous room is already built.\nReturn the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\nInput: prevRoom = [-1,0,1]\nOutput: 1\nExplanation: There is only one way to build the additional rooms: 0 \u2192 1 \u2192 2\nExample 2:\nInput: prevRoom = [-1,0,0,1,2]\nOutput: 6\nExplanation:\nThe 6 ways are:\n0 \u2192 1 \u2192 3 \u2192 2 \u2192 4\n0 \u2192 2 \u2192 4 \u2192 1 \u2192 3\n0 \u2192 1 \u2192 2 \u2192 3 \u2192 4\n0 \u2192 1 \u2192 2 \u2192 4 \u2192 3\n0 \u2192 2 \u2192 1 \u2192 3 \u2192 4\n0 \u2192 2 \u2192 1 \u2192 4 \u2192 3\n Constraints:\nn == prevRoom.length\n2 <= n <= 105\nprevRoom[0] == -1\n0 <= prevRoom[i] < n for all 1 <= i < n\nEvery room is reachable from room 0 once all the rooms are built." }, { "post_href": "https://leetcode.com/problems/build-array-from-permutation/discuss/1314345/Python3-1-line", "python_solutions": "class Solution:\n def buildArray(self, nums: List[int]) -> List[int]:\n return [nums[nums[i]] for i in range(len(nums))]", "slug": "build-array-from-permutation", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 11, "views": 1800, "problem_title": "build array from permutation", "number": 1920, "acceptance": 0.912, "difficulty": "Easy", "__index_level_0__": 27080, "question": "Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it.\nA zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).\n Example 1:\nInput: nums = [0,2,1,5,3,4]\nOutput: [0,1,2,4,5,3]\nExplanation: The array ans is built as follows: \nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]\n = [0,1,2,4,5,3]\nExample 2:\nInput: nums = [5,0,1,2,3,4]\nOutput: [4,5,0,1,2,3]\nExplanation: The array ans is built as follows:\nans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]\n = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]\n = [4,5,0,1,2,3]\n Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] < nums.length\nThe elements in nums are distinct.\n Follow-up: Can you solve it without using an extra space (i.e., O(1) memory)?" }, { "post_href": "https://leetcode.com/problems/eliminate-maximum-number-of-monsters/discuss/1314370/Python3-3-line", "python_solutions": "class Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n for i, t in enumerate(sorted((d+s-1)//s for d, s in zip(dist, speed))): \n if i == t: return i\n return len(dist)", "slug": "eliminate-maximum-number-of-monsters", "post_title": "[Python3] 3-line", "user": "ye15", "upvotes": 4, "views": 312, "problem_title": "eliminate maximum number of monsters", "number": 1921, "acceptance": 0.379, "difficulty": "Medium", "__index_level_0__": 27128, "question": "You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city.\nThe monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute.\nYou have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge. The weapon is fully charged at the very start.\nYou lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon.\nReturn the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.\n Example 1:\nInput: dist = [1,3,4], speed = [1,1,1]\nOutput: 3\nExplanation:\nIn the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\nAfter a minute, the distances of the monsters are [X,X,2]. You eliminate the third monster.\nAll 3 monsters can be eliminated.\nExample 2:\nInput: dist = [1,1,2,3], speed = [1,1,1,1]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,1,2], so you lose.\nYou can only eliminate 1 monster.\nExample 3:\nInput: dist = [3,2,4], speed = [5,3,2]\nOutput: 1\nExplanation:\nIn the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\nAfter a minute, the distances of the monsters are [X,0,2], so you lose.\nYou can only eliminate 1 monster.\n Constraints:\nn == dist.length == speed.length\n1 <= n <= 105\n1 <= dist[i], speed[i] <= 105" }, { "post_href": "https://leetcode.com/problems/count-good-numbers/discuss/1314484/Python3-Powermod-hack-3-lines", "python_solutions": "class Solution:\n def countGoodNumbers(self, n: int) -> int:\n '''\n ans=1\n MOD=int(10**9+7)\n for i in range(n):\n if i%2==0:\n ans*=5\n else:\n ans*=4\n ans%=MOD\n return ans\n '''\n MOD=int(10**9+7)\n\n fives,fours=n//2+n%2,n//2\n # 5^fives*4^fours % MOD\n # = 5^fives % MOD * 4^fours % MOD\n return (pow(5,fives,MOD) * pow(4,fours,MOD)) % MOD", "slug": "count-good-numbers", "post_title": "[Python3] Powermod hack, 3 lines", "user": "mikeyliu", "upvotes": 5, "views": 396, "problem_title": "count good numbers", "number": 1922, "acceptance": 0.384, "difficulty": "Medium", "__index_level_0__": 27137, "question": "A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7).\nFor example, \"2582\" is good because the digits (2 and 8) at even positions are even and the digits (5 and 2) at odd positions are prime. However, \"3245\" is not good because 3 is at an even index but is not even.\nGiven an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7.\nA digit string is a string consisting of digits 0 through 9 that may contain leading zeros.\n Example 1:\nInput: n = 1\nOutput: 5\nExplanation: The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".\nExample 2:\nInput: n = 4\nOutput: 400\nExample 3:\nInput: n = 50\nOutput: 564908303\n Constraints:\n1 <= n <= 1015" }, { "post_href": "https://leetcode.com/problems/count-square-sum-triples/discuss/2318104/Easy-Solution-oror-PYTHON", "python_solutions": "```class Solution:\n def countTriples(self, n: int) -> int:\n count = 0\n sqrt = 0\n for i in range(1,n-1):\n for j in range(i+1, n):\n sqrt = ((i*i) + (j*j)) ** 0.5\n if sqrt % 1 == 0 and sqrt <= n:\n count += 2\n return (count)\n\t\t\n\n*Please Upvote if you like*", "slug": "count-square-sum-triples", "post_title": "Easy Solution || PYTHON", "user": "Jonny69", "upvotes": 2, "views": 134, "problem_title": "count square sum triples", "number": 1925, "acceptance": 0.68, "difficulty": "Easy", "__index_level_0__": 27145, "question": "A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.\nGiven an integer n, return the number of square triples such that 1 <= a, b, c <= n.\n Example 1:\nInput: n = 5\nOutput: 2\nExplanation: The square triples are (3,4,5) and (4,3,5).\nExample 2:\nInput: n = 10\nOutput: 4\nExplanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).\n Constraints:\n1 <= n <= 250" }, { "post_href": "https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/discuss/1329534/Python-3-or-BFS-Deque-In-place-or-Explanation", "python_solutions": "class Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n q = collections.deque([(*entrance, 0)])\n m, n = len(maze), len(maze[0])\n maze[entrance[0]][entrance[1]] == '+' \n while q:\n x, y, c = q.popleft()\n if (x == 0 or x == m-1 or y == 0 or y == n-1) and [x, y] != entrance:\n return c\n for i, j in [(x+_x, y+_y) for _x, _y in [(-1, 0), (1, 0), (0, -1), (0, 1)]]:\n if 0 <= i < m and 0 <= j < n and maze[i][j] == '.':\n maze[i][j] = '+'\n q.append((i, j, c + 1))\n return -1", "slug": "nearest-exit-from-entrance-in-maze", "post_title": "Python 3 | BFS, Deque, In-place | Explanation", "user": "idontknoooo", "upvotes": 5, "views": 197, "problem_title": "nearest exit from entrance in maze", "number": 1926, "acceptance": 0.49, "difficulty": "Medium", "__index_level_0__": 27157, "question": "You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.\nIn one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.\nReturn the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.\n Example 1:\nInput: maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\nOutput: 1\nExplanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\nInitially, you are at the entrance cell [1,2].\n- You can reach [1,0] by moving 2 steps left.\n- You can reach [0,2] by moving 1 step up.\nIt is impossible to reach [2,3] from the entrance.\nThus, the nearest exit is [0,2], which is 1 step away.\nExample 2:\nInput: maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\nOutput: 2\nExplanation: There is 1 exit in this maze at [1,2].\n[1,0] does not count as an exit since it is the entrance cell.\nInitially, you are at the entrance cell [1,0].\n- You can reach [1,2] by moving 2 steps right.\nThus, the nearest exit is [1,2], which is 2 steps away.\nExample 3:\nInput: maze = [[\".\",\"+\"]], entrance = [0,0]\nOutput: -1\nExplanation: There are no exits in this maze.\n Constraints:\nmaze.length == m\nmaze[i].length == n\n1 <= m, n <= 100\nmaze[i][j] is either '.' or '+'.\nentrance.length == 2\n0 <= entrancerow < m\n0 <= entrancecol < n\nentrance will always be an empty cell." }, { "post_href": "https://leetcode.com/problems/sum-game/discuss/1330360/Python-3-or-Simple-Math-or-Explanation", "python_solutions": "class Solution:\n def sumGame(self, num: str) -> bool:\n n = len(num)\n q_cnt_1 = s1 = 0\n for i in range(n//2): # get digit sum and question mark count for the first half of `num`\n if num[i] == '?':\n q_cnt_1 += 1\n else: \n s1 += int(num[i])\n q_cnt_2 = s2 = 0\t\t\t\t\n for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`\n if num[i] == '?':\n q_cnt_2 += 1\n else: \n s2 += int(num[i])\n s_diff = s1 - s2 # calculate sum difference and question mark difference\n q_diff = q_cnt_2 - q_cnt_1\n return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can't win, Alice wins", "slug": "sum-game", "post_title": "Python 3 | Simple Math | Explanation", "user": "idontknoooo", "upvotes": 16, "views": 396, "problem_title": "sum game", "number": 1927, "acceptance": 0.469, "difficulty": "Medium", "__index_level_0__": 27202, "question": "Alice and Bob take turns playing a game, with Alice starting first.\nYou are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:\nChoose an index i where num[i] == '?'.\nReplace num[i] with any digit between '0' and '9'.\nThe game ends when there are no more '?' characters in num.\nFor Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.\nFor example, if the game ended with num = \"243801\", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = \"243803\", then Alice wins because 2+4+3 != 8+0+3.\nAssuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.\n Example 1:\nInput: num = \"5023\"\nOutput: false\nExplanation: There are no moves to be made.\nThe sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.\nExample 2:\nInput: num = \"25??\"\nOutput: true\nExplanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.\nExample 3:\nInput: num = \"?3295???\"\nOutput: false\nExplanation: It can be proven that Bob will always win. One possible outcome is:\n- Alice replaces the first '?' with '9'. num = \"93295???\".\n- Bob replaces one of the '?' in the right half with '9'. num = \"932959??\".\n- Alice replaces one of the '?' in the right half with '2'. num = \"9329592?\".\n- Bob replaces the last '?' in the right half with '7'. num = \"93295927\".\nBob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.\n Constraints:\n2 <= num.length <= 105\nnum.length is even.\nnum consists of only digits and '?'." }, { "post_href": "https://leetcode.com/problems/minimum-cost-to-reach-destination-in-time/discuss/2841255/Python-Dijkstra's-Algorithm%3A-36-time-8-space", "python_solutions": "class Solution:\n def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:\n n = len(passingFees)\n mat = {}\n for x, y, time in edges:\n if x not in mat: mat[x] = set()\n if y not in mat: mat[y] = set()\n mat[x].add((y, time))\n mat[y].add((x, time))\n\n h = [(passingFees[0], 0, 0)]\n visited = set()\n while h:\n fees, time_so_far, city = heappop(h)\n if time_so_far > maxTime: continue\n if city == n - 1: return fees\n\n if (city, time_so_far) in visited: continue\n visited.add((city, time_so_far))\n \n for nxt, time_to_travel in mat[city]:\n # Check if we are retracing a visited path\n if (nxt, time_so_far - time_to_travel) in visited: continue\n heappush(h, (fees + passingFees[nxt], time_so_far + time_to_travel, nxt))\n return -1", "slug": "minimum-cost-to-reach-destination-in-time", "post_title": "Python Dijkstra's Algorithm: 36% time, 8% space", "user": "hqz3", "upvotes": 0, "views": 2, "problem_title": "minimum cost to reach destination in time", "number": 1928, "acceptance": 0.374, "difficulty": "Hard", "__index_level_0__": 27204, "question": "There is a country of n cities numbered from 0 to n - 1 where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array edges where edges[i] = [xi, yi, timei] denotes a road between cities xi and yi that takes timei minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.\nEach time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array passingFees of length n where passingFees[j] is the amount of dollars you must pay when you pass through city j.\nIn the beginning, you are at city 0 and want to reach city n - 1 in maxTime minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities).\nGiven maxTime, edges, and passingFees, return the minimum cost to complete your journey, or -1 if you cannot complete it within maxTime minutes.\n Example 1:\nInput: maxTime = 30, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: 11\nExplanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.\nExample 2:\nInput: maxTime = 29, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: 48\nExplanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\nYou cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.\nExample 3:\nInput: maxTime = 25, edges = [[0,1,10],[1,2,10],[2,5,10],[0,3,1],[3,4,10],[4,5,15]], passingFees = [5,1,2,20,20,3]\nOutput: -1\nExplanation: There is no way to reach city 5 from city 0 within 25 minutes.\n Constraints:\n1 <= maxTime <= 1000\nn == passingFees.length\n2 <= n <= 1000\nn - 1 <= edges.length <= 1000\n0 <= xi, yi <= n - 1\n1 <= timei <= 1000\n1 <= passingFees[j] <= 1000 \nThe graph may contain multiple edges between two nodes.\nThe graph does not contain self loops." }, { "post_href": "https://leetcode.com/problems/concatenation-of-array/discuss/2044719/Easy-Python-two-liner-code", "python_solutions": "class Solution:\n def getConcatenation(self, nums: List[int]) -> List[int]:\n nums.extend(nums)\n return nums", "slug": "concatenation-of-array", "post_title": "Easy Python two liner code", "user": "Shivam_Raj_Sharma", "upvotes": 10, "views": 743, "problem_title": "concatenation of array", "number": 1929, "acceptance": 0.912, "difficulty": "Easy", "__index_level_0__": 27207, "question": "Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).\nSpecifically, ans is the concatenation of two nums arrays.\nReturn the array ans.\n Example 1:\nInput: nums = [1,2,1]\nOutput: [1,2,1,1,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n- ans = [1,2,1,1,2,1]\nExample 2:\nInput: nums = [1,3,2,1]\nOutput: [1,3,2,1,1,3,2,1]\nExplanation: The array ans is formed as follows:\n- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]\n- ans = [1,3,2,1,1,3,2,1]\n Constraints:\nn == nums.length\n1 <= n <= 1000\n1 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/unique-length-3-palindromic-subsequences/discuss/1330186/easy-python-solution", "python_solutions": "class Solution(object):\n def countPalindromicSubsequence(self, s):\n d=defaultdict(list)\n for i,c in enumerate(s):\n d[c].append(i)\n ans=0\n for el in d:\n if len(d[el])<2:\n continue\n a=d[el][0]\n b=d[el][-1]\n ans+=len(set(s[a+1:b]))\n return(ans)", "slug": "unique-length-3-palindromic-subsequences", "post_title": "easy python solution", "user": "aayush_chhabra", "upvotes": 32, "views": 1100, "problem_title": "unique length 3 palindromic subsequences", "number": 1930, "acceptance": 0.515, "difficulty": "Medium", "__index_level_0__": 27274, "question": "Given a string s, return the number of unique palindromes of length three that are a subsequence of s.\nNote that even if there are multiple ways to obtain the same subsequence, it is still only counted once.\nA palindrome is a string that reads the same forwards and backwards.\nA subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.\nFor example, \"ace\" is a subsequence of \"abcde\".\n Example 1:\nInput: s = \"aabca\"\nOutput: 3\nExplanation: The 3 palindromic subsequences of length 3 are:\n- \"aba\" (subsequence of \"aabca\")\n- \"aaa\" (subsequence of \"aabca\")\n- \"aca\" (subsequence of \"aabca\")\nExample 2:\nInput: s = \"adc\"\nOutput: 0\nExplanation: There are no palindromic subsequences of length 3 in \"adc\".\nExample 3:\nInput: s = \"bbcbaba\"\nOutput: 4\nExplanation: The 4 palindromic subsequences of length 3 are:\n- \"bbb\" (subsequence of \"bbcbaba\")\n- \"bcb\" (subsequence of \"bbcbaba\")\n- \"bab\" (subsequence of \"bbcbaba\")\n- \"aba\" (subsequence of \"bbcbaba\")\n Constraints:\n3 <= s.length <= 105\ns consists of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/1338695/Python3-top-down-dp", "python_solutions": "class Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n \n @cache\n def fn(i, j, mask): \n \"\"\"Return number of ways to color grid.\"\"\"\n if j == n: return 1 \n if i == m: return fn(0, j+1, mask)\n ans = 0 \n for x in 1<<2*i, 1<<2*i+1, 0b11<<2*i: \n mask0 = mask ^ x\n if mask0 & 0b11<<2*i and (i == 0 or (mask0 >> 2*i) & 0b11 != (mask0 >> 2*i-2) & 0b11): \n ans += fn(i+1, j, mask0)\n return ans % 1_000_000_007\n \n return fn(0, 0, 0)", "slug": "painting-a-grid-with-three-different-colors", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 1, "views": 263, "problem_title": "painting a grid with three different colors", "number": 1931, "acceptance": 0.57, "difficulty": "Hard", "__index_level_0__": 27285, "question": "You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.\nReturn the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.\n Example 1:\nInput: m = 1, n = 1\nOutput: 3\nExplanation: The three possible colorings are shown in the image above.\nExample 2:\nInput: m = 1, n = 2\nOutput: 6\nExplanation: The six possible colorings are shown in the image above.\nExample 3:\nInput: m = 5, n = 5\nOutput: 580986\n Constraints:\n1 <= m <= 5\n1 <= n <= 1000" }, { "post_href": "https://leetcode.com/problems/merge-bsts-to-create-single-bst/discuss/1410066/Python3-Recursive-tree-building-solution", "python_solutions": "class Solution:\n def canMerge(self, trees: List[TreeNode]) -> TreeNode:\n roots, leaves, loners, n = {}, {}, set(), len(trees)\n if n == 1:\n return trees[0]\n for tree in trees:\n if not tree.left and not tree.right:\n loners.add(tree.val)\n continue\n roots[tree.val] = tree\n for node in [tree.left, tree.right]:\n if node:\n if node.val in leaves:\n return None\n leaves[node.val] = node\n \n for loner in loners:\n if loner not in leaves and loner not in roots:\n return None\n \n orphan = None\n for val, tree in roots.items():\n if val not in leaves:\n if orphan:\n return None\n orphan = tree\n if not orphan:\n return None\n \n def build(node, small, big):\n nonlocal roots\n if not node:\n return True\n if small >= node.val or node.val >= big:\n return False\n \n if node.val in roots:\n node.left, node.right = roots[node.val].left, roots[node.val].right\n del roots[node.val]\n return build(node.left, small, node.val) and build(node.right, node.val, big)\n del roots[orphan.val]\n result = build(orphan.left, -inf, orphan.val) and build(orphan.right, orphan.val, inf)\n return orphan if result and not roots.keys() else None", "slug": "merge-bsts-to-create-single-bst", "post_title": "Python3 Recursive tree building solution", "user": "yiseboge", "upvotes": 0, "views": 134, "problem_title": "merge bsts to create single bst", "number": 1932, "acceptance": 0.353, "difficulty": "Hard", "__index_level_0__": 27287, "question": "You are given n BST (binary search tree) root nodes for n separate BSTs stored in an array trees (0-indexed). Each BST in trees has at most 3 nodes, and no two roots have the same value. In one operation, you can:\nSelect two distinct indices i and j such that the value stored at one of the leaves of trees[i] is equal to the root value of trees[j].\nReplace the leaf node in trees[i] with trees[j].\nRemove trees[j] from trees.\nReturn the root of the resulting BST if it is possible to form a valid BST after performing n - 1 operations, or null if it is impossible to create a valid BST.\nA BST (binary search tree) is a binary tree where each node satisfies the following property:\nEvery node in the node's left subtree has a value strictly less than the node's value.\nEvery node in the node's right subtree has a value strictly greater than the node's value.\nA leaf is a node that has no children.\n Example 1:\nInput: trees = [[2,1],[3,2,5],[5,4]]\nOutput: [3,2,5,1,null,4]\nExplanation:\nIn the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\nDelete trees[0], so trees = [[3,2,5,1],[5,4]].\nIn the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[3,2,5,1,null,4]].\nThe resulting tree, shown above, is a valid BST, so return its root.\nExample 2:\nInput: trees = [[5,3,8],[3,2,6]]\nOutput: []\nExplanation:\nPick i=0 and j=1 and merge trees[1] into trees[0].\nDelete trees[1], so trees = [[5,3,8,2,6]].\nThe resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.\nExample 3:\nInput: trees = [[5,4],[3]]\nOutput: []\nExplanation: It is impossible to perform any operations.\n Constraints:\nn == trees.length\n1 <= n <= 5 * 104\nThe number of nodes in each tree is in the range [1, 3].\nEach node in the input may have children but no grandchildren.\nNo two roots of trees have the same value.\nAll the trees in the input are valid BSTs.\n1 <= TreeNode.val <= 5 * 104." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-words-you-can-type/discuss/1355349/Easy-Fast-Python-Solutions-(2-Approaches-28ms-32ms-Faster-than-93)", "python_solutions": "class Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n text = text.split()\n length = len(text)\n brokenLetters = set(brokenLetters)\n\n for word in text:\n for char in word:\n if char in brokenLetters:\n length -= 1\n break\n\t\t\t\t\t\n return length", "slug": "maximum-number-of-words-you-can-type", "post_title": "Easy, Fast Python Solutions (2 Approaches - 28ms, 32ms; Faster than 93%)", "user": "the_sky_high", "upvotes": 10, "views": 624, "problem_title": "maximum number of words you can type", "number": 1935, "acceptance": 0.71, "difficulty": "Easy", "__index_level_0__": 27288, "question": "There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.\nGiven a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.\n Example 1:\nInput: text = \"hello world\", brokenLetters = \"ad\"\nOutput: 1\nExplanation: We cannot type \"world\" because the 'd' key is broken.\nExample 2:\nInput: text = \"leet code\", brokenLetters = \"lt\"\nOutput: 1\nExplanation: We cannot type \"leet\" because the 'l' and 't' keys are broken.\nExample 3:\nInput: text = \"leet code\", brokenLetters = \"e\"\nOutput: 0\nExplanation: We cannot type either word because the 'e' key is broken.\n Constraints:\n1 <= text.length <= 104\n0 <= brokenLetters.length <= 26\ntext consists of words separated by a single space without any leading or trailing spaces.\nEach word only consists of lowercase English letters.\nbrokenLetters consists of distinct lowercase English letters." }, { "post_href": "https://leetcode.com/problems/add-minimum-number-of-rungs/discuss/1344878/Divide-gaps-by-dist", "python_solutions": "class Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n return sum((a - b - 1) // dist for a, b in zip(rungs, [0] + rungs))", "slug": "add-minimum-number-of-rungs", "post_title": "Divide gaps by dist", "user": "votrubac", "upvotes": 37, "views": 1800, "problem_title": "add minimum number of rungs", "number": 1936, "acceptance": 0.429, "difficulty": "Medium", "__index_level_0__": 27323, "question": "You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung.\nYou are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there.\nReturn the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.\n Example 1:\nInput: rungs = [1,3,5,10], dist = 2\nOutput: 2\nExplanation:\nYou currently cannot reach the last rung.\nAdd rungs at heights 7 and 8 to climb this ladder. \nThe ladder will now have rungs at [1,3,5,7,8,10].\nExample 2:\nInput: rungs = [3,6,8,10], dist = 3\nOutput: 0\nExplanation:\nThis ladder can be climbed without adding additional rungs.\nExample 3:\nInput: rungs = [3,4,6,7], dist = 2\nOutput: 1\nExplanation:\nYou currently cannot reach the first rung from the ground.\nAdd a rung at height 1 to climb this ladder.\nThe ladder will now have rungs at [1,3,4,6,7].\n Constraints:\n1 <= rungs.length <= 105\n1 <= rungs[i] <= 109\n1 <= dist <= 109\nrungs is strictly increasing." }, { "post_href": "https://leetcode.com/problems/maximum-number-of-points-with-cost/discuss/2119013/Python%3A-Dynamic-Programming-O(mn)-Solution", "python_solutions": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n m, n = len(points), len(points[0])\n \n dp = points[0]\n \n left = [0] * n ## left side contribution\n right = [0] * n ## right side contribution\n \n for r in range(1, m):\n for c in range(n):\n if c == 0:\n left[c] = dp[c]\n else:\n left[c] = max(left[c - 1] - 1, dp[c])\n \n for c in range(n - 1, -1, -1):\n if c == n-1:\n right[c] = dp[c]\n else:\n right[c] = max(right[c + 1] - 1, dp[c])\n \n for c in range(n):\n dp[c] = points[r][c] + max(left[c], right[c])\n \n return max(dp)", "slug": "maximum-number-of-points-with-cost", "post_title": "Python: Dynamic Programming O(mn) Solution", "user": "dadhania", "upvotes": 14, "views": 784, "problem_title": "maximum number of points with cost", "number": 1937, "acceptance": 0.362, "difficulty": "Medium", "__index_level_0__": 27340, "question": "You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix.\nTo gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score.\nHowever, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score.\nReturn the maximum number of points you can achieve.\nabs(x) is defined as:\nx for x >= 0.\n-x for x < 0.\n Example 1:\nInput: points = [[1,2,3],[1,5,1],[3,1,1]]\nOutput: 9\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\nYou add 3 + 5 + 3 = 11 to your score.\nHowever, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\nYour final score is 11 - 2 = 9.\nExample 2:\nInput: points = [[1,5],[2,3],[4,2]]\nOutput: 11\nExplanation:\nThe blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\nYou add 5 + 3 + 4 = 12 to your score.\nHowever, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\nYour final score is 12 - 1 = 11.\n Constraints:\nm == points.length\nn == points[r].length\n1 <= m, n <= 105\n1 <= m * n <= 105\n0 <= points[r][c] <= 105" }, { "post_href": "https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences/discuss/1359715/Python3-1-line", "python_solutions": "class Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1", "slug": "check-if-all-characters-have-equal-number-of-occurrences", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 35, "views": 2100, "problem_title": "check if all characters have equal number of occurrences", "number": 1941, "acceptance": 0.768, "difficulty": "Easy", "__index_level_0__": 27350, "question": "Given a string s, return true if s is a good string, or false otherwise.\nA string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).\n Example 1:\nInput: s = \"abacbc\"\nOutput: true\nExplanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.\nExample 2:\nInput: s = \"aaabb\"\nOutput: false\nExplanation: The characters that appear in s are 'a' and 'b'.\n'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.\n Constraints:\n1 <= s.length <= 1000\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/the-number-of-the-smallest-unoccupied-chair/discuss/1359713/Python-Simple-Heap-Solution-with-Explanation", "python_solutions": "class Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n arrivals = []\n departures = []\n for ind, (x, y) in enumerate(times):\n heappush(arrivals, (x, ind))\n heappush(departures, (y, ind))\n d = {}\n occupied = [0] * len(times)\n while True:\n if arrivals and departures and arrivals[0][0] < departures[0][0]:\n _, ind = heappop(arrivals)\n d[ind] = occupied.index(0)\n occupied[d[ind]] = 1\n if ind == targetFriend:\n return d[ind]\n elif arrivals and departures and arrivals[0][0] >= departures[0][0]:\n _, ind = heappop(departures)\n occupied[d[ind]] = 0", "slug": "the-number-of-the-smallest-unoccupied-chair", "post_title": "Python - Simple Heap Solution with Explanation", "user": "ajith6198", "upvotes": 20, "views": 1100, "problem_title": "the number of the smallest unoccupied chair", "number": 1942, "acceptance": 0.406, "difficulty": "Medium", "__index_level_0__": 27391, "question": "There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number.\nFor example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.\nWhen a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.\nYou are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct.\nReturn the chair number that the friend numbered targetFriend will sit on.\n Example 1:\nInput: times = [[1,4],[2,3],[4,6]], targetFriend = 1\nOutput: 1\nExplanation: \n- Friend 0 arrives at time 1 and sits on chair 0.\n- Friend 1 arrives at time 2 and sits on chair 1.\n- Friend 1 leaves at time 3 and chair 1 becomes empty.\n- Friend 0 leaves at time 4 and chair 0 becomes empty.\n- Friend 2 arrives at time 4 and sits on chair 0.\nSince friend 1 sat on chair 1, we return 1.\nExample 2:\nInput: times = [[3,10],[1,5],[2,6]], targetFriend = 0\nOutput: 2\nExplanation: \n- Friend 1 arrives at time 1 and sits on chair 0.\n- Friend 2 arrives at time 2 and sits on chair 1.\n- Friend 0 arrives at time 3 and sits on chair 2.\n- Friend 1 leaves at time 5 and chair 0 becomes empty.\n- Friend 2 leaves at time 6 and chair 1 becomes empty.\n- Friend 0 leaves at time 10 and chair 2 becomes empty.\nSince friend 0 sat on chair 2, we return 2.\n Constraints:\nn == times.length\n2 <= n <= 104\ntimes[i].length == 2\n1 <= arrivali < leavingi <= 105\n0 <= targetFriend <= n - 1\nEach arrivali time is distinct." }, { "post_href": "https://leetcode.com/problems/describe-the-painting/discuss/1359717/Python-Easy-solution-in-O(n*logn)-with-detailed-explanation", "python_solutions": "class Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n\t\t# via this mapping, we can easily know which coordinates should be took into consideration.\n mapping = defaultdict(int)\n for s, e, c in segments:\n mapping[s] += c\n mapping[e] -= c\n \n res = []\n prev, color = None, 0\n for now in sorted(mapping):\n if color: # if color == 0, it means this part isn't painted.\n res.append((prev, now, color))\n \n color += mapping[now]\n prev = now\n \n return res", "slug": "describe-the-painting", "post_title": "[Python] Easy solution in O(n*logn) with detailed explanation", "user": "fishballLin", "upvotes": 129, "views": 2000, "problem_title": "describe the painting", "number": 1943, "acceptance": 0.48, "difficulty": "Medium", "__index_level_0__": 27398, "question": "There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color.\nThe colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors.\nFor example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}.\nFor the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.\nYou want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj.\nFor example, the painting created with segments = [[1,4,5],[1,7,7]] can be described by painting = [[1,4,12],[4,7,7]] because:\n[1,4) is colored {5,7} (with a sum of 12) from both the first and second segments.\n[4,7) is colored {7} from only the second segment.\nReturn the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.\nA half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.\n Example 1:\nInput: segments = [[1,4,5],[4,7,7],[1,7,9]]\nOutput: [[1,4,14],[4,7,16]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,9} (with a sum of 14) from the first and third segments.\n- [4,7) is colored {7,9} (with a sum of 16) from the second and third segments.\nExample 2:\nInput: segments = [[1,7,9],[6,8,15],[8,10,7]]\nOutput: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\nExplanation: The painting can be described as follows:\n- [1,6) is colored 9 from the first segment.\n- [6,7) is colored {9,15} (with a sum of 24) from the first and second segments.\n- [7,8) is colored 15 from the second segment.\n- [8,10) is colored 7 from the third segment.\nExample 3:\nInput: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\nOutput: [[1,4,12],[4,7,12]]\nExplanation: The painting can be described as follows:\n- [1,4) is colored {5,7} (with a sum of 12) from the first and second segments.\n- [4,7) is colored {1,11} (with a sum of 12) from the third and fourth segments.\nNote that returning a single segment [1,7) is incorrect because the mixed color sets are different.\n Constraints:\n1 <= segments.length <= 2 * 104\nsegments[i].length == 3\n1 <= starti < endi <= 105\n1 <= colori <= 109\nEach colori is distinct." }, { "post_href": "https://leetcode.com/problems/number-of-visible-people-in-a-queue/discuss/1359735/Python3-mono-stack", "python_solutions": "class Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n ans = [0]*len(heights)\n stack = [] # mono-stack \n for i in reversed(range(len(heights))): \n while stack and stack[-1] <= heights[i]: \n ans[i] += 1\n stack.pop()\n if stack: ans[i] += 1\n stack.append(heights[i])\n return ans", "slug": "number-of-visible-people-in-a-queue", "post_title": "[Python3] mono-stack", "user": "ye15", "upvotes": 10, "views": 667, "problem_title": "number of visible people in a queue", "number": 1944, "acceptance": 0.6970000000000001, "difficulty": "Hard", "__index_level_0__": 27403, "question": "There are n people standing in a queue, and they numbered from 0 to n - 1 in left to right order. You are given an array heights of distinct integers where heights[i] represents the height of the ith person.\nA person can see another person to their right in the queue if everybody in between is shorter than both of them. More formally, the ith person can see the jth person if i < j and min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], ..., heights[j-1]).\nReturn an array answer of length n where answer[i] is the number of people the ith person can see to their right in the queue.\n Example 1:\nInput: heights = [10,6,8,5,11,9]\nOutput: [3,1,2,1,1,0]\nExplanation:\nPerson 0 can see person 1, 2, and 4.\nPerson 1 can see person 2.\nPerson 2 can see person 3 and 4.\nPerson 3 can see person 4.\nPerson 4 can see person 5.\nPerson 5 can see no one since nobody is to the right of them.\nExample 2:\nInput: heights = [5,1,2,3,10]\nOutput: [4,1,1,1,0]\n Constraints:\nn == heights.length\n1 <= n <= 105\n1 <= heights[i] <= 105\nAll the values of heights are unique." }, { "post_href": "https://leetcode.com/problems/sum-of-digits-of-string-after-convert/discuss/1360730/Python3-simulation", "python_solutions": "class Solution:\n def getLucky(self, s: str, k: int) -> int:\n s = \"\".join(str(ord(ch) - 96) for ch in s)\n for _ in range(k): \n x = sum(int(ch) for ch in s)\n s = str(x)\n return x", "slug": "sum-of-digits-of-string-after-convert", "post_title": "[Python3] simulation", "user": "ye15", "upvotes": 5, "views": 487, "problem_title": "sum of digits of string after convert", "number": 1945, "acceptance": 0.612, "difficulty": "Easy", "__index_level_0__": 27409, "question": "You are given a string s consisting of lowercase English letters, and an integer k.\nFirst, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total.\nFor example, if s = \"zbax\" and k = 2, then the resulting integer would be 8 by the following operations:\nConvert: \"zbax\" \u279d \"(26)(2)(1)(24)\" \u279d \"262124\" \u279d 262124\nTransform #1: 262124 \u279d 2 + 6 + 2 + 1 + 2 + 4 \u279d 17\nTransform #2: 17 \u279d 1 + 7 \u279d 8\nReturn the resulting integer after performing the operations described above.\n Example 1:\nInput: s = \"iiii\", k = 1\nOutput: 36\nExplanation: The operations are as follows:\n- Convert: \"iiii\" \u279d \"(9)(9)(9)(9)\" \u279d \"9999\" \u279d 9999\n- Transform #1: 9999 \u279d 9 + 9 + 9 + 9 \u279d 36\nThus the resulting integer is 36.\nExample 2:\nInput: s = \"leetcode\", k = 2\nOutput: 6\nExplanation: The operations are as follows:\n- Convert: \"leetcode\" \u279d \"(12)(5)(5)(20)(3)(15)(4)(5)\" \u279d \"12552031545\" \u279d 12552031545\n- Transform #1: 12552031545 \u279d 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 \u279d 33\n- Transform #2: 33 \u279d 3 + 3 \u279d 6\nThus the resulting integer is 6.\nExample 3:\nInput: s = \"zbax\", k = 2\nOutput: 8\n Constraints:\n1 <= s.length <= 100\n1 <= k <= 10\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/largest-number-after-mutating-substring/discuss/1360736/Python3-greedy", "python_solutions": "class Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n num = list(num)\n on = False \n for i, ch in enumerate(num): \n x = int(ch)\n if x < change[x]: \n on = True\n num[i] = str(change[x])\n elif x > change[x] and on: break\n return \"\".join(num)", "slug": "largest-number-after-mutating-substring", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 7, "views": 572, "problem_title": "largest number after mutating substring", "number": 1946, "acceptance": 0.346, "difficulty": "Medium", "__index_level_0__": 27437, "question": "You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d].\nYou may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]).\nReturn a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.\nA substring is a contiguous sequence of characters within the string.\n Example 1:\nInput: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\nOutput: \"832\"\nExplanation: Replace the substring \"1\":\n- 1 maps to change[1] = 8.\nThus, \"132\" becomes \"832\".\n\"832\" is the largest number that can be created, so return it.\nExample 2:\nInput: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\nOutput: \"934\"\nExplanation: Replace the substring \"021\":\n- 0 maps to change[0] = 9.\n- 2 maps to change[2] = 3.\n- 1 maps to change[1] = 4.\nThus, \"021\" becomes \"934\".\n\"934\" is the largest number that can be created, so return it.\nExample 3:\nInput: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\nOutput: \"5\"\nExplanation: \"5\" is already the largest number that can be created, so return it.\n Constraints:\n1 <= num.length <= 105\nnum consists of only digits 0-9.\nchange.length == 10\n0 <= change[d] <= 9" }, { "post_href": "https://leetcode.com/problems/maximum-compatibility-score-sum/discuss/1360746/Python3-permutations", "python_solutions": "class Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m = len(students)\n \n score = [[0]*m for _ in range(m)]\n for i in range(m): \n for j in range(m): \n score[i][j] = sum(x == y for x, y in zip(students[i], mentors[j]))\n \n ans = 0 \n for perm in permutations(range(m)): \n ans = max(ans, sum(score[i][j] for i, j in zip(perm, range(m))))\n return ans", "slug": "maximum-compatibility-score-sum", "post_title": "[Python3] permutations", "user": "ye15", "upvotes": 16, "views": 1100, "problem_title": "maximum compatibility score sum", "number": 1947, "acceptance": 0.609, "difficulty": "Medium", "__index_level_0__": 27443, "question": "There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).\nThe survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed).\nEach student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor.\nFor example, if the student's answers were [1, 0, 1] and the mentor's answers were [0, 0, 1], then their compatibility score is 2 because only the second and the third answers are the same.\nYou are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.\nGiven students and mentors, return the maximum compatibility score sum that can be achieved.\n Example 1:\nInput: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\nOutput: 8\nExplanation: We assign students to mentors in the following way:\n- student 0 to mentor 2 with a compatibility score of 3.\n- student 1 to mentor 0 with a compatibility score of 2.\n- student 2 to mentor 1 with a compatibility score of 3.\nThe compatibility score sum is 3 + 2 + 3 = 8.\nExample 2:\nInput: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\nOutput: 0\nExplanation: The compatibility score of any student-mentor pair is 0.\n Constraints:\nm == students.length == mentors.length\nn == students[i].length == mentors[j].length\n1 <= m, n <= 8\nstudents[i][k] is either 0 or 1.\nmentors[j][k] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/delete-duplicate-folders-in-system/discuss/1360749/Python3-serialize-sub-trees", "python_solutions": "class Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n paths.sort()\n \n tree = {\"#\": -1}\n for i, path in enumerate(paths): \n node = tree\n for x in path: node = node.setdefault(x, {})\n node[\"#\"] = i\n \n seen = {}\n mark = set()\n \n def fn(n): \n \"\"\"Return serialized value of sub-tree rooted at n.\"\"\"\n if len(n) == 1: return \"$\" # leaf node \n vals = []\n for k in n: \n if k != \"#\": vals.append(f\"${k}${fn(n[k])}\")\n hs = \"\".join(vals)\n if hs in seen: \n mark.add(n[\"#\"])\n mark.add(seen[hs])\n if hs != \"$\": seen[hs] = n[\"#\"]\n return hs\n \n fn(tree)\n \n ans = []\n stack = [tree]\n while stack: \n n = stack.pop()\n if n[\"#\"] >= 0: ans.append(paths[n[\"#\"]])\n for k in n: \n if k != \"#\" and n[k][\"#\"] not in mark: stack.append(n[k])\n return ans", "slug": "delete-duplicate-folders-in-system", "post_title": "[Python3] serialize sub-trees", "user": "ye15", "upvotes": 4, "views": 469, "problem_title": "delete duplicate folders in system", "number": 1948, "acceptance": 0.579, "difficulty": "Hard", "__index_level_0__": 27452, "question": "Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i] is an array representing an absolute path to the ith folder in the file system.\nFor example, [\"one\", \"two\", \"three\"] represents the path \"/one/two/three\".\nTwo folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If two or more folders are identical, then mark the folders as well as all their subfolders.\nFor example, folders \"/a\" and \"/b\" in the file structure below are identical. They (as well as their subfolders) should all be marked:\n/a\n/a/x\n/a/x/y\n/a/z\n/b\n/b/x\n/b/x/y\n/b/z\nHowever, if the file structure also included the path \"/b/w\", then the folders \"/a\" and \"/b\" would not be identical. Note that \"/a/x\" and \"/b/x\" would still be considered identical even with the added folder.\nOnce all the identical folders and their subfolders have been marked, the file system will delete all of them. The file system only runs the deletion once, so any folders that become identical after the initial deletion are not deleted.\nReturn the 2D array ans containing the paths of the remaining folders after deleting all the marked folders. The paths may be returned in any order.\n Example 1:\nInput: paths = [[\"a\"],[\"c\"],[\"d\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"d\",\"a\"]]\nOutput: [[\"d\"],[\"d\",\"a\"]]\nExplanation: The file structure is as shown.\nFolders \"/a\" and \"/c\" (and their subfolders) are marked for deletion because they both contain an empty\nfolder named \"b\".\nExample 2:\nInput: paths = [[\"a\"],[\"c\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"a\",\"b\",\"x\"],[\"a\",\"b\",\"x\",\"y\"],[\"w\"],[\"w\",\"y\"]]\nOutput: [[\"c\"],[\"c\",\"b\"],[\"a\"],[\"a\",\"b\"]]\nExplanation: The file structure is as shown. \nFolders \"/a/b/x\" and \"/w\" (and their subfolders) are marked for deletion because they both contain an empty folder named \"y\".\nNote that folders \"/a\" and \"/c\" are identical after the deletion, but they are not deleted because they were not marked beforehand.\nExample 3:\nInput: paths = [[\"a\",\"b\"],[\"c\",\"d\"],[\"c\"],[\"a\"]]\nOutput: [[\"c\"],[\"c\",\"d\"],[\"a\"],[\"a\",\"b\"]]\nExplanation: All folders are unique in the file system.\nNote that the returned array can be in a different order as the order does not matter.\n Constraints:\n1 <= paths.length <= 2 * 104\n1 <= paths[i].length <= 500\n1 <= paths[i][j].length <= 10\n1 <= sum(paths[i][j].length) <= 2 * 105\npath[i][j] consists of lowercase English letters.\nNo two paths lead to the same folder.\nFor any folder not at the root level, its parent folder will also be in the input." }, { "post_href": "https://leetcode.com/problems/three-divisors/discuss/1375468/Python3-1-line", "python_solutions": "class Solution:\n def isThree(self, n: int) -> bool:\n return sum(n%i == 0 for i in range(1, n+1)) == 3", "slug": "three-divisors", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 14, "views": 866, "problem_title": "three divisors", "number": 1952, "acceptance": 0.5720000000000001, "difficulty": "Easy", "__index_level_0__": 27454, "question": "Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.\nAn integer m is a divisor of n if there exists an integer k such that n = k * m.\n Example 1:\nInput: n = 2\nOutput: false\nExplantion: 2 has only two divisors: 1 and 2.\nExample 2:\nInput: n = 4\nOutput: true\nExplantion: 4 has three divisors: 1, 2, and 4.\n Constraints:\n1 <= n <= 104" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-weeks-for-which-you-can-work/discuss/1375390/Python-Solution-with-detailed-explanation-and-proof-and-common-failure-analysis", "python_solutions": "class Solution:\n def numberOfWeeks(self, milestones: List[int]) -> int:\n _sum, _max = sum(milestones), max(milestones)\n\t\t# (_sum - _max) is the sum of milestones from (2) the rest of projects, if True, we can form another project with the same amount of milestones as (1)\n\t\t# can refer to the section `Why the greedy strategy works?` for the proof\n if _sum - _max >= _max: \n return _sum\n return 2 * (_sum - _max) + 1 # start from the project with most milestones (_sum - _max + 1) and work on the the rest of milestones (_sum - _max)", "slug": "maximum-number-of-weeks-for-which-you-can-work", "post_title": "[Python] Solution with detailed explanation & proof & common failure analysis", "user": "fishballLin", "upvotes": 232, "views": 7200, "problem_title": "maximum number of weeks for which you can work", "number": 1953, "acceptance": 0.391, "difficulty": "Medium", "__index_level_0__": 27482, "question": "There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has.\nYou can work on the projects following these two rules:\nEvery week, you will finish exactly one milestone of one project. You must work every week.\nYou cannot work on two milestones from the same project for two consecutive weeks.\nOnce all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints.\nReturn the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.\n Example 1:\nInput: milestones = [1,2,3]\nOutput: 6\nExplanation: One possible scenario is:\n- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 2.\n- During the 3rd week, you will work on a milestone of project 1.\n- During the 4th week, you will work on a milestone of project 2.\n- During the 5th week, you will work on a milestone of project 1.\n- During the 6th week, you will work on a milestone of project 2.\nThe total number of weeks is 6.\nExample 2:\nInput: milestones = [5,2,1]\nOutput: 7\nExplanation: One possible scenario is:\n- During the 1st week, you will work on a milestone of project 0.\n- During the 2nd week, you will work on a milestone of project 1.\n- During the 3rd week, you will work on a milestone of project 0.\n- During the 4th week, you will work on a milestone of project 1.\n- During the 5th week, you will work on a milestone of project 0.\n- During the 6th week, you will work on a milestone of project 2.\n- During the 7th week, you will work on a milestone of project 0.\nThe total number of weeks is 7.\nNote that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.\nThus, one milestone in project 0 will remain unfinished.\n Constraints:\nn == milestones.length\n1 <= n <= 105\n1 <= milestones[i] <= 109" }, { "post_href": "https://leetcode.com/problems/minimum-garden-perimeter-to-collect-enough-apples/discuss/1589250/Explanation-for-Intuition-behind-the-math-formula-derivation", "python_solutions": "class Solution:\n def minimumPerimeter(self, nap: int) -> int:\n \n \n# here for n = 2 , there are two series : \n# (1) Diagnal points for n=3 , diagnal apples = 2*n = 6\n# (2) there is series = 2,3,3 = 2+ (sigma(3)-sigma(2))*2\n \n# how to solve:\n \n# here 3 = sigma(n+(n-1))-sigma(n) = sigma(2*n-1)-sigma(n) = 0.5*2n*(2n-1)-0.5*n*n-1\n# (3) so our final 2,3,3 = 3*2+2 = (0.5*2n*(2n-1)-0.5*n*n-1)*2+n\n# (4) so final 2,3,3 = 3*n*n - 2*n\n# (5) we have 4 times repitation of (2,3,3) = 4*(2,3,3) = 4*(3*n*n - 2*n) = 12*n*n - 8*n\n# (6) we have 4 diagnal points so their sum(4 diagnal) = 4*(2*n)\n# (7) so final sum(total) = 4 diagnal sum + 4(2,3,3) = 4(2*n) + 12*n*n - 8*n = 12*n*n\n \n# so at nth distance we have total 12*n*n apples at the circumfrance\n \n# so net sum = sigma(12*n*n) = 2*n*(n+1)*(2*n+1)\n \n \n n=1\n val=2*n*(n+1)*(2*n+1)\n while(val= 0\n-x if x < 0\n Example 1:\nInput: neededApples = 1\nOutput: 8\nExplanation: A square plot of side length 1 does not contain any apples.\nHowever, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\nThe perimeter is 2 * 4 = 8.\nExample 2:\nInput: neededApples = 13\nOutput: 16\nExample 3:\nInput: neededApples = 1000000000\nOutput: 5040\n Constraints:\n1 <= neededApples <= 1015" }, { "post_href": "https://leetcode.com/problems/count-number-of-special-subsequences/discuss/1387357/Simple-Python-with-comments.-One-pass-O(n)-with-O(1)-space", "python_solutions": "class Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n total_zeros = 0 # number of subsequences of 0s so far\n total_ones = 0 # the number of subsequences of 0s followed by 1s so far\n total_twos = 0 # the number of special subsequences so far\n \n M = 1000000007\n \n for n in nums:\n if n == 0:\n # if we have found new 0 we can add it to any existing subsequence of 0s\n # or use only this 0\n total_zeros += (total_zeros + 1) % M\n elif n == 1:\n # if we have found new 1 we can add it to any existing subsequence of 0s or 0s and 1s\n # to get a valid subsequence of 0s and 1s\n total_ones += (total_zeros + total_ones) % M\n else:\n # if we have found new 2 we can add it to any existing subsequence of 0s and 1s 0r 0s,1s and 2s\n # to get a valid subsequence of 0s,1s and 2s\n total_twos += (total_ones + total_twos) % M\n \n return total_twos % M", "slug": "count-number-of-special-subsequences", "post_title": "Simple Python with comments. One pass O(n) with O(1) space", "user": "IlyaL", "upvotes": 4, "views": 151, "problem_title": "count number of special subsequences", "number": 1955, "acceptance": 0.513, "difficulty": "Hard", "__index_level_0__": 27499, "question": "A sequence is special if it consists of a positive number of 0s, followed by a positive number of 1s, then a positive number of 2s.\nFor example, [0,1,2] and [0,0,1,1,1,2] are special.\nIn contrast, [2,1,0], [1], and [0,1,2,0] are not special.\nGiven an array nums (consisting of only integers 0, 1, and 2), return the number of different subsequences that are special. Since the answer may be very large, return it modulo 109 + 7.\nA subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. Two subsequences are different if the set of indices chosen are different.\n Example 1:\nInput: nums = [0,1,2,2]\nOutput: 3\nExplanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].\nExample 2:\nInput: nums = [2,2,0,0]\nOutput: 0\nExplanation: There are no special subsequences in [2,2,0,0].\nExample 3:\nInput: nums = [0,1,2,0,1,2]\nOutput: 7\nExplanation: The special subsequences are bolded:\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n- [0,1,2,0,1,2]\n Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 2" }, { "post_href": "https://leetcode.com/problems/delete-characters-to-make-fancy-string/discuss/2714159/Python-or-Easy-Solution", "python_solutions": "class Solution:\n def makeFancyString(self, s: str) -> str:\n stack = []\n for letter in s:\n if len(stack) > 1 and letter == stack[-1] == stack[-2]:\n stack.pop()\n stack.append(letter)\n return ''.join(stack)", "slug": "delete-characters-to-make-fancy-string", "post_title": "Python | Easy Solution\u2714", "user": "manayathgeorgejames", "upvotes": 6, "views": 113, "problem_title": "delete characters to make fancy string", "number": 1957, "acceptance": 0.5670000000000001, "difficulty": "Easy", "__index_level_0__": 27503, "question": "A fancy string is a string where no three consecutive characters are equal.\nGiven a string s, delete the minimum possible number of characters from s to make it fancy.\nReturn the final string after the deletion. It can be shown that the answer will always be unique.\n Example 1:\nInput: s = \"leeetcode\"\nOutput: \"leetcode\"\nExplanation:\nRemove an 'e' from the first group of 'e's to create \"leetcode\".\nNo three consecutive characters are equal, so return \"leetcode\".\nExample 2:\nInput: s = \"aaabaaaa\"\nOutput: \"aabaa\"\nExplanation:\nRemove an 'a' from the first group of 'a's to create \"aabaaaa\".\nRemove two 'a's from the second group of 'a's to create \"aabaa\".\nNo three consecutive characters are equal, so return \"aabaa\".\nExample 3:\nInput: s = \"aab\"\nOutput: \"aab\"\nExplanation: No three consecutive characters are equal, so return \"aab\".\n Constraints:\n1 <= s.length <= 105\ns consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/check-if-move-is-legal/discuss/1389250/Python3-check-8-directions", "python_solutions": "class Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n for di, dj in (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1): \n i, j = rMove+di, cMove+dj\n step = 0\n while 0 <= i < 8 and 0 <= j < 8: \n if board[i][j] == color and step: return True \n if board[i][j] == \".\" or board[i][j] == color and not step: break \n i, j = i+di, j+dj\n step += 1\n return False", "slug": "check-if-move-is-legal", "post_title": "[Python3] check 8 directions", "user": "ye15", "upvotes": 5, "views": 312, "problem_title": "check if move is legal", "number": 1958, "acceptance": 0.445, "difficulty": "Medium", "__index_level_0__": 27526, "question": "You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'.\nEach move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal).\nA good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below:\nGiven two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.\n Example 1:\nInput: board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"\nOutput: true\nExplanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\nThe two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.\nExample 2:\nInput: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"\nOutput: false\nExplanation: While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.\n Constraints:\nboard.length == board[r].length == 8\n0 <= rMove, cMove < 8\nboard[rMove][cMove] == '.'\ncolor is either 'B' or 'W'." }, { "post_href": "https://leetcode.com/problems/minimum-total-space-wasted-with-k-resizing-operations/discuss/1389260/Python3-dp", "python_solutions": "class Solution:\n def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:\n \n @cache\n def fn(i, k): \n \"\"\"Return min waste from i with k ops.\"\"\"\n if i == len(nums): return 0\n if k < 0: return inf \n ans = inf\n rmx = rsm = 0\n for j in range(i, len(nums)): \n rmx = max(rmx, nums[j])\n rsm += nums[j]\n ans = min(ans, rmx*(j-i+1) - rsm + fn(j+1, k-1))\n return ans \n \n return fn(0, k)", "slug": "minimum-total-space-wasted-with-k-resizing-operations", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 14, "views": 987, "problem_title": "minimum total space wasted with k resizing operations", "number": 1959, "acceptance": 0.42, "difficulty": "Medium", "__index_level_0__": 27530, "question": "You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).\nThe size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length.\nReturn the minimum total space wasted if you can resize the array at most k times.\nNote: The array can have any size at the start and does not count towards the number of resizing operations.\n Example 1:\nInput: nums = [10,20], k = 0\nOutput: 10\nExplanation: size = [20,20].\nWe can set the initial size to be 20.\nThe total wasted space is (20 - 10) + (20 - 20) = 10.\nExample 2:\nInput: nums = [10,20,30], k = 1\nOutput: 10\nExplanation: size = [20,20,30].\nWe can set the initial size to be 20 and resize to 30 at time 2. \nThe total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.\nExample 3:\nInput: nums = [10,20,15,30,20], k = 2\nOutput: 15\nExplanation: size = [10,20,20,30,30].\nWe can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\nThe total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.\n Constraints:\n1 <= nums.length <= 200\n1 <= nums[i] <= 106\n0 <= k <= nums.length - 1" }, { "post_href": "https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-substrings/discuss/1393832/Python3-Manacher", "python_solutions": "class Solution:\n def maxProduct(self, s: str) -> int:\n n = len(s)\n \n # Manacher's algo\n hlen = [0]*n # half-length\n center = right = 0 \n for i in range(n): \n if i < right: hlen[i] = min(right - i, hlen[2*center - i])\n while 0 <= i-1-hlen[i] and i+1+hlen[i] < len(s) and s[i-1-hlen[i]] == s[i+1+hlen[i]]: \n hlen[i] += 1\n if right < i+hlen[i]: center, right = i, i+hlen[i]\n \n prefix = [0]*n\n suffix = [0]*n\n for i in range(n): \n prefix[i+hlen[i]] = max(prefix[i+hlen[i]], 2*hlen[i]+1)\n suffix[i-hlen[i]] = max(suffix[i-hlen[i]], 2*hlen[i]+1)\n \n for i in range(1, n): \n prefix[~i] = max(prefix[~i], prefix[~i+1]-2)\n suffix[i] = max(suffix[i], suffix[i-1]-2)\n \n for i in range(1, n): \n prefix[i] = max(prefix[i-1], prefix[i])\n suffix[~i] = max(suffix[~i], suffix[~i+1])\n \n return max(prefix[i-1]*suffix[i] for i in range(1, n))", "slug": "maximum-product-of-the-length-of-two-palindromic-substrings", "post_title": "[Python3] Manacher", "user": "ye15", "upvotes": 3, "views": 200, "problem_title": "maximum product of the length of two palindromic substrings", "number": 1960, "acceptance": 0.293, "difficulty": "Hard", "__index_level_0__": 27534, "question": "You are given a 0-indexed string s and are tasked with finding two non-intersecting palindromic substrings of odd length such that the product of their lengths is maximized.\nMore formally, you want to choose four integers i, j, k, l such that 0 <= i <= j < k <= l < s.length and both the substrings s[i...j] and s[k...l] are palindromes and have odd lengths. s[i...j] denotes a substring from index i to index j inclusive.\nReturn the maximum possible product of the lengths of the two non-intersecting palindromic substrings.\nA palindrome is a string that is the same forward and backward. A substring is a contiguous sequence of characters in a string.\n Example 1:\nInput: s = \"ababbb\"\nOutput: 9\nExplanation: Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.\nExample 2:\nInput: s = \"zaaaxbbby\"\nOutput: 9\nExplanation: Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.\n Constraints:\n2 <= s.length <= 105\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/check-if-string-is-a-prefix-of-array/discuss/1390199/Python3-move-along-s", "python_solutions": "class Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n i = 0\n for word in words: \n if s[i:i+len(word)] != word: return False \n i += len(word)\n if i == len(s): return True \n return False", "slug": "check-if-string-is-a-prefix-of-array", "post_title": "[Python3] move along s", "user": "ye15", "upvotes": 22, "views": 1200, "problem_title": "check if string is a prefix of array", "number": 1961, "acceptance": 0.541, "difficulty": "Easy", "__index_level_0__": 27535, "question": "Given a string s and an array of strings words, determine whether s is a prefix string of words.\nA string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length.\nReturn true if s is a prefix string of words, or false otherwise.\n Example 1:\nInput: s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\nOutput: true\nExplanation:\ns can be made by concatenating \"i\", \"love\", and \"leetcode\" together.\nExample 2:\nInput: s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\nOutput: false\nExplanation:\nIt is impossible to make s using a prefix of arr.\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 20\n1 <= s.length <= 1000\nwords[i] and s consist of only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/remove-stones-to-minimize-the-total/discuss/1390207/Python3-priority-queue", "python_solutions": "class Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n pq = [-x for x in piles]\n heapify(pq)\n for _ in range(k): heapreplace(pq, pq[0]//2)\n return -sum(pq)", "slug": "remove-stones-to-minimize-the-total", "post_title": "[Python3] priority queue", "user": "ye15", "upvotes": 7, "views": 413, "problem_title": "remove stones to minimize the total", "number": 1962, "acceptance": 0.593, "difficulty": "Medium", "__index_level_0__": 27556, "question": "You are given a 0-indexed integer array piles, where piles[i] represents the number of stones in the ith pile, and an integer k. You should apply the following operation exactly k times:\nChoose any piles[i] and remove floor(piles[i] / 2) stones from it.\nNotice that you can apply the operation on the same pile more than once.\nReturn the minimum possible total number of stones remaining after applying the k operations.\nfloor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).\n Example 1:\nInput: piles = [5,4,9], k = 2\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [5,4,5].\n- Apply the operation on pile 0. The resulting piles are [3,4,5].\nThe total number of stones in [3,4,5] is 12.\nExample 2:\nInput: piles = [4,3,6,7], k = 3\nOutput: 12\nExplanation: Steps of a possible scenario are:\n- Apply the operation on pile 2. The resulting piles are [4,3,3,7].\n- Apply the operation on pile 3. The resulting piles are [4,3,3,4].\n- Apply the operation on pile 0. The resulting piles are [2,3,3,4].\nThe total number of stones in [2,3,3,4] is 12.\n Constraints:\n1 <= piles.length <= 105\n1 <= piles[i] <= 104\n1 <= k <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/discuss/1390576/Two-Pointers", "python_solutions": "class Solution:\n def minSwaps(self, s: str) -> int:\n res, bal = 0, 0\n for ch in s:\n bal += 1 if ch == '[' else -1\n if bal == -1:\n res += 1\n bal = 1\n return res", "slug": "minimum-number-of-swaps-to-make-the-string-balanced", "post_title": "Two Pointers", "user": "votrubac", "upvotes": 19, "views": 2000, "problem_title": "minimum number of swaps to make the string balanced", "number": 1963, "acceptance": 0.684, "difficulty": "Medium", "__index_level_0__": 27563, "question": "You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.\nA string is called balanced if and only if:\nIt is the empty string, or\nIt can be written as AB, where both A and B are balanced strings, or\nIt can be written as [C], where C is a balanced string.\nYou may swap the brackets at any two indices any number of times.\nReturn the minimum number of swaps to make s balanced.\n Example 1:\nInput: s = \"][][\"\nOutput: 1\nExplanation: You can make the string balanced by swapping index 0 with index 3.\nThe resulting string is \"[[]]\".\nExample 2:\nInput: s = \"]]][[[\"\nOutput: 2\nExplanation: You can do the following to make the string balanced:\n- Swap index 0 with index 4. s = \"[]][][\".\n- Swap index 1 with index 5. s = \"[[][]]\".\nThe resulting string is \"[[][]]\".\nExample 3:\nInput: s = \"[]\"\nOutput: 0\nExplanation: The string is already balanced.\n Constraints:\nn == s.length\n2 <= n <= 106\nn is even.\ns[i] is either '[' or ']'.\nThe number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2." }, { "post_href": "https://leetcode.com/problems/find-the-longest-valid-obstacle-course-at-each-position/discuss/1390573/Clean-and-Simple-oror-98-faster-oror-Easy-Code", "python_solutions": "class Solution:\ndef longestObstacleCourseAtEachPosition(self, obs: List[int]) -> List[int]:\n local = []\n res=[0 for _ in range(len(obs))]\n for i in range(len(obs)):\n n=obs[i]\n if len(local)==0 or local[-1]<=n:\n local.append(n)\n res[i]=len(local)\n else:\n ind = bisect.bisect_right(local,n)\n local[ind]=n\n res[i]=ind+1\n \n return res", "slug": "find-the-longest-valid-obstacle-course-at-each-position", "post_title": "\ud83d\udccc Clean & Simple || 98% faster || Easy-Code \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 1, "views": 48, "problem_title": "find the longest valid obstacle course at each position", "number": 1964, "acceptance": 0.469, "difficulty": "Hard", "__index_level_0__": 27574, "question": "You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle.\nFor every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:\nYou choose any number of obstacles between 0 and i inclusive.\nYou must include the ith obstacle in the course.\nYou must put the chosen obstacles in the same order as they appear in obstacles.\nEvery obstacle (except the first) is taller than or the same height as the obstacle immediately before it.\nReturn an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.\n Example 1:\nInput: obstacles = [1,2,3,2]\nOutput: [1,2,3,3]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [1], [1] has length 1.\n- i = 1: [1,2], [1,2] has length 2.\n- i = 2: [1,2,3], [1,2,3] has length 3.\n- i = 3: [1,2,3,2], [1,2,2] has length 3.\nExample 2:\nInput: obstacles = [2,2,1]\nOutput: [1,2,1]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [2], [2] has length 1.\n- i = 1: [2,2], [2,2] has length 2.\n- i = 2: [2,2,1], [1] has length 1.\nExample 3:\nInput: obstacles = [3,1,5,6,4,2]\nOutput: [1,1,2,3,2,2]\nExplanation: The longest valid obstacle course at each position is:\n- i = 0: [3], [3] has length 1.\n- i = 1: [3,1], [1] has length 1.\n- i = 2: [3,1,5], [3,5] has length 2. [1,5] is also valid.\n- i = 3: [3,1,5,6], [3,5,6] has length 3. [1,5,6] is also valid.\n- i = 4: [3,1,5,6,4], [3,4] has length 2. [1,4] is also valid.\n- i = 5: [3,1,5,6,4,2], [1,2] has length 2.\n Constraints:\nn == obstacles.length\n1 <= n <= 105\n1 <= obstacles[i] <= 107" }, { "post_href": "https://leetcode.com/problems/number-of-strings-that-appear-as-substrings-in-word/discuss/1404073/Python3-1-line", "python_solutions": "class Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n return sum(x in word for x in patterns)", "slug": "number-of-strings-that-appear-as-substrings-in-word", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 19, "views": 1400, "problem_title": "number of strings that appear as substrings in word", "number": 1967, "acceptance": 0.799, "difficulty": "Easy", "__index_level_0__": 27576, "question": "Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.\nA substring is a contiguous sequence of characters within a string.\n Example 1:\nInput: patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"\nOutput: 3\nExplanation:\n- \"a\" appears as a substring in \"abc\".\n- \"abc\" appears as a substring in \"abc\".\n- \"bc\" appears as a substring in \"abc\".\n- \"d\" does not appear as a substring in \"abc\".\n3 of the strings in patterns appear as a substring in word.\nExample 2:\nInput: patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"\nOutput: 2\nExplanation:\n- \"a\" appears as a substring in \"aaaaabbbbb\".\n- \"b\" appears as a substring in \"aaaaabbbbb\".\n- \"c\" does not appear as a substring in \"aaaaabbbbb\".\n2 of the strings in patterns appear as a substring in word.\nExample 3:\nInput: patterns = [\"a\",\"a\",\"a\"], word = \"ab\"\nOutput: 3\nExplanation: Each of the patterns appears as a substring in word \"ab\".\n Constraints:\n1 <= patterns.length <= 100\n1 <= patterns[i].length <= 100\n1 <= word.length <= 100\npatterns[i] and word consist of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/discuss/2280763/O(nlogn)-Solution-or-Python", "python_solutions": "class Solution:\n \n \n def rearrangeArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n if len(nums)==3:\n nums[1],nums[0] = nums[0],nums[1]\n return nums\n for i in range(1,len(nums)-1):\n if nums[i]-nums[i-1] == nums[i+1]-nums[i]:\n if i!=len(nums)-2:\n nums[i+1],nums[i+2] = nums[i+2],nums[i+1] \n if i==len(nums)-2:\n nums[i+1],nums[0] = nums[0],nums[i+1]\n return nums", "slug": "array-with-elements-not-equal-to-average-of-neighbors", "post_title": "O(nlogn) Solution | Python", "user": "user7457RV", "upvotes": 0, "views": 27, "problem_title": "array with elements not equal to average of neighbors", "number": 1968, "acceptance": 0.496, "difficulty": "Medium", "__index_level_0__": 27600, "question": "You are given a 0-indexed array nums of distinct integers. You want to rearrange the elements in the array such that every element in the rearranged array is not equal to the average of its neighbors.\nMore formally, the rearranged array should have the property such that for every i in the range 1 <= i < nums.length - 1, (nums[i-1] + nums[i+1]) / 2 is not equal to nums[i].\nReturn any rearrangement of nums that meets the requirements.\n Example 1:\nInput: nums = [1,2,3,4,5]\nOutput: [1,2,4,5,3]\nExplanation:\nWhen i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\nWhen i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\nWhen i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\nExample 2:\nInput: nums = [6,2,0,9,7]\nOutput: [9,7,6,2,0]\nExplanation:\nWhen i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\nWhen i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\nWhen i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\n Constraints:\n3 <= nums.length <= 105\n0 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-non-zero-product-of-the-array-elements/discuss/1403953/Python3-2-line", "python_solutions": "class Solution:\n def minNonZeroProduct(self, p: int) -> int:\n x = (1 << p) - 1\n return pow(x-1, (x-1)//2, 1_000_000_007) * x % 1_000_000_007", "slug": "minimum-non-zero-product-of-the-array-elements", "post_title": "[Python3] 2-line", "user": "ye15", "upvotes": 6, "views": 569, "problem_title": "minimum non zero product of the array elements", "number": 1969, "acceptance": 0.3379999999999999, "difficulty": "Medium", "__index_level_0__": 27603, "question": "You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times:\nChoose two elements x and y from nums.\nChoose a bit in x and swap it with its corresponding bit in y. Corresponding bit refers to the bit that is in the same position in the other integer.\nFor example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.\nFind the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.\nNote: The answer should be the minimum product before the modulo operation is done.\n Example 1:\nInput: p = 1\nOutput: 1\nExplanation: nums = [1].\nThere is only one element, so the product equals that element.\nExample 2:\nInput: p = 2\nOutput: 6\nExplanation: nums = [01, 10, 11].\nAny swap would either make the product 0 or stay the same.\nThus, the array product of 1 * 2 * 3 = 6 is already minimized.\nExample 3:\nInput: p = 3\nOutput: 1512\nExplanation: nums = [001, 010, 011, 100, 101, 110, 111]\n- In the first operation we can swap the leftmost bit of the second and fifth elements.\n - The resulting array is [001, 110, 011, 100, 001, 110, 111].\n- In the second operation we can swap the middle bit of the third and fourth elements.\n - The resulting array is [001, 110, 001, 110, 001, 110, 111].\nThe array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.\n Constraints:\n1 <= p <= 60" }, { "post_href": "https://leetcode.com/problems/last-day-where-you-can-still-cross/discuss/2489142/Python3-or-Binary-Search-%2B-BFS", "python_solutions": "class Solution(object):\n def latestDayToCross(self, row, col, cells):\n l,h=0,len(cells)-1\n ans=-1\n while l<=h:\n m=(l+h)>>1\n if self.isPath(cells,m,row,col):\n l=m+1\n ans=m+1\n else:\n h=m-1\n return ans\n def isPath(self,cells,ind,row,col):\n grid=[[0 for i in range(col)] for j in range(row)]\n for i in range(ind+1):\n x,y=cells[i]\n grid[x-1][y-1]=1\n vis=set()\n for i in range(col):\n if grid[0][i]!=1:\n dq=deque()\n dq.append((0,i))\n dr=[(-1,0),(0,-1),(1,0),(0,1)]\n while dq:\n x,y=dq.popleft()\n if x==row-1:\n return True\n for d in dr:\n dx,dy=d\n if 0<=x+dx int:\n ans = len(word)\n prev = \"a\"\n for ch in word: \n val = (ord(ch) - ord(prev)) % 26 \n ans += min(val, 26 - val)\n prev = ch\n return ans", "slug": "minimum-time-to-type-word-using-special-typewriter", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 48, "views": 2200, "problem_title": "minimum time to type word using special typewriter", "number": 1974, "acceptance": 0.7140000000000001, "difficulty": "Easy", "__index_level_0__": 27634, "question": "There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.\nEach second, you may perform one of the following operations:\nMove the pointer one character counterclockwise or clockwise.\nType the character the pointer is currently on.\nGiven a string word, return the minimum number of seconds to type out the characters in word.\n Example 1:\nInput: word = \"abc\"\nOutput: 5\nExplanation: \nThe characters are printed as follows:\n- Type the character 'a' in 1 second since the pointer is initially on 'a'.\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer clockwise to 'c' in 1 second.\n- Type the character 'c' in 1 second.\nExample 2:\nInput: word = \"bza\"\nOutput: 7\nExplanation:\nThe characters are printed as follows:\n- Move the pointer clockwise to 'b' in 1 second.\n- Type the character 'b' in 1 second.\n- Move the pointer counterclockwise to 'z' in 2 seconds.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'a' in 1 second.\n- Type the character 'a' in 1 second.\nExample 3:\nInput: word = \"zjpc\"\nOutput: 34\nExplanation:\nThe characters are printed as follows:\n- Move the pointer counterclockwise to 'z' in 1 second.\n- Type the character 'z' in 1 second.\n- Move the pointer clockwise to 'j' in 10 seconds.\n- Type the character 'j' in 1 second.\n- Move the pointer clockwise to 'p' in 6 seconds.\n- Type the character 'p' in 1 second.\n- Move the pointer counterclockwise to 'c' in 13 seconds.\n- Type the character 'c' in 1 second.\n Constraints:\n1 <= word.length <= 100\nword consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-matrix-sum/discuss/1417592/Python3-greedy", "python_solutions": "class Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n ans = mult = 0\n val = inf \n for i in range(len(matrix)): \n for j in range(len(matrix)):\n ans += abs(matrix[i][j])\n val = min(val, abs(matrix[i][j]))\n if matrix[i][j] < 0: mult ^= 1\n return ans - 2*mult*val", "slug": "maximum-matrix-sum", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 12, "views": 581, "problem_title": "maximum matrix sum", "number": 1975, "acceptance": 0.457, "difficulty": "Medium", "__index_level_0__": 27647, "question": "You are given an n x n integer matrix. You can do the following operation any number of times:\nChoose any two adjacent elements of matrix and multiply each of them by -1.\nTwo elements are considered adjacent if and only if they share a border.\nYour goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.\n Example 1:\nInput: matrix = [[1,-1],[-1,1]]\nOutput: 4\nExplanation: We can follow the following steps to reach sum equals 4:\n- Multiply the 2 elements in the first row by -1.\n- Multiply the 2 elements in the first column by -1.\nExample 2:\nInput: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\nOutput: 16\nExplanation: We can follow the following step to reach sum equals 16:\n- Multiply the 2 last elements in the second row by -1.\n Constraints:\nn == matrix.length == matrix[i].length\n2 <= n <= 250\n-105 <= matrix[i][j] <= 105" }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-arrive-at-destination/discuss/1417598/Python3-dfs-%2B-dp", "python_solutions": "class Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n graph = {}\n for u, v, time in roads: \n graph.setdefault(u, {})[v] = time\n graph.setdefault(v, {})[u] = time\n \n dist = [inf]*n\n dist[-1] = 0\n stack = [(n-1, 0)]\n while stack: \n x, t = stack.pop()\n if t == dist[x]: \n for xx in graph.get(x, {}): \n if t + graph[x][xx] < dist[xx]: \n dist[xx] = t + graph[x][xx]\n stack.append((xx, t + graph[x][xx]))\n \n @cache\n def fn(x):\n \"\"\"Return \"\"\"\n if x == n-1: return 1 \n if dist[x] == inf: return 0 \n ans = 0 \n for xx in graph.get(x, {}): \n if graph[x][xx] + dist[xx] == dist[x]: ans += fn(xx)\n return ans % 1_000_000_007\n \n return fn(0)", "slug": "number-of-ways-to-arrive-at-destination", "post_title": "[Python3] dfs + dp", "user": "ye15", "upvotes": 5, "views": 846, "problem_title": "number of ways to arrive at destination", "number": 1976, "acceptance": 0.3229999999999999, "difficulty": "Medium", "__index_level_0__": 27653, "question": "You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.\nYou are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.\nReturn the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\nInput: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]\nOutput: 4\nExplanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\nThe four ways to get there in 7 minutes are:\n- 0 \u279d 6\n- 0 \u279d 4 \u279d 6\n- 0 \u279d 1 \u279d 2 \u279d 5 \u279d 6\n- 0 \u279d 1 \u279d 3 \u279d 5 \u279d 6\nExample 2:\nInput: n = 2, roads = [[1,0,10]]\nOutput: 1\nExplanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n Constraints:\n1 <= n <= 200\nn - 1 <= roads.length <= n * (n - 1) / 2\nroads[i].length == 3\n0 <= ui, vi <= n - 1\n1 <= timei <= 109\nui != vi\nThere is at most one road connecting any two intersections.\nYou can reach any intersection from any other intersection." }, { "post_href": "https://leetcode.com/problems/number-of-ways-to-separate-numbers/discuss/1424057/Python3-dp", "python_solutions": "class Solution:\n def numberOfCombinations(self, num: str) -> int:\n n = len(num)\n lcs = [[0]*(n+1) for _ in range(n)]\n for i in reversed(range(n)): \n for j in reversed(range(i+1, n)): \n if num[i] == num[j]: lcs[i][j] = 1 + lcs[i+1][j+1]\n \n def cmp(i, j, d): \n \"\"\"Return True if \"\"\"\n m = lcs[i][j]\n if m >= d: return True \n return num[i+m] <= num[j+m]\n \n dp = [[0]*(n+1) for _ in range(n)]\n for i in range(n): \n if num[i] != \"0\": \n for j in range(i+1, n+1): \n if i == 0: dp[i][j] = 1\n else: \n dp[i][j] = dp[i][j-1]\n if 2*i-j >= 0 and cmp(2*i-j, i, j-i): dp[i][j] += dp[2*i-j][i]\n if 2*i-j+1 >= 0 and not cmp(2*i-j+1, i, j-i-1): dp[i][j] += dp[2*i-j+1][i]\n return sum(dp[i][n] for i in range(n)) % 1_000_000_007", "slug": "number-of-ways-to-separate-numbers", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 3, "views": 367, "problem_title": "number of ways to separate numbers", "number": 1977, "acceptance": 0.209, "difficulty": "Hard", "__index_level_0__": 27660, "question": "You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros.\nReturn the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\nInput: num = \"327\"\nOutput: 2\nExplanation: You could have written down the numbers:\n3, 27\n327\nExample 2:\nInput: num = \"094\"\nOutput: 0\nExplanation: No numbers can have leading zeros and all numbers must be positive.\nExample 3:\nInput: num = \"0\"\nOutput: 0\nExplanation: No numbers can have leading zeros and all numbers must be positive.\n Constraints:\n1 <= num.length <= 3500\nnum consists of digits '0' through '9'." }, { "post_href": "https://leetcode.com/problems/find-greatest-common-divisor-of-array/discuss/2580234/2-lines-PythonJavascript-(no-built-in-gcd-function)", "python_solutions": "class Solution:\n def findGCD(self, nums: List[int]) -> int:\n gcd = lambda a, b: a if b == 0 else gcd(b, a % b)\n return gcd(max(nums), min(nums))", "slug": "find-greatest-common-divisor-of-array", "post_title": "2 lines Python/Javascript (no built in gcd function)", "user": "SmittyWerbenjagermanjensen", "upvotes": 1, "views": 125, "problem_title": "find greatest common divisor of array", "number": 1979, "acceptance": 0.767, "difficulty": "Easy", "__index_level_0__": 27661, "question": "Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.\nThe greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.\n Example 1:\nInput: nums = [2,5,6,9,10]\nOutput: 2\nExplanation:\nThe smallest number in nums is 2.\nThe largest number in nums is 10.\nThe greatest common divisor of 2 and 10 is 2.\nExample 2:\nInput: nums = [7,5,6,8,3]\nOutput: 1\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 8.\nThe greatest common divisor of 3 and 8 is 1.\nExample 3:\nInput: nums = [3,3]\nOutput: 3\nExplanation:\nThe smallest number in nums is 3.\nThe largest number in nums is 3.\nThe greatest common divisor of 3 and 3 is 3.\n Constraints:\n2 <= nums.length <= 1000\n1 <= nums[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/find-unique-binary-string/discuss/1657090/One-line-python-Solution", "python_solutions": "class Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n return list(set(list((map(lambda x:\"\".join(list(map(str,x))),list(itertools.product([0,1],repeat=len(nums)))))))-set(nums))[0]", "slug": "find-unique-binary-string", "post_title": "One line python Solution", "user": "amannarayansingh10", "upvotes": 2, "views": 159, "problem_title": "find unique binary string", "number": 1980, "acceptance": 0.643, "difficulty": "Medium", "__index_level_0__": 27687, "question": "Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.\n Example 1:\nInput: nums = [\"01\",\"10\"]\nOutput: \"11\"\nExplanation: \"11\" does not appear in nums. \"00\" would also be correct.\nExample 2:\nInput: nums = [\"00\",\"01\"]\nOutput: \"11\"\nExplanation: \"11\" does not appear in nums. \"10\" would also be correct.\nExample 3:\nInput: nums = [\"111\",\"011\",\"001\"]\nOutput: \"101\"\nExplanation: \"101\" does not appear in nums. \"000\", \"010\", \"100\", and \"110\" would also be correct.\n Constraints:\nn == nums.length\n1 <= n <= 16\nnums[i].length == n\nnums[i] is either '0' or '1'.\nAll the strings of nums are unique." }, { "post_href": "https://leetcode.com/problems/minimize-the-difference-between-target-and-chosen-elements/discuss/1418634/100-efficient-or-Pruning-%2B-Memoization-or-Dynamic-Programming-or-Explanation", "python_solutions": "class Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n # store the mxn size of the matrix\n m = len(mat)\n n = len(mat[0])\n \n dp = defaultdict(defaultdict)\n \n # Sorting each row of the array for more efficient pruning\n # Note:this purely based on the observation on problem constraints (although interesting :))\n for i in range(m):\n mat[i] = sorted(mat[i])\n \n # returns minimum absolute starting from from row i to n-1 for the target\n globalMin = float(\"inf\")\n def findMinAbsDiff(i,prevSum):\n nonlocal globalMin\n if i == m:\n globalMin = min(globalMin, abs(prevSum-target))\n return abs(prevSum-target)\n \n # pruning step 1\n # because the array is increasing & prevSum & target will always be positive\n if prevSum-target > globalMin:\n return float(\"inf\")\n \n \n if (i in dp) and (prevSum in dp[i]):\n return dp[i][prevSum]\n \n minDiff = float(\"inf\")\n # for each candidate select that and backtrack\n for j in range(n):\n diff = findMinAbsDiff(i+1, prevSum+mat[i][j])\n # pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL\n if diff == 0:\n minDiff = 0\n break\n minDiff = min(minDiff, diff)\n \n dp[i][prevSum] = minDiff\n return minDiff\n \n return findMinAbsDiff(0, 0)", "slug": "minimize-the-difference-between-target-and-chosen-elements", "post_title": "\u2705 100% efficient | Pruning + Memoization | Dynamic Programming | Explanation", "user": "CaptainX", "upvotes": 24, "views": 2200, "problem_title": "minimize the difference between target and chosen elements", "number": 1981, "acceptance": 0.3229999999999999, "difficulty": "Medium", "__index_level_0__": 27714, "question": "You are given an m x n integer matrix mat and an integer target.\nChoose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.\nReturn the minimum absolute difference.\nThe absolute difference between two numbers a and b is the absolute value of a - b.\n Example 1:\nInput: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\nOutput: 0\nExplanation: One possible choice is to:\n- Choose 1 from the first row.\n- Choose 5 from the second row.\n- Choose 7 from the third row.\nThe sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.\nExample 2:\nInput: mat = [[1],[2],[3]], target = 100\nOutput: 94\nExplanation: The best possible choice is to:\n- Choose 1 from the first row.\n- Choose 2 from the second row.\n- Choose 3 from the third row.\nThe sum of the chosen elements is 6, and the absolute difference is 94.\nExample 3:\nInput: mat = [[1,2,9,8,7]], target = 6\nOutput: 1\nExplanation: The best choice is to choose 7 from the first row.\nThe absolute difference is 1.\n Constraints:\nm == mat.length\nn == mat[i].length\n1 <= m, n <= 70\n1 <= mat[i][j] <= 70\n1 <= target <= 800" }, { "post_href": "https://leetcode.com/problems/find-array-given-subset-sums/discuss/1431457/Easy-Explanation-for-Noobs-%2B-Python-code-with-comments", "python_solutions": "class Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n res = [] # Result set\n sums.sort()\n \n while len(sums) > 1:\n num = sums[-1] - sums[-2] # max - secondMax\n countMap = Counter(sums) # Get count of each elements\n excluding = [] # Subset sums that do NOT contain num\n including = [] # Subset sums that contain num\n \n for x in sums:\n if countMap.get(x) > 0:\n excluding.append(x)\n including.append(x+num)\n countMap[x] -= 1\n countMap[x+num] -= 1\n \n\t\t\t# Check validity of excluding set\t\n if 0 in excluding:\n sums = excluding\n res.append(num)\n else:\n sums = including\n res.append(-1*num)\n \n return res", "slug": "find-array-given-subset-sums", "post_title": "Easy Explanation for Noobs + Python code with comments", "user": "sumit686215", "upvotes": 57, "views": 1500, "problem_title": "find array given subset sums", "number": 1982, "acceptance": 0.489, "difficulty": "Hard", "__index_level_0__": 27718, "question": "You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order).\nReturn the array ans of length n representing the unknown array. If multiple answers exist, return any of them.\nAn array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0.\nNote: Test cases are generated such that there will always be at least one correct answer.\n Example 1:\nInput: n = 3, sums = [-3,-2,-1,0,0,1,2,3]\nOutput: [1,2,-3]\nExplanation: [1,2,-3] is able to achieve the given subset sums:\n- []: sum is 0\n- [1]: sum is 1\n- [2]: sum is 2\n- [1,2]: sum is 3\n- [-3]: sum is -3\n- [1,-3]: sum is -2\n- [2,-3]: sum is -1\n- [1,2,-3]: sum is 0\nNote that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.\nExample 2:\nInput: n = 2, sums = [0,0,0,0]\nOutput: [0,0]\nExplanation: The only correct answer is [0,0].\nExample 3:\nInput: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\nOutput: [0,-1,4,5]\nExplanation: [0,-1,4,5] is able to achieve the given subset sums.\n Constraints:\n1 <= n <= 15\nsums.length == 2n\n-104 <= sums[i] <= 104" }, { "post_href": "https://leetcode.com/problems/minimum-difference-between-highest-and-lowest-of-k-scores/discuss/1433298/Python3-greedy-2-line", "python_solutions": "class Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min(nums[i+k-1]-nums[i] for i in range(len(nums)-k+1))", "slug": "minimum-difference-between-highest-and-lowest-of-k-scores", "post_title": "[Python3] greedy 2-line", "user": "ye15", "upvotes": 2, "views": 151, "problem_title": "minimum difference between highest and lowest of k scores", "number": 1984, "acceptance": 0.536, "difficulty": "Easy", "__index_level_0__": 27720, "question": "You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k.\nPick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized.\nReturn the minimum possible difference.\n Example 1:\nInput: nums = [90], k = 1\nOutput: 0\nExplanation: There is one way to pick score(s) of one student:\n- [90]. The difference between the highest and lowest score is 90 - 90 = 0.\nThe minimum possible difference is 0.\nExample 2:\nInput: nums = [9,4,1,7], k = 2\nOutput: 2\nExplanation: There are six ways to pick score(s) of two students:\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 1 = 8.\n- [9,4,1,7]. The difference between the highest and lowest score is 9 - 7 = 2.\n- [9,4,1,7]. The difference between the highest and lowest score is 4 - 1 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 4 = 3.\n- [9,4,1,7]. The difference between the highest and lowest score is 7 - 1 = 6.\nThe minimum possible difference is 2.\n Constraints:\n1 <= k <= nums.length <= 1000\n0 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/find-the-kth-largest-integer-in-the-array/discuss/1432093/Python-or-The-Right-Way-during-Interview-or-Comparators", "python_solutions": "class Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n nums = sorted(map(int, nums), reverse=True)\n return str(nums[k-1])", "slug": "find-the-kth-largest-integer-in-the-array", "post_title": "Python | The Right Way during Interview | Comparators", "user": "malraharsh", "upvotes": 28, "views": 1800, "problem_title": "find the kth largest integer in the array", "number": 1985, "acceptance": 0.447, "difficulty": "Medium", "__index_level_0__": 27738, "question": "You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.\nReturn the string that represents the kth largest integer in nums.\nNote: Duplicate numbers should be counted distinctly. For example, if nums is [\"1\",\"2\",\"2\"], \"2\" is the first largest integer, \"2\" is the second-largest integer, and \"1\" is the third-largest integer.\n Example 1:\nInput: nums = [\"3\",\"6\",\"7\",\"10\"], k = 4\nOutput: \"3\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\nThe 4th largest integer in nums is \"3\".\nExample 2:\nInput: nums = [\"2\",\"21\",\"12\",\"1\"], k = 3\nOutput: \"2\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\nThe 3rd largest integer in nums is \"2\".\nExample 3:\nInput: nums = [\"0\",\"0\"], k = 2\nOutput: \"0\"\nExplanation:\nThe numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\nThe 2nd largest integer in nums is \"0\".\n Constraints:\n1 <= k <= nums.length <= 104\n1 <= nums[i].length <= 100\nnums[i] consists of only digits.\nnums[i] will not have any leading zeros." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-work-sessions-to-finish-the-tasks/discuss/1433054/Python-or-Backtracking-or-664ms-or-100-time-and-space-or-Explanation", "python_solutions": "class Solution:\n def minSessions(self, tasks: List[int], sessionTime: int) -> int:\n subsets = []\n self.ans = len(tasks)\n \n def func(idx):\n if len(subsets) >= self.ans:\n return\n \n if idx == len(tasks):\n self.ans = min(self.ans, len(subsets))\n return\n \n for i in range(len(subsets)):\n if subsets[i] + tasks[idx] <= sessionTime:\n subsets[i] += tasks[idx]\n func(idx + 1)\n subsets[i] -= tasks[idx]\n \n subsets.append(tasks[idx])\n func(idx + 1)\n subsets.pop()\n \n func(0)\n return self.ans", "slug": "minimum-number-of-work-sessions-to-finish-the-tasks", "post_title": "Python | Backtracking | 664ms | 100% time and space | Explanation", "user": "detective_dp", "upvotes": 22, "views": 1000, "problem_title": "minimum number of work sessions to finish the tasks", "number": 1986, "acceptance": 0.331, "difficulty": "Medium", "__index_level_0__": 27760, "question": "There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break.\nYou should finish the given tasks in a way that satisfies the following conditions:\nIf you start a task in a work session, you must complete it in the same work session.\nYou can start a new task immediately after finishing the previous one.\nYou may complete the tasks in any order.\nGiven tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.\nThe tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].\n Example 1:\nInput: tasks = [1,2,3], sessionTime = 3\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n- Second work session: finish the third task in 3 hours.\nExample 2:\nInput: tasks = [3,1,3,1,1], sessionTime = 8\nOutput: 2\nExplanation: You can finish the tasks in two work sessions.\n- First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n- Second work session: finish the last task in 1 hour.\nExample 3:\nInput: tasks = [1,2,3,4,5], sessionTime = 15\nOutput: 1\nExplanation: You can finish all the tasks in one work session.\n Constraints:\nn == tasks.length\n1 <= n <= 14\n1 <= tasks[i] <= 10\nmax(tasks[i]) <= sessionTime <= 15" }, { "post_href": "https://leetcode.com/problems/number-of-unique-good-subsequences/discuss/1433355/Python3-bit-mask-dp", "python_solutions": "class Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n \n @cache\n def fn(i, mask, v): \n \"\"\"Return # unique good subsequences starting with 1.\"\"\"\n if i == len(binary) or not mask: return v\n x = int(binary[i])\n if not mask & (1< int:\n left = 0 # nums[0] + nums[1] + ... + nums[middleIndex-1]\n right = sum(nums) # nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]\n\n for i, num in enumerate(nums): # we can use normal for loop as well.\n right -= num # as we are trying to find out middle index so iteratively we`ll reduce the value of right to find the middle index\n if left == right: # comparing the values for finding out the middle index.\n return i # if there is any return the index whixh will be our required index.\n left += num # we have to add the num iteratively. \n\n return -1", "slug": "find-the-middle-index-in-array", "post_title": "Python 98.85% faster | Simplest solution with explanation | Beg to Adv | Prefix Sum", "user": "rlakshay14", "upvotes": 8, "views": 224, "problem_title": "find the middle index in array", "number": 1991, "acceptance": 0.6729999999999999, "difficulty": "Easy", "__index_level_0__": 27770, "question": "Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).\nA middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].\nIf middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0.\nReturn the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.\n Example 1:\nInput: nums = [2,3,-1,8,4]\nOutput: 3\nExplanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\nThe sum of the numbers after index 3 is: 4 = 4\nExample 2:\nInput: nums = [1,-1,4]\nOutput: 2\nExplanation: The sum of the numbers before index 2 is: 1 + -1 = 0\nThe sum of the numbers after index 2 is: 0\nExample 3:\nInput: nums = [2,5]\nOutput: -1\nExplanation: There is no valid middleIndex.\n Constraints:\n1 <= nums.length <= 100\n-1000 <= nums[i] <= 1000\n Note: This question is the same as 724: https://leetcode.com/problems/find-pivot-index/" }, { "post_href": "https://leetcode.com/problems/find-all-groups-of-farmland/discuss/1444115/Python3-dfs", "python_solutions": "class Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n m, n = len(land), len(land[0])\n ans = []\n for i in range(m):\n for j in range(n): \n if land[i][j]: # found farmland\n mini, minj = i, j \n maxi, maxj = i, j \n stack = [(i, j)]\n land[i][j] = 0 # mark as visited \n while stack: \n i, j = stack.pop()\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and land[ii][jj]: \n stack.append((ii, jj))\n land[ii][jj] = 0 \n maxi = max(maxi, ii)\n maxj = max(maxj, jj)\n ans.append([mini, minj, maxi, maxj])\n return ans", "slug": "find-all-groups-of-farmland", "post_title": "[Python3] dfs", "user": "ye15", "upvotes": 5, "views": 207, "problem_title": "find all groups of farmland", "number": 1992, "acceptance": 0.687, "difficulty": "Medium", "__index_level_0__": 27804, "question": "You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland.\nTo keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group.\nland can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2].\nReturn a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.\n Example 1:\nInput: land = [[1,0,0],[0,1,1],[0,1,1]]\nOutput: [[0,0,0,0],[1,1,2,2]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\nThe second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].\nExample 2:\nInput: land = [[1,1],[1,1]]\nOutput: [[0,0,1,1]]\nExplanation:\nThe first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].\nExample 3:\nInput: land = [[0]]\nOutput: []\nExplanation:\nThere are no groups of farmland.\n Constraints:\nm == land.length\nn == land[i].length\n1 <= m, n <= 300\nland consists of only 0's and 1's.\nGroups of farmland are rectangular in shape." }, { "post_href": "https://leetcode.com/problems/the-number-of-good-subsets/discuss/1444318/Python3-dp", "python_solutions": "class Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n freq = [0] * 31\n for x in nums: freq[x] += 1\n \n masks = [0] * 31\n for x in range(1, 31): \n if x == 1: masks[x] = 0b10\n else: \n bits = 0\n xx = x\n for k in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29): \n while xx % k == 0: \n if (bits >> k) & 1: break # repeated factors \n bits ^= 1 << k\n xx //= k\n else: continue \n break \n else: masks[x] = bits\n \n @cache\n def fn(x, m): \n \"\"\"Return number of good subsets.\"\"\"\n if x == 31: return int(m > 2)\n ans = fn(x+1, m)\n if freq[x] and masks[x]: \n if x == 1: ans *= 2**freq[x]\n elif not m & masks[x]: ans += freq[x] * fn(x+1, m | masks[x])\n return ans % 1_000_000_007\n \n return fn(1, 0)", "slug": "the-number-of-good-subsets", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 2, "views": 203, "problem_title": "the number of good subsets", "number": 1994, "acceptance": 0.344, "difficulty": "Hard", "__index_level_0__": 27820, "question": "You are given an integer array nums. We call a subset of nums good if its product can be represented as a product of one or more distinct prime numbers.\nFor example, if nums = [1, 2, 3, 4]:\n[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.\n[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.\nReturn the number of different good subsets in nums modulo 109 + 7.\nA subset of nums is any array that can be obtained by deleting some (possibly none or all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.\n Example 1:\nInput: nums = [1,2,3,4]\nOutput: 6\nExplanation: The good subsets are:\n- [1,2]: product is 2, which is the product of distinct prime 2.\n- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [1,3]: product is 3, which is the product of distinct prime 3.\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [3]: product is 3, which is the product of distinct prime 3.\nExample 2:\nInput: nums = [4,2,3,15]\nOutput: 5\nExplanation: The good subsets are:\n- [2]: product is 2, which is the product of distinct prime 2.\n- [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.\n- [3]: product is 3, which is the product of distinct prime 3.\n- [15]: product is 15, which is the product of distinct primes 3 and 5.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 30" }, { "post_href": "https://leetcode.com/problems/count-special-quadruplets/discuss/1445362/Python-non-brute-force.-Time%3A-O(N2)-Space%3A-O(N2)", "python_solutions": "class Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n idx = defaultdict(list)\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n idx[nums[j]-nums[i]].append(i)\n \n count = 0 \n for i in range(len(nums)-3):\n for j in range(i+1, len(nums)-2):\n count += sum(k > j for k in idx[nums[i]+nums[j]])\n \n return count", "slug": "count-special-quadruplets", "post_title": "Python, non-brute force. Time: O(N^2), Space: O(N^2)", "user": "blue_sky5", "upvotes": 4, "views": 729, "problem_title": "count special quadruplets", "number": 1995, "acceptance": 0.593, "difficulty": "Easy", "__index_level_0__": 27822, "question": "Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:\nnums[a] + nums[b] + nums[c] == nums[d], and\na < b < c < d\n Example 1:\nInput: nums = [1,2,3,6]\nOutput: 1\nExplanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.\nExample 2:\nInput: nums = [3,3,6,4,5]\nOutput: 0\nExplanation: There are no such quadruplets in [3,3,6,4,5].\nExample 3:\nInput: nums = [1,1,1,3,5]\nOutput: 4\nExplanation: The 4 quadruplets that satisfy the requirement are:\n- (0, 1, 2, 3): 1 + 1 + 1 == 3\n- (0, 1, 3, 4): 1 + 1 + 3 == 5\n- (0, 2, 3, 4): 1 + 1 + 3 == 5\n- (1, 2, 3, 4): 1 + 1 + 3 == 5\n Constraints:\n4 <= nums.length <= 50\n1 <= nums[i] <= 100" }, { "post_href": "https://leetcode.com/problems/the-number-of-weak-characters-in-the-game/discuss/1445198/Python-Sort", "python_solutions": "class Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \n properties.sort(key=lambda x: (-x[0],x[1]))\n \n ans = 0\n curr_max = 0\n \n for _, d in properties:\n if d < curr_max:\n ans += 1\n else:\n curr_max = d\n return ans", "slug": "the-number-of-weak-characters-in-the-game", "post_title": "Python - Sort", "user": "lokeshsenthilkumar", "upvotes": 209, "views": 9000, "problem_title": "the number of weak characters in the game", "number": 1996, "acceptance": 0.44, "difficulty": "Medium", "__index_level_0__": 27837, "question": "You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game.\nA character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei.\nReturn the number of weak characters.\n Example 1:\nInput: properties = [[5,5],[6,3],[3,6]]\nOutput: 0\nExplanation: No character has strictly greater attack and defense than the other.\nExample 2:\nInput: properties = [[2,2],[3,3]]\nOutput: 1\nExplanation: The first character is weak because the second character has a strictly greater attack and defense.\nExample 3:\nInput: properties = [[1,5],[10,4],[4,3]]\nOutput: 1\nExplanation: The third character is weak because the second character has a strictly greater attack and defense.\n Constraints:\n2 <= properties.length <= 105\nproperties[i].length == 2\n1 <= attacki, defensei <= 105" }, { "post_href": "https://leetcode.com/problems/first-day-where-you-have-been-in-all-the-rooms/discuss/1446619/Python3-dp", "python_solutions": "class Solution:\n def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:\n odd = [0]\n even = [1]\n for i in range(1, len(nextVisit)): \n odd.append((even[-1] + 1) % 1_000_000_007)\n even.append((2*odd[-1] - odd[nextVisit[i]] + 1) % 1_000_000_007)\n return odd[-1]", "slug": "first-day-where-you-have-been-in-all-the-rooms", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 3, "views": 139, "problem_title": "first day where you have been in all the rooms", "number": 1997, "acceptance": 0.367, "difficulty": "Medium", "__index_level_0__": 27870, "question": "There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.\nInitially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:\nAssuming that on a day, you visit room i,\nif you have been in room i an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i;\nif you have been in room i an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n.\nReturn the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\nInput: nextVisit = [0,0]\nOutput: 2\nExplanation:\n- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.\n On the next day you will visit room nextVisit[0] = 0\n- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.\n On the next day you will visit room (0 + 1) mod 2 = 1\n- On day 2, you visit room 1. This is the first day where you have been in all the rooms.\nExample 2:\nInput: nextVisit = [0,0,2]\nOutput: 6\nExplanation:\nYour room visiting order for each day is: [0,0,1,0,0,1,2,...].\nDay 6 is the first day where you have been in all the rooms.\nExample 3:\nInput: nextVisit = [0,1,2,0]\nOutput: 6\nExplanation:\nYour room visiting order for each day is: [0,0,1,1,2,2,3,...].\nDay 6 is the first day where you have been in all the rooms.\n Constraints:\nn == nextVisit.length\n2 <= n <= 105\n0 <= nextVisit[i] <= i" }, { "post_href": "https://leetcode.com/problems/reverse-prefix-of-word/discuss/1472737/Easy-Python-Solution-(28ms)-or-Faster-than-93", "python_solutions": "class Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n try:\n ix = word.index(ch)\n return word[:ix+1][::-1] + word[ix+1:]\n except ValueError:\n return word", "slug": "reverse-prefix-of-word", "post_title": "Easy Python Solution (28ms) | Faster than 93%", "user": "the_sky_high", "upvotes": 6, "views": 506, "problem_title": "reverse prefix of word", "number": 2000, "acceptance": 0.778, "difficulty": "Easy", "__index_level_0__": 27875, "question": "Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.\nFor example, if word = \"abcdefd\" and ch = \"d\", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be \"dcbaefd\".\nReturn the resulting string.\n Example 1:\nInput: word = \"abcdefd\", ch = \"d\"\nOutput: \"dcbaefd\"\nExplanation: The first occurrence of \"d\" is at index 3. \nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".\nExample 2:\nInput: word = \"xyxzxe\", ch = \"z\"\nOutput: \"zxyxxe\"\nExplanation: The first and only occurrence of \"z\" is at index 3.\nReverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".\nExample 3:\nInput: word = \"abcd\", ch = \"z\"\nOutput: \"abcd\"\nExplanation: \"z\" does not exist in word.\nYou should not do any reverse operation, the resulting string is \"abcd\".\n Constraints:\n1 <= word.length <= 250\nword consists of lowercase English letters.\nch is a lowercase English letter." }, { "post_href": "https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/discuss/2818774/O(n)-solution-of-Combined-Dictionary-and-Pre-sum-in-Python", "python_solutions": "class Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n preSum = []\n for rec in rectangles:\n preSum.append(rec[1]/rec[0])\n \n dic1 = {}\n for i in range(len(preSum)-1, -1, -1):\n if preSum[i] not in dic1.keys():\n dic1[preSum[i]] = [0,1]\n else:\n dic1[preSum[i]][0] = dic1[preSum[i]][0] + dic1[preSum[i]][1]\n dic1[preSum[i]][1] += 1\n \n return sum ([v[0] for v in dic1.values()])", "slug": "number-of-pairs-of-interchangeable-rectangles", "post_title": "O(n) solution of Combined Dictionary and Pre sum in Python", "user": "DNST", "upvotes": 0, "views": 3, "problem_title": "number of pairs of interchangeable rectangles", "number": 2001, "acceptance": 0.451, "difficulty": "Medium", "__index_level_0__": 27917, "question": "You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.\nTwo rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).\nReturn the number of pairs of interchangeable rectangles in rectangles.\n Example 1:\nInput: rectangles = [[4,8],[3,6],[10,20],[15,30]]\nOutput: 6\nExplanation: The following are the interchangeable pairs of rectangles by index (0-indexed):\n- Rectangle 0 with rectangle 1: 4/8 == 3/6.\n- Rectangle 0 with rectangle 2: 4/8 == 10/20.\n- Rectangle 0 with rectangle 3: 4/8 == 15/30.\n- Rectangle 1 with rectangle 2: 3/6 == 10/20.\n- Rectangle 1 with rectangle 3: 3/6 == 15/30.\n- Rectangle 2 with rectangle 3: 10/20 == 15/30.\nExample 2:\nInput: rectangles = [[4,5],[7,8]]\nOutput: 0\nExplanation: There are no interchangeable pairs of rectangles.\n Constraints:\nn == rectangles.length\n1 <= n <= 105\nrectangles[i].length == 2\n1 <= widthi, heighti <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-product-of-the-length-of-two-palindromic-subsequences/discuss/1458484/Python-Bruteforce", "python_solutions": "class Solution:\n def maxProduct(self, s: str) -> int:\n subs = []\n n = len(s)\n def dfs(curr, ind, inds):\n if ind == n:\n if curr == curr[::-1]:\n subs.append((curr, inds))\n return\n dfs(curr+s[ind], ind+1, inds|{ind})\n dfs(curr, ind+1, inds)\n \n dfs('', 0, set())\n \n res = 0\n n = len(subs)\n for i in range(n):\n s1, i1 = subs[i]\n for j in range(i+1, n):\n s2, i2 = subs[j]\n if len(i1 & i2) == 0:\n res = max(res, len(s1)*len(s2))\n return res", "slug": "maximum-product-of-the-length-of-two-palindromic-subsequences", "post_title": "Python - Bruteforce", "user": "ajith6198", "upvotes": 3, "views": 232, "problem_title": "maximum product of the length of two palindromic subsequences", "number": 2002, "acceptance": 0.5329999999999999, "difficulty": "Medium", "__index_level_0__": 27929, "question": "Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index.\nReturn the maximum possible product of the lengths of the two palindromic subsequences.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.\n Example 1:\nInput: s = \"leetcodecom\"\nOutput: 9\nExplanation: An optimal solution is to choose \"ete\" for the 1st subsequence and \"cdc\" for the 2nd subsequence.\nThe product of their lengths is: 3 * 3 = 9.\nExample 2:\nInput: s = \"bb\"\nOutput: 1\nExplanation: An optimal solution is to choose \"b\" (the first character) for the 1st subsequence and \"b\" (the second character) for the 2nd subsequence.\nThe product of their lengths is: 1 * 1 = 1.\nExample 3:\nInput: s = \"accbcaxxcxx\"\nOutput: 25\nExplanation: An optimal solution is to choose \"accca\" for the 1st subsequence and \"xxcxx\" for the 2nd subsequence.\nThe product of their lengths is: 5 * 5 = 25.\n Constraints:\n2 <= s.length <= 12\ns consists of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/discuss/1461767/Python3-dfs", "python_solutions": "class Solution:\n def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n ans = [1] * len(parents)\n if 1 in nums: \n tree = {}\n for i, x in enumerate(parents): \n tree.setdefault(x, []).append(i)\n \n k = nums.index(1)\n val = 1\n seen = set()\n \n while k != -1: \n stack = [k]\n while stack: \n x = stack.pop()\n seen.add(nums[x])\n for xx in tree.get(x, []): \n if nums[xx] not in seen: \n stack.append(xx)\n seen.add(nums[xx])\n while val in seen: val += 1\n ans[k] = val\n k = parents[k]\n return ans", "slug": "smallest-missing-genetic-value-in-each-subtree", "post_title": "[Python3] dfs", "user": "ye15", "upvotes": 0, "views": 89, "problem_title": "smallest missing genetic value in each subtree", "number": 2003, "acceptance": 0.4429999999999999, "difficulty": "Hard", "__index_level_0__": 27936, "question": "There is a family tree rooted at 0 consisting of n nodes numbered 0 to n - 1. You are given a 0-indexed integer array parents, where parents[i] is the parent for node i. Since node 0 is the root, parents[0] == -1.\nThere are 105 genetic values, each represented by an integer in the inclusive range [1, 105]. You are given a 0-indexed integer array nums, where nums[i] is a distinct genetic value for node i.\nReturn an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.\nThe subtree rooted at a node x contains node x and all of its descendant nodes.\n Example 1:\nInput: parents = [-1,0,0,2], nums = [1,2,3,4]\nOutput: [5,1,1,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.\nExample 2:\nInput: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\nOutput: [7,1,1,4,2,1]\nExplanation: The answer for each subtree is calculated as follows:\n- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.\nExample 3:\nInput: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\nOutput: [1,1,1,1,1,1,1]\nExplanation: The value 1 is missing from all the subtrees.\n Constraints:\nn == parents.length == nums.length\n2 <= n <= 105\n0 <= parents[i] <= n - 1 for i != 0\nparents[0] == -1\nparents represents a valid tree.\n1 <= nums[i] <= 105\nEach nums[i] is distinct." }, { "post_href": "https://leetcode.com/problems/count-number-of-pairs-with-absolute-difference-k/discuss/1471015/Python-Clean-and-concise.-Dictionary-T.C-O(N)", "python_solutions": "class Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n tmp, tmp2 = num - k, num + k\n if tmp in seen:\n counter += seen[tmp]\n if tmp2 in seen:\n counter += seen[tmp2]\n \n seen[num] += 1\n \n return counter", "slug": "count-number-of-pairs-with-absolute-difference-k", "post_title": "[Python] Clean & concise. Dictionary T.C O(N)", "user": "asbefu", "upvotes": 36, "views": 3700, "problem_title": "count number of pairs with absolute difference k", "number": 2006, "acceptance": 0.823, "difficulty": "Easy", "__index_level_0__": 27937, "question": "Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k.\nThe value of |x| is defined as:\nx if x >= 0.\n-x if x < 0.\n Example 1:\nInput: nums = [1,2,2,1], k = 1\nOutput: 4\nExplanation: The pairs with an absolute difference of 1 are:\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\n- [1,2,2,1]\nExample 2:\nInput: nums = [1,3], k = 3\nOutput: 0\nExplanation: There are no pairs with an absolute difference of 3.\nExample 3:\nInput: nums = [3,2,1,5,4], k = 2\nOutput: 3\nExplanation: The pairs with an absolute difference of 2 are:\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n- [3,2,1,5,4]\n Constraints:\n1 <= nums.length <= 200\n1 <= nums[i] <= 100\n1 <= k <= 99" }, { "post_href": "https://leetcode.com/problems/find-original-array-from-doubled-array/discuss/1470895/Python-Sorting.-Easy-to-understand-and-clean-T.C%3A-O(n-log-n)-S.C%3A-O(N)", "python_solutions": "class Solution:\n def findOriginalArray(self, changed: List[int]) -> List[int]:\n \n \"\"\"\n The idea is to:\n 1st sort the numbers\n 2nd Create a counter to save the frequency of each number\n 3nd iterate the array and for each number check if the double exists.\n 4rd after taking len(changed) // 2 numbers return the answer\n \n Time complexity: O(nlog(n)) \n Space complexity: O(n)\n \n \"\"\"\n \n \n if len(changed) % 2 != 0: # If there are not even amount the numbers there is no solution.\n return []\n \n changed.sort()\n \n c = Counter(changed) # The counter is needed because we have 0s\n \n answer = []\n for num in changed:\n if num in c and c[num] >= 1: # Check if the number is available (we may have taken it before)\n c[num] -= 1 # we mark the number as used by decreasing the counter (only needed for the zeros)\n if (num * 2) in c and c[(num * 2)] >= 1: # Take the one that doubles it if exists\n answer.append(num)\n c[num*2] -= 1 # The number has been taken.\n \n if len(answer) == len(changed) // 2:\n return answer\n \n return []", "slug": "find-original-array-from-doubled-array", "post_title": "[Python] Sorting. Easy to understand and clean T.C: O(n log n) S.C: O(N)", "user": "asbefu", "upvotes": 13, "views": 981, "problem_title": "find original array from doubled array", "number": 2007, "acceptance": 0.409, "difficulty": "Medium", "__index_level_0__": 27983, "question": "An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array.\nGiven an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.\n Example 1:\nInput: changed = [1,3,4,2,6,8]\nOutput: [1,3,4]\nExplanation: One possible original array could be [1,3,4]:\n- Twice the value of 1 is 1 * 2 = 2.\n- Twice the value of 3 is 3 * 2 = 6.\n- Twice the value of 4 is 4 * 2 = 8.\nOther original arrays could be [4,3,1] or [3,1,4].\nExample 2:\nInput: changed = [6,3,0,1]\nOutput: []\nExplanation: changed is not a doubled array.\nExample 3:\nInput: changed = [1]\nOutput: []\nExplanation: changed is not a doubled array.\n Constraints:\n1 <= changed.length <= 105\n0 <= changed[i] <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-earnings-from-taxi/discuss/1485339/Python-Solution-Maximum-Earnings-from-Taxi", "python_solutions": "class Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:\n \n d = {}\n for start,end,tip in rides:\n if end not in d:\n d[end] =[[start,tip]]\n else:\n d[end].append([start,tip])\n \n \n dp = [0]*(n+1)\n dp[0] = 0\n \n for i in range(1,n+1):\n dp[i] = dp[i-1]\n if i in d:\n temp_profit = 0\n for start,tip in d[i]:\n if (i-start)+tip+dp[start] > temp_profit:\n temp_profit = i-start+tip+dp[start]\n dp[i] = max(dp[i],temp_profit)\n \n \n return dp[-1]", "slug": "maximum-earnings-from-taxi", "post_title": "[Python] Solution - Maximum Earnings from Taxi", "user": "SaSha59", "upvotes": 2, "views": 2100, "problem_title": "maximum earnings from taxi", "number": 2008, "acceptance": 0.432, "difficulty": "Medium", "__index_level_0__": 28021, "question": "There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi.\nThe passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip.\nFor each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time.\nGiven n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally.\nNote: You may drop off a passenger and pick up a different passenger at the same point.\n Example 1:\nInput: n = 5, rides = [[2,5,4],[1,5,1]]\nOutput: 7\nExplanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.\nExample 2:\nInput: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\nOutput: 20\nExplanation: We will pick up the following passengers:\n- Drive passenger 1 from point 3 to point 10 for a profit of 10 - 3 + 2 = 9 dollars.\n- Drive passenger 2 from point 10 to point 12 for a profit of 12 - 10 + 3 = 5 dollars.\n- Drive passenger 5 from point 13 to point 18 for a profit of 18 - 13 + 1 = 6 dollars.\nWe earn 9 + 5 + 6 = 20 dollars in total.\n Constraints:\n1 <= n <= 105\n1 <= rides.length <= 3 * 104\nrides[i].length == 3\n1 <= starti < endi <= n\n1 <= tipi <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-make-array-continuous/discuss/1471593/Python3-sliding-window", "python_solutions": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n \n ans = ii = 0\n for i, x in enumerate(nums): \n if x - nums[ii] >= n: ii += 1\n ans = max(ans, i - ii + 1)\n return n - ans", "slug": "minimum-number-of-operations-to-make-array-continuous", "post_title": "[Python3] sliding window", "user": "ye15", "upvotes": 5, "views": 218, "problem_title": "minimum number of operations to make array continuous", "number": 2009, "acceptance": 0.4579999999999999, "difficulty": "Hard", "__index_level_0__": 28030, "question": "You are given an integer array nums. In one operation, you can replace any element in nums with any integer.\nnums is considered continuous if both of the following conditions are fulfilled:\nAll elements in nums are unique.\nThe difference between the maximum element and the minimum element in nums equals nums.length - 1.\nFor example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.\nReturn the minimum number of operations to make nums continuous.\n Example 1:\nInput: nums = [4,2,5,3]\nOutput: 0\nExplanation: nums is already continuous.\nExample 2:\nInput: nums = [1,2,3,5,6]\nOutput: 1\nExplanation: One possible solution is to change the last element to 4.\nThe resulting array is [1,2,3,5,4], which is continuous.\nExample 3:\nInput: nums = [1,10,100,1000]\nOutput: 3\nExplanation: One possible solution is to:\n- Change the second element to 2.\n- Change the third element to 3.\n- Change the fourth element to 4.\nThe resulting array is [1,2,3,4], which is continuous.\n Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/final-value-of-variable-after-performing-operations/discuss/1472568/Python3-A-Simple-Solution-and-A-One-Line-Solution", "python_solutions": "class Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n x = 0\n for o in operations:\n if '+' in o:\n x += 1\n else:\n x -= 1\n return x", "slug": "final-value-of-variable-after-performing-operations", "post_title": "[Python3] A Simple Solution and A One Line Solution", "user": "terrencetang", "upvotes": 18, "views": 1800, "problem_title": "final value of variable after performing operations", "number": 2011, "acceptance": 0.888, "difficulty": "Easy", "__index_level_0__": 28035, "question": "There is a programming language with only four operations and one variable X:\n++X and X++ increments the value of the variable X by 1.\n--X and X-- decrements the value of the variable X by 1.\nInitially, the value of X is 0.\nGiven an array of strings operations containing a list of operations, return the final value of X after performing all the operations.\n Example 1:\nInput: operations = [\"--X\",\"X++\",\"X++\"]\nOutput: 1\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n--X: X is decremented by 1, X = 0 - 1 = -1.\nX++: X is incremented by 1, X = -1 + 1 = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\nExample 2:\nInput: operations = [\"++X\",\"++X\",\"X++\"]\nOutput: 3\nExplanation: The operations are performed as follows:\nInitially, X = 0.\n++X: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\nX++: X is incremented by 1, X = 2 + 1 = 3.\nExample 3:\nInput: operations = [\"X++\",\"++X\",\"--X\",\"X--\"]\nOutput: 0\nExplanation: The operations are performed as follows:\nInitially, X = 0.\nX++: X is incremented by 1, X = 0 + 1 = 1.\n++X: X is incremented by 1, X = 1 + 1 = 2.\n--X: X is decremented by 1, X = 2 - 1 = 1.\nX--: X is decremented by 1, X = 1 - 1 = 0.\n Constraints:\n1 <= operations.length <= 100\noperations[i] will be either \"++X\", \"X++\", \"--X\", or \"X--\"." }, { "post_href": "https://leetcode.com/problems/sum-of-beauty-in-the-array/discuss/1477177/Python3-or-Brute-Force-(TLE)-and-O(n)-solution-with-explanation-or-86ile-runtime", "python_solutions": "class Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n beauty=[0]*len(nums)\n for i in range(1,len(nums)-1):\n leftarr=nums[:i]\n rightarr=nums[i+1:]\n if(max(leftarr)nums[i]):\n beauty[i]=2\n elif(nums[i-1]nums[i]):\n beauty[i]=1\n else:\n beauty[i]=0\n return sum(beauty)", "slug": "sum-of-beauty-in-the-array", "post_title": "Python3 | Brute Force (TLE) and O(n) solution with explanation | 86%ile runtime", "user": "aaditya47", "upvotes": 1, "views": 54, "problem_title": "sum of beauty in the array", "number": 2012, "acceptance": 0.467, "difficulty": "Medium", "__index_level_0__": 28091, "question": "You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:\n2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.\n1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.\n0, if none of the previous conditions holds.\nReturn the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.\n Example 1:\nInput: nums = [1,2,3]\nOutput: 2\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 2.\nExample 2:\nInput: nums = [2,4,6,4]\nOutput: 1\nExplanation: For each index i in the range 1 <= i <= 2:\n- The beauty of nums[1] equals 1.\n- The beauty of nums[2] equals 0.\nExample 3:\nInput: nums = [3,2,1]\nOutput: 0\nExplanation: For each index i in the range 1 <= i <= 1:\n- The beauty of nums[1] equals 0.\n Constraints:\n3 <= nums.length <= 105\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/longest-subsequence-repeated-k-times/discuss/1477019/Python3-bfs", "python_solutions": "class Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n freq = [0] * 26\n for ch in s: freq[ord(ch)-97] += 1\n \n cand = [chr(i+97) for i, x in enumerate(freq) if x >= k] # valid candidates \n \n def fn(ss): \n \"\"\"Return True if ss is a k-repeated sub-sequence of s.\"\"\"\n i = cnt = 0\n for ch in s: \n if ss[i] == ch: \n i += 1\n if i == len(ss): \n if (cnt := cnt + 1) == k: return True \n i = 0\n return False \n \n ans = \"\"\n queue = deque([\"\"])\n while queue: \n x = queue.popleft()\n for ch in cand: \n xx = x + ch\n if fn(xx): \n ans = xx\n queue.append(xx)\n return ans", "slug": "longest-subsequence-repeated-k-times", "post_title": "[Python3] bfs", "user": "ye15", "upvotes": 9, "views": 409, "problem_title": "longest subsequence repeated k times", "number": 2014, "acceptance": 0.556, "difficulty": "Hard", "__index_level_0__": 28101, "question": "You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\nA subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times.\nFor example, \"bba\" is repeated 2 times in the string \"bababcba\", because the string \"bbabba\", constructed by concatenating \"bba\" 2 times, is a subsequence of the string \"bababcba\".\nReturn the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.\n Example 1:\nInput: s = \"letsleetcode\", k = 2\nOutput: \"let\"\nExplanation: There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n\"let\" is the lexicographically largest one.\nExample 2:\nInput: s = \"bb\", k = 2\nOutput: \"b\"\nExplanation: The longest subsequence repeated 2 times is \"b\".\nExample 3:\nInput: s = \"ab\", k = 2\nOutput: \"\"\nExplanation: There is no subsequence repeated 2 times. Empty string is returned.\n Constraints:\nn == s.length\n2 <= n, k <= 2000\n2 <= n < k * 8\ns consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/maximum-difference-between-increasing-elements/discuss/1486318/Python3-prefix-min", "python_solutions": "class Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n ans = -1 \n prefix = inf\n for i, x in enumerate(nums): \n if i and x > prefix: ans = max(ans, x - prefix)\n prefix = min(prefix, x)\n return ans", "slug": "maximum-difference-between-increasing-elements", "post_title": "[Python3] prefix min", "user": "ye15", "upvotes": 6, "views": 557, "problem_title": "maximum difference between increasing elements", "number": 2016, "acceptance": 0.535, "difficulty": "Easy", "__index_level_0__": 28104, "question": "Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].\nReturn the maximum difference. If no such i and j exists, return -1.\n Example 1:\nInput: nums = [7,1,5,4]\nOutput: 4\nExplanation:\nThe maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\nNote that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.\nExample 2:\nInput: nums = [9,4,3,2]\nOutput: -1\nExplanation:\nThere is no i and j such that i < j and nums[i] < nums[j].\nExample 3:\nInput: nums = [1,5,2,10]\nOutput: 9\nExplanation:\nThe maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.\n Constraints:\nn == nums.length\n2 <= n <= 1000\n1 <= nums[i] <= 109" }, { "post_href": "https://leetcode.com/problems/grid-game/discuss/1486349/Python-Easy", "python_solutions": "class Solution(object):\n def gridGame(self, grid):\n \n top, bottom = grid\n top_sum = sum(top)\n bottom_sum = 0\n res = float('inf')\n \n for i in range(len(top)):\n top_sum -= top[i]\n res = min(res, max(top_sum, bottom_sum))\n bottom_sum += bottom[i]\n \n return res", "slug": "grid-game", "post_title": "Python - Easy", "user": "lokeshsenthilkumar", "upvotes": 3, "views": 181, "problem_title": "grid game", "number": 2017, "acceptance": 0.43, "difficulty": "Medium", "__index_level_0__": 28129, "question": "You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.\nBoth robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)).\nAt the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.\nThe first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.\n Example 1:\nInput: grid = [[2,5,4],[1,5,1]]\nOutput: 4\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 0 + 4 + 0 = 4 points.\nExample 2:\nInput: grid = [[3,3,1],[8,5,2]]\nOutput: 4\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 3 + 1 + 0 = 4 points.\nExample 3:\nInput: grid = [[1,3,1,15],[1,3,3,1]]\nOutput: 7\nExplanation: The optimal path taken by the first robot is shown in red, and the optimal path taken by the second robot is shown in blue.\nThe cells visited by the first robot are set to 0.\nThe second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.\n Constraints:\ngrid.length == 2\nn == grid[r].length\n1 <= n <= 5 * 104\n1 <= grid[r][c] <= 105" }, { "post_href": "https://leetcode.com/problems/check-if-word-can-be-placed-in-crossword/discuss/1486326/Python3-row-by-row-and-col-by-col", "python_solutions": "class Solution:\n def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:\n for x in board, zip(*board): \n for row in x: \n for s in \"\".join(row).split(\"#\"): \n for w in word, word[::-1]: \n if len(s) == len(w) and all(ss in (\" \", ww) for ss, ww in zip(s, w)): return True \n return False", "slug": "check-if-word-can-be-placed-in-crossword", "post_title": "[Python3] row-by-row & col-by-col", "user": "ye15", "upvotes": 10, "views": 1300, "problem_title": "check if word can be placed in crossword", "number": 2018, "acceptance": 0.494, "difficulty": "Medium", "__index_level_0__": 28137, "question": "You are given an m x n matrix board, representing the current state of a crossword puzzle. The crossword contains lowercase English letters (from solved words), ' ' to represent any empty cells, and '#' to represent any blocked cells.\nA word can be placed horizontally (left to right or right to left) or vertically (top to bottom or bottom to top) in the board if:\nIt does not occupy a cell containing the character '#'.\nThe cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.\nThere must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.\nThere must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.\nGiven a string word, return true if word can be placed in board, or false otherwise.\n Example 1:\nInput: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"\nOutput: true\nExplanation: The word \"abc\" can be placed as shown above (top to bottom).\nExample 2:\nInput: board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"\nOutput: false\nExplanation: It is impossible to place the word because there will always be a space/letter above or below it.\nExample 3:\nInput: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"\nOutput: true\nExplanation: The word \"ca\" can be placed as shown above (right to left). \n Constraints:\nm == board.length\nn == board[i].length\n1 <= m * n <= 2 * 105\nboard[i][j] will be ' ', '#', or a lowercase English letter.\n1 <= word.length <= max(m, n)\nword will contain only lowercase English letters." }, { "post_href": "https://leetcode.com/problems/the-score-of-students-solving-math-expression/discuss/1487285/Python3-somewhat-dp", "python_solutions": "class Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n \n @cache\n def fn(lo, hi): \n \"\"\"Return possible answers of s[lo:hi].\"\"\"\n if lo+1 == hi: return {int(s[lo])}\n ans = set()\n for mid in range(lo+1, hi, 2): \n for x in fn(lo, mid): \n for y in fn(mid+1, hi): \n if s[mid] == \"+\" and x + y <= 1000: ans.add(x + y)\n elif s[mid] == \"*\" and x * y <= 1000: ans.add(x * y)\n return ans \n \n target = eval(s)\n cand = fn(0, len(s))\n ans = 0 \n for x in answers: \n if x == target: ans += 5\n elif x in cand: ans += 2\n return ans", "slug": "the-score-of-students-solving-math-expression", "post_title": "[Python3] somewhat dp", "user": "ye15", "upvotes": 6, "views": 267, "problem_title": "the score of students solving math expression", "number": 2019, "acceptance": 0.3379999999999999, "difficulty": "Hard", "__index_level_0__": 28146, "question": "You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations:\nCompute multiplication, reading from left to right; Then,\nCompute addition, reading from left to right.\nYou are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules:\nIf an answer equals the correct answer of the expression, this student will be rewarded 5 points;\nOtherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;\nOtherwise, this student will be rewarded 0 points.\nReturn the sum of the points of the students.\n Example 1:\nInput: s = \"7+3*1*2\", answers = [20,13,42]\nOutput: 7\nExplanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\nA student might have applied the operators in this wrong order: ((7+3)*1)*2 = 20. Therefore one student is rewarded 2 points: [20,13,42]\nThe points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.\nExample 2:\nInput: s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\nOutput: 19\nExplanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\nA student might have applied the operators in this wrong order: ((3+5)*2 = 16. Therefore two students are rewarded 2 points: [13,0,10,13,13,16,16]\nThe points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.\nExample 3:\nInput: s = \"6+0*1\", answers = [12,9,6,4,8,6]\nOutput: 10\nExplanation: The correct answer of the expression is 6.\nIf a student had incorrectly done (6+0)*1, the answer would also be 6.\nBy the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\nThe points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.\n Constraints:\n3 <= s.length <= 31\ns represents a valid expression that contains only digits 0-9, '+', and '*' only.\nAll the integer operands in the expression are in the inclusive range [0, 9].\n1 <= The count of all operators ('+' and '*') in the math expression <= 15\nTest data are generated such that the correct answer of the expression is in the range of [0, 1000].\nn == answers.length\n1 <= n <= 104\n0 <= answers[i] <= 1000" }, { "post_href": "https://leetcode.com/problems/convert-1d-array-into-2d-array/discuss/1499000/Python3-simulation", "python_solutions": "class Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n ans = []\n if len(original) == m*n: \n for i in range(0, len(original), n): \n ans.append(original[i:i+n])\n return ans", "slug": "convert-1d-array-into-2d-array", "post_title": "[Python3] simulation", "user": "ye15", "upvotes": 36, "views": 2800, "problem_title": "convert 1d array into 2d array", "number": 2022, "acceptance": 0.584, "difficulty": "Easy", "__index_level_0__": 28148, "question": "You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.\nThe elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.\nReturn an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.\n Example 1:\nInput: original = [1,2,3,4], m = 2, n = 2\nOutput: [[1,2],[3,4]]\nExplanation: The constructed 2D array should contain 2 rows and 2 columns.\nThe first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\nThe second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.\nExample 2:\nInput: original = [1,2,3], m = 1, n = 3\nOutput: [[1,2,3]]\nExplanation: The constructed 2D array should contain 1 row and 3 columns.\nPut all three elements in original into the first row of the constructed 2D array.\nExample 3:\nInput: original = [1,2], m = 1, n = 1\nOutput: []\nExplanation: There are 2 elements in original.\nIt is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.\n Constraints:\n1 <= original.length <= 5 * 104\n1 <= original[i] <= 105\n1 <= m, n <= 4 * 104" }, { "post_href": "https://leetcode.com/problems/number-of-pairs-of-strings-with-concatenation-equal-to-target/discuss/1499007/Python3-freq-table", "python_solutions": "class Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n freq = Counter(nums)\n ans = 0 \n for k, v in freq.items(): \n if target.startswith(k): \n suffix = target[len(k):]\n ans += v * freq[suffix]\n if k == suffix: ans -= freq[suffix]\n return ans", "slug": "number-of-pairs-of-strings-with-concatenation-equal-to-target", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 36, "views": 2600, "problem_title": "number of pairs of strings with concatenation equal to target", "number": 2023, "acceptance": 0.7290000000000001, "difficulty": "Medium", "__index_level_0__": 28182, "question": "Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.\n Example 1:\nInput: nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"\nOutput: 4\nExplanation: Valid pairs are:\n- (0, 1): \"777\" + \"7\"\n- (1, 0): \"7\" + \"777\"\n- (2, 3): \"77\" + \"77\"\n- (3, 2): \"77\" + \"77\"\nExample 2:\nInput: nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"\nOutput: 2\nExplanation: Valid pairs are:\n- (0, 1): \"123\" + \"4\"\n- (2, 3): \"12\" + \"34\"\nExample 3:\nInput: nums = [\"1\",\"1\",\"1\"], target = \"11\"\nOutput: 6\nExplanation: Valid pairs are:\n- (0, 1): \"1\" + \"1\"\n- (1, 0): \"1\" + \"1\"\n- (0, 2): \"1\" + \"1\"\n- (2, 0): \"1\" + \"1\"\n- (1, 2): \"1\" + \"1\"\n- (2, 1): \"1\" + \"1\"\n Constraints:\n2 <= nums.length <= 100\n1 <= nums[i].length <= 100\n2 <= target.length <= 100\nnums[i] and target consist of digits.\nnums[i] and target do not have leading zeros." }, { "post_href": "https://leetcode.com/problems/maximize-the-confusion-of-an-exam/discuss/1951750/WEEB-DOES-PYTHONC%2B%2B-SLIDING-WINDOW", "python_solutions": "class Solution:\n\tdef maxConsecutiveAnswers(self, string: str, k: int) -> int:\n\t\tresult = 0\n\t\tj = 0\n\t\tcount1 = k\n\t\tfor i in range(len(string)):\n\t\t\tif count1 == 0 and string[i] == \"F\":\n\t\t\t\twhile string[j] != \"F\":\n\t\t\t\t\tj+=1\n\t\t\t\tcount1+=1 \n\t\t\t\tj+=1\n\n\t\t\tif string[i] == \"F\":\n\t\t\t\tif count1 > 0:\n\t\t\t\t\tcount1-=1\n\n\t\t\tif i - j + 1 > result:\n\t\t\t\tresult = i - j + 1\n\n\t\tj = 0\n\t\tcount2 = k\n\t\tfor i in range(len(string)):\n\t\t\tif count2 == 0 and string[i] == \"T\":\n\t\t\t\twhile string[j] != \"T\":\n\t\t\t\t\tj+=1\n\t\t\t\tcount2+=1 \n\t\t\t\tj+=1\n\n\t\t\tif string[i] == \"T\":\n\t\t\t\tif count2 > 0:\n\t\t\t\t\tcount2-=1\n\n\t\t\tif i - j + 1 > result:\n\t\t\t\tresult = i - j + 1\n\n\t\treturn result", "slug": "maximize-the-confusion-of-an-exam", "post_title": "WEEB DOES PYTHON/C++ SLIDING WINDOW", "user": "Skywalker5423", "upvotes": 2, "views": 95, "problem_title": "maximize the confusion of an exam", "number": 2024, "acceptance": 0.598, "difficulty": "Medium", "__index_level_0__": 28206, "question": "A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).\nYou are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:\nChange the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').\nReturn the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.\n Example 1:\nInput: answerKey = \"TTFF\", k = 2\nOutput: 4\nExplanation: We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\nThere are four consecutive 'T's.\nExample 2:\nInput: answerKey = \"TFFT\", k = 1\nOutput: 3\nExplanation: We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\nAlternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\nIn both cases, there are three consecutive 'F's.\nExample 3:\nInput: answerKey = \"TTFTTFTT\", k = 1\nOutput: 5\nExplanation: We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\nAlternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \nIn both cases, there are five consecutive 'T's.\n Constraints:\nn == answerKey.length\n1 <= n <= 5 * 104\nanswerKey[i] is either 'T' or 'F'\n1 <= k <= n" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/discuss/1499024/Python3-binary-search", "python_solutions": "class Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n prefix = [0]\n loc = defaultdict(list)\n for i, x in enumerate(nums): \n prefix.append(prefix[-1] + x)\n if i < len(nums)-1: loc[prefix[-1]].append(i)\n \n ans = 0 \n if prefix[-1] % 2 == 0: ans = len(loc[prefix[-1]//2]) # unchanged \n \n total = prefix[-1]\n for i, x in enumerate(nums): \n cnt = 0 \n diff = k - x\n target = total + diff \n if target % 2 == 0: \n target //= 2\n cnt += bisect_left(loc[target], i)\n cnt += len(loc[target-diff]) - bisect_left(loc[target-diff], i)\n ans = max(ans, cnt)\n return ans", "slug": "maximum-number-of-ways-to-partition-an-array", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 2, "views": 227, "problem_title": "maximum number of ways to partition an array", "number": 2025, "acceptance": 0.321, "difficulty": "Hard", "__index_level_0__": 28221, "question": "You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions:\n1 <= pivot < n\nnums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]\nYou are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged.\nReturn the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.\n Example 1:\nInput: nums = [2,-1,2], k = 3\nOutput: 1\nExplanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\nThere is one way to partition the array:\n- For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.\nExample 2:\nInput: nums = [0,0,0], k = 1\nOutput: 2\nExplanation: The optimal approach is to leave the array unchanged.\nThere are two ways to partition the array:\n- For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n- For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.\nExample 3:\nInput: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\nOutput: 4\nExplanation: One optimal approach is to change nums[2] to k. The array becomes [22,4,-33,-20,-15,15,-16,7,19,-10,0,-13,-14].\nThere are four ways to partition the array.\n Constraints:\nn == nums.length\n2 <= n <= 105\n-105 <= k, nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-moves-to-convert-string/discuss/1500215/Python3-scan", "python_solutions": "class Solution:\n def minimumMoves(self, s: str) -> int:\n ans = i = 0\n while i < len(s): \n if s[i] == \"X\": \n ans += 1\n i += 3\n else: i += 1\n return ans", "slug": "minimum-moves-to-convert-string", "post_title": "[Python3] scan", "user": "ye15", "upvotes": 28, "views": 1200, "problem_title": "minimum moves to convert string", "number": 2027, "acceptance": 0.537, "difficulty": "Easy", "__index_level_0__": 28223, "question": "You are given a string s consisting of n characters which are either 'X' or 'O'.\nA move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.\nReturn the minimum number of moves required so that all the characters of s are converted to 'O'.\n Example 1:\nInput: s = \"XXX\"\nOutput: 1\nExplanation: XXX -> OOO\nWe select all the 3 characters and convert them in one move.\nExample 2:\nInput: s = \"XXOX\"\nOutput: 2\nExplanation: XXOX -> OOOX -> OOOO\nWe select the first 3 characters in the first move, and convert them to 'O'.\nThen we select the last 3 characters and convert them so that the final string contains all 'O's.\nExample 3:\nInput: s = \"OOOO\"\nOutput: 0\nExplanation: There are no 'X's in s to convert.\n Constraints:\n3 <= s.length <= 1000\ns[i] is either 'X' or 'O'." }, { "post_href": "https://leetcode.com/problems/find-missing-observations/discuss/1506196/Divmod-and-list-comprehension-96-speed", "python_solutions": "class Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n missing_val, rem = divmod(mean * (len(rolls) + n) - sum(rolls), n)\n if rem == 0:\n if 1 <= missing_val <= 6:\n return [missing_val] * n\n elif 1 <= missing_val < 6:\n return [missing_val + 1] * rem + [missing_val] * (n - rem)\n return []", "slug": "find-missing-observations", "post_title": "Divmod and list comprehension, 96% speed", "user": "EvgenySH", "upvotes": 2, "views": 133, "problem_title": "find missing observations", "number": 2028, "acceptance": 0.439, "difficulty": "Medium", "__index_level_0__": 28241, "question": "You have observations of n + m 6-sided dice rolls with each face numbered from 1 to 6. n of the observations went missing, and you only have the observations of m rolls. Fortunately, you have also calculated the average value of the n + m rolls.\nYou are given an integer array rolls of length m where rolls[i] is the value of the ith observation. You are also given the two integers mean and n.\nReturn an array of length n containing the missing observations such that the average value of the n + m rolls is exactly mean. If there are multiple valid answers, return any of them. If no such array exists, return an empty array.\nThe average value of a set of k numbers is the sum of the numbers divided by k.\nNote that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.\n Example 1:\nInput: rolls = [3,2,4,3], mean = 4, n = 2\nOutput: [6,6]\nExplanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.\nExample 2:\nInput: rolls = [1,5,6], mean = 3, n = 4\nOutput: [2,3,2,2]\nExplanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.\nExample 3:\nInput: rolls = [1,2,3,4], mean = 6, n = 4\nOutput: []\nExplanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.\n Constraints:\nm == rolls.length\n1 <= n, m <= 105\n1 <= rolls[i], mean <= 6" }, { "post_href": "https://leetcode.com/problems/stone-game-ix/discuss/1500343/Python3-freq-table", "python_solutions": "class Solution:\n def stoneGameIX(self, stones: List[int]) -> bool:\n freq = defaultdict(int)\n for x in stones: freq[x % 3] += 1\n \n if freq[0]%2 == 0: return freq[1] and freq[2]\n return abs(freq[1] - freq[2]) >= 3", "slug": "stone-game-ix", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 3, "views": 165, "problem_title": "stone game ix", "number": 2029, "acceptance": 0.264, "difficulty": "Medium", "__index_level_0__": 28250, "question": "Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.\nAlice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice's turn).\nAssuming both players play optimally, return true if Alice wins and false if Bob wins.\n Example 1:\nInput: stones = [2,1]\nOutput: true\nExplanation: The game will be played as follows:\n- Turn 1: Alice can remove either stone.\n- Turn 2: Bob removes the remaining stone. \nThe sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.\nExample 2:\nInput: stones = [2]\nOutput: false\nExplanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. \nSince all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.\nExample 3:\nInput: stones = [5,1,2,4,3]\nOutput: false\nExplanation: Bob will always win. One possible way for Bob to win is shown below:\n- Turn 1: Alice can remove the second stone with value 1. Sum of removed stones = 1.\n- Turn 2: Bob removes the fifth stone with value 3. Sum of removed stones = 1 + 3 = 4.\n- Turn 3: Alices removes the fourth stone with value 4. Sum of removed stones = 1 + 3 + 4 = 8.\n- Turn 4: Bob removes the third stone with value 2. Sum of removed stones = 1 + 3 + 4 + 2 = 10.\n- Turn 5: Alice removes the first stone with value 5. Sum of removed stones = 1 + 3 + 4 + 2 + 5 = 15.\nAlice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.\n Constraints:\n1 <= stones.length <= 105\n1 <= stones[i] <= 104" }, { "post_href": "https://leetcode.com/problems/smallest-k-length-subsequence-with-occurrences-of-a-letter/discuss/1502134/PYTHON3-O(n)-using-stack-with-explanation", "python_solutions": "class Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n counts,total = 0, 0\n n = len(s)\n for ch in s:\n if ch==letter:\n total +=1\n stack = []\n occ = 0\n for idx,ch in enumerate(s):\n if ch==letter:\n counts +=1\n while stack and stack[-1]>ch and len(stack)+ (n-1-idx)>=k and (occ+total-counts-(stack[-1]==letter)+(ch==letter)>=repetition ): \n occ -= stack.pop()==letter\n if ch!=letter and len(stack)< k-max(0,(repetition-occ)):\n stack.append(ch)\n elif ch==letter and len(stack)+(total-counts) List[int]:\n s1, s2, s3 = set(nums1), set(nums2), set(nums3)\n return (s1&s2) | (s2&s3) | (s1&s3)", "slug": "two-out-of-three", "post_title": "[Python3] set", "user": "ye15", "upvotes": 20, "views": 1400, "problem_title": "two out of three", "number": 2032, "acceptance": 0.726, "difficulty": "Easy", "__index_level_0__": 28255, "question": "Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.\n Example 1:\nInput: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\nOutput: [3,2]\nExplanation: The values that are present in at least two arrays are:\n- 3, in all three arrays.\n- 2, in nums1 and nums2.\nExample 2:\nInput: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\nOutput: [2,3,1]\nExplanation: The values that are present in at least two arrays are:\n- 2, in nums2 and nums3.\n- 3, in nums1 and nums2.\n- 1, in nums1 and nums3.\nExample 3:\nInput: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\nOutput: []\nExplanation: No value is present in at least two arrays.\n Constraints:\n1 <= nums1.length, nums2.length, nums3.length <= 100\n1 <= nums1[i], nums2[j], nums3[k] <= 100" }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-make-a-uni-value-grid/discuss/1513319/Python3-median-4-line", "python_solutions": "class Solution:\n def minOperations(self, grid: List[List[int]], x: int) -> int:\n vals = [x for row in grid for x in row]\n if len(set(val%x for val in vals)) > 1: return -1 # impossible\n median = sorted(vals)[len(vals)//2] # O(N) possible via \"quick select\"\n return sum(abs(val - median)//x for val in vals)", "slug": "minimum-operations-to-make-a-uni-value-grid", "post_title": "[Python3] median 4-line", "user": "ye15", "upvotes": 21, "views": 1100, "problem_title": "minimum operations to make a uni value grid", "number": 2033, "acceptance": 0.524, "difficulty": "Medium", "__index_level_0__": 28297, "question": "You are given a 2D integer grid of size m x n and an integer x. In one operation, you can add x to or subtract x from any element in the grid.\nA uni-value grid is a grid where all the elements of it are equal.\nReturn the minimum number of operations to make the grid uni-value. If it is not possible, return -1.\n Example 1:\nInput: grid = [[2,4],[6,8]], x = 2\nOutput: 4\nExplanation: We can make every element equal to 4 by doing the following: \n- Add x to 2 once.\n- Subtract x from 6 once.\n- Subtract x from 8 twice.\nA total of 4 operations were used.\nExample 2:\nInput: grid = [[1,5],[2,3]], x = 1\nOutput: 5\nExplanation: We can make every element equal to 3.\nExample 3:\nInput: grid = [[1,2],[3,4]], x = 2\nOutput: -1\nExplanation: It is impossible to make every element equal.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 105\n1 <= m * n <= 105\n1 <= x, grid[i][j] <= 104" }, { "post_href": "https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/discuss/1513435/Python-or-Easy-Explanation-or-Meet-in-the-Middle", "python_solutions": "class Solution:\n def minimumDifference(self, nums: List[int]) -> int:\n N = len(nums) // 2 # Note this is N/2, ie no. of elements required in each.\n \n def get_sums(nums): # generate all combinations sum of k elements\n ans = {}\n N = len(nums)\n for k in range(1, N+1): # takes k element for nums\n sums = []\n for comb in combinations(nums, k):\n s = sum(comb)\n sums.append(s)\n ans[k] = sums\n return ans\n \n left_part, right_part = nums[:N], nums[N:]\n left_sums, right_sums = get_sums(left_part), get_sums(right_part)\n ans = abs(sum(left_part) - sum(right_part)) # the case when taking all N from left_part for left_ans, and vice versa\n total = sum(nums) \n half = total // 2 # the best sum required for each, we have to find sum nearest to this\n for k in range(1, N):\n left = left_sums[k] # if taking k no. from left_sums\n right = right_sums[N-k] # then we have to take remaining N-k from right_sums.\n right.sort() # sorting, so that we can binary search the required value\n for x in left:\n r = half - x # required, how much we need to add in x to bring it closer to half.\n p = bisect.bisect_left(right, r) # we are finding index of value closest to r, present in right, using binary search\n for q in [p, p-1]:\n if 0 <= q < len(right):\n left_ans_sum = x + right[q]\n right_ans_sum = total - left_ans_sum\n diff = abs(left_ans_sum - right_ans_sum)\n ans = min(ans, diff) \n return ans", "slug": "partition-array-into-two-arrays-to-minimize-sum-difference", "post_title": "Python | Easy Explanation | Meet in the Middle", "user": "malraharsh", "upvotes": 117, "views": 8800, "problem_title": "partition array into two arrays to minimize sum difference", "number": 2035, "acceptance": 0.183, "difficulty": "Hard", "__index_level_0__": 28307, "question": "You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays. To partition nums, put each element of nums into one of the two arrays.\nReturn the minimum possible absolute difference.\n Example 1:\nInput: nums = [3,9,7,3]\nOutput: 2\nExplanation: One optimal partition is: [3,9] and [7,3].\nThe absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.\nExample 2:\nInput: nums = [-36,36]\nOutput: 72\nExplanation: One optimal partition is: [-36] and [36].\nThe absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.\nExample 3:\nInput: nums = [2,-1,0,4,-2,-9]\nOutput: 0\nExplanation: One optimal partition is: [2,4,-9] and [-1,0,-2].\nThe absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.\n Constraints:\n1 <= n <= 15\nnums.length == 2 * n\n-107 <= nums[i] <= 107" }, { "post_href": "https://leetcode.com/problems/minimum-number-of-moves-to-seat-everyone/discuss/1539518/O(n)-counting-sort-in-Python", "python_solutions": "class Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n seats.sort()\n students.sort()\n return sum(abs(seat - student) for seat, student in zip(seats, students))", "slug": "minimum-number-of-moves-to-seat-everyone", "post_title": "O(n) counting sort in Python", "user": "mousun224", "upvotes": 7, "views": 841, "problem_title": "minimum number of moves to seat everyone", "number": 2037, "acceptance": 0.821, "difficulty": "Easy", "__index_level_0__": 28310, "question": "There are n seats and n students in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.\nYou may perform the following move any number of times:\nIncrease or decrease the position of the ith student by 1 (i.e., moving the ith student from position x to x + 1 or x - 1)\nReturn the minimum number of moves required to move each student to a seat such that no two students are in the same seat.\nNote that there may be multiple seats or students in the same position at the beginning.\n Example 1:\nInput: seats = [3,1,5], students = [2,7,4]\nOutput: 4\nExplanation: The students are moved as follows:\n- The first student is moved from from position 2 to position 1 using 1 move.\n- The second student is moved from from position 7 to position 5 using 2 moves.\n- The third student is moved from from position 4 to position 3 using 1 move.\nIn total, 1 + 2 + 1 = 4 moves were used.\nExample 2:\nInput: seats = [4,1,5,9], students = [1,3,2,6]\nOutput: 7\nExplanation: The students are moved as follows:\n- The first student is not moved.\n- The second student is moved from from position 3 to position 4 using 1 move.\n- The third student is moved from from position 2 to position 5 using 3 moves.\n- The fourth student is moved from from position 6 to position 9 using 3 moves.\nIn total, 0 + 1 + 3 + 3 = 7 moves were used.\nExample 3:\nInput: seats = [2,2,6,6], students = [1,3,2,6]\nOutput: 4\nExplanation: Note that there are two seats at position 2 and two seats at position 6.\nThe students are moved as follows:\n- The first student is moved from from position 1 to position 2 using 1 move.\n- The second student is moved from from position 3 to position 6 using 3 moves.\n- The third student is not moved.\n- The fourth student is not moved.\nIn total, 1 + 3 + 0 + 0 = 4 moves were used.\n Constraints:\nn == seats.length == students.length\n1 <= n <= 100\n1 <= seats[i], students[j] <= 100" }, { "post_href": "https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/discuss/1524153/C%2B%2BPythonJava-Count-%22AAA%22-and-%22BBB%22", "python_solutions": "class Solution:\n def winnerOfGame(self, s: str) -> bool:\n \n a = b = 0\n \n for i in range(1,len(s)-1):\n if s[i-1] == s[i] == s[i+1]:\n if s[i] == 'A':\n a += 1\n else:\n b += 1\n \n return a>b", "slug": "remove-colored-pieces-if-both-neighbors-are-the-same-color", "post_title": "[C++/Python/Java] Count \"AAA\" and \"BBB\"", "user": "lokeshsenthilkumar", "upvotes": 75, "views": 5000, "problem_title": "remove colored pieces if both neighbors are the same color", "number": 2038, "acceptance": 0.5820000000000001, "difficulty": "Medium", "__index_level_0__": 28351, "question": "There are n pieces arranged in a line, and each piece is colored either by 'A' or by 'B'. You are given a string colors of length n where colors[i] is the color of the ith piece.\nAlice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.\nAlice is only allowed to remove a piece colored 'A' if both its neighbors are also colored 'A'. She is not allowed to remove pieces that are colored 'B'.\nBob is only allowed to remove a piece colored 'B' if both its neighbors are also colored 'B'. He is not allowed to remove pieces that are colored 'A'.\nAlice and Bob cannot remove pieces from the edge of the line.\nIf a player cannot make a move on their turn, that player loses and the other player wins.\nAssuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.\n Example 1:\nInput: colors = \"AAABABB\"\nOutput: true\nExplanation:\nAAABABB -> AABABB\nAlice moves first.\nShe removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n\nNow it's Bob's turn.\nBob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\nThus, Alice wins, so return true.\nExample 2:\nInput: colors = \"AA\"\nOutput: false\nExplanation:\nAlice has her turn first.\nThere are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\nThus, Bob wins, so return false.\nExample 3:\nInput: colors = \"ABBBBBBBAAA\"\nOutput: false\nExplanation:\nABBBBBBBAAA -> ABBBBBBBAA\nAlice moves first.\nHer only option is to remove the second to last 'A' from the right.\n\nABBBBBBBAA -> ABBBBBBAA\nNext is Bob's turn.\nHe has many options for which 'B' piece to remove. He can pick any.\n\nOn Alice's second turn, she has no more pieces that she can remove.\nThus, Bob wins, so return false.\n Constraints:\n1 <= colors.length <= 105\ncolors consists of only the letters 'A' and 'B'" }, { "post_href": "https://leetcode.com/problems/the-time-when-the-network-becomes-idle/discuss/1524183/Python3-graph", "python_solutions": "class Solution:\n def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n graph = {}\n for u, v in edges: \n graph.setdefault(u, []).append(v)\n graph.setdefault(v, []).append(u)\n \n dist = [-1]*len(graph)\n dist[0] = 0 \n val = 0\n queue = [0]\n while queue: \n val += 2\n newq = []\n for u in queue: \n for v in graph[u]: \n if dist[v] == -1: \n dist[v] = val\n newq.append(v)\n queue = newq\n \n ans = 0\n for d, p in zip(dist, patience): \n if p: \n k = d//p - int(d%p == 0)\n ans = max(ans, d + k*p)\n return ans + 1", "slug": "the-time-when-the-network-becomes-idle", "post_title": "[Python3] graph", "user": "ye15", "upvotes": 5, "views": 176, "problem_title": "the time when the network becomes idle", "number": 2039, "acceptance": 0.508, "difficulty": "Medium", "__index_level_0__": 28361, "question": "There is a network of n servers, labeled from 0 to n - 1. You are given a 2D integer array edges, where edges[i] = [ui, vi] indicates there is a message channel between servers ui and vi, and they can pass any number of messages to each other directly in one second. You are also given a 0-indexed integer array patience of length n.\nAll servers are connected, i.e., a message can be passed from one server to any other server(s) directly or indirectly through the message channels.\nThe server labeled 0 is the master server. The rest are data servers. Each data server needs to send its message to the master server for processing and wait for a reply. Messages move between servers optimally, so every message takes the least amount of time to arrive at the master server. The master server will process all newly arrived messages instantly and send a reply to the originating server via the reversed path the message had gone through.\nAt the beginning of second 0, each data server sends its message to be processed. Starting from second 1, at the beginning of every second, each data server will check if it has received a reply to the message it sent (including any newly arrived replies) from the master server:\nIf it has not, it will resend the message periodically. The data server i will resend the message every patience[i] second(s), i.e., the data server i will resend the message if patience[i] second(s) have elapsed since the last time the message was sent from this server.\nOtherwise, no more resending will occur from this server.\nThe network becomes idle when there are no messages passing between servers or arriving at servers.\nReturn the earliest second starting from which the network becomes idle.\n Example 1:\nInput: edges = [[0,1],[1,2]], patience = [0,2,1]\nOutput: 8\nExplanation:\nAt (the beginning of) second 0,\n- Data server 1 sends its message (denoted 1A) to the master server.\n- Data server 2 sends its message (denoted 2A) to the master server.\n\nAt second 1,\n- Message 1A arrives at the master server. Master server processes message 1A instantly and sends a reply 1A back.\n- Server 1 has not received any reply. 1 second (1 < patience[1] = 2) elapsed since this server has sent the message, therefore it does not resend the message.\n- Server 2 has not received any reply. 1 second (1 == patience[2] = 1) elapsed since this server has sent the message, therefore it resends the message (denoted 2B).\n\nAt second 2,\n- The reply 1A arrives at server 1. No more resending will occur from server 1.\n- Message 2A arrives at the master server. Master server processes message 2A instantly and sends a reply 2A back.\n- Server 2 resends the message (denoted 2C).\n...\nAt second 4,\n- The reply 2A arrives at server 2. No more resending will occur from server 2.\n...\nAt second 7, reply 2D arrives at server 2.\n\nStarting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\nThis is the time when the network becomes idle.\nExample 2:\nInput: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\nOutput: 3\nExplanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.\nFrom the beginning of the second 3, the network becomes idle.\n Constraints:\nn == patience.length\n2 <= n <= 105\npatience[0] == 0\n1 <= patience[i] <= 105 for 1 <= i < n\n1 <= edges.length <= min(105, n * (n - 1) / 2)\nedges[i].length == 2\n0 <= ui, vi < n\nui != vi\nThere are no duplicate edges.\nEach server can directly or indirectly reach another server." }, { "post_href": "https://leetcode.com/problems/kth-smallest-product-of-two-sorted-arrays/discuss/1524190/Python3-binary-search", "python_solutions": "class Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n \n def fn(val):\n \"\"\"Return count of products <= val.\"\"\"\n ans = 0\n for x in nums1: \n if x < 0: ans += len(nums2) - bisect_left(nums2, ceil(val/x))\n elif x == 0: \n if 0 <= val: ans += len(nums2)\n else: ans += bisect_right(nums2, floor(val/x))\n return ans \n \n lo, hi = -10**10, 10**10 + 1\n while lo < hi: \n mid = lo + hi >> 1\n if fn(mid) < k: lo = mid + 1\n else: hi = mid\n return lo", "slug": "kth-smallest-product-of-two-sorted-arrays", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 8, "views": 1300, "problem_title": "kth smallest product of two sorted arrays", "number": 2040, "acceptance": 0.291, "difficulty": "Hard", "__index_level_0__": 28368, "question": "Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.\n Example 1:\nInput: nums1 = [2,5], nums2 = [3,4], k = 2\nOutput: 8\nExplanation: The 2 smallest products are:\n- nums1[0] * nums2[0] = 2 * 3 = 6\n- nums1[0] * nums2[1] = 2 * 4 = 8\nThe 2nd smallest product is 8.\nExample 2:\nInput: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6\nOutput: 0\nExplanation: The 6 smallest products are:\n- nums1[0] * nums2[1] = (-4) * 4 = -16\n- nums1[0] * nums2[0] = (-4) * 2 = -8\n- nums1[1] * nums2[1] = (-2) * 4 = -8\n- nums1[1] * nums2[0] = (-2) * 2 = -4\n- nums1[2] * nums2[0] = 0 * 2 = 0\n- nums1[2] * nums2[1] = 0 * 4 = 0\nThe 6th smallest product is 0.\nExample 3:\nInput: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3\nOutput: -6\nExplanation: The 3 smallest products are:\n- nums1[0] * nums2[4] = (-2) * 5 = -10\n- nums1[0] * nums2[3] = (-2) * 4 = -8\n- nums1[4] * nums2[0] = 2 * (-3) = -6\nThe 3rd smallest product is -6.\n Constraints:\n1 <= nums1.length, nums2.length <= 5 * 104\n-105 <= nums1[i], nums2[j] <= 105\n1 <= k <= nums1.length * nums2.length\nnums1 and nums2 are sorted." }, { "post_href": "https://leetcode.com/problems/check-if-numbers-are-ascending-in-a-sentence/discuss/1525219/Python3-2-line", "python_solutions": "class Solution:\n def areNumbersAscending(self, s: str) -> bool:\n nums = [int(w) for w in s.split() if w.isdigit()]\n return all(nums[i-1] < nums[i] for i in range(1, len(nums)))", "slug": "check-if-numbers-are-ascending-in-a-sentence", "post_title": "[Python3] 2-line", "user": "ye15", "upvotes": 24, "views": 1400, "problem_title": "check if numbers are ascending in a sentence", "number": 2042, "acceptance": 0.6609999999999999, "difficulty": "Easy", "__index_level_0__": 28372, "question": "A sentence is a list of tokens separated by a single space with no leading or trailing spaces. Every token is either a positive number consisting of digits 0-9 with no leading zeros, or a word consisting of lowercase English letters.\nFor example, \"a puppy has 2 eyes 4 legs\" is a sentence with seven tokens: \"2\" and \"4\" are numbers and the other tokens such as \"puppy\" are words.\nGiven a string s representing a sentence, you need to check if all the numbers in s are strictly increasing from left to right (i.e., other than the last number, each number is strictly smaller than the number on its right in s).\nReturn true if so, or false otherwise.\n Example 1:\nInput: s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"\nOutput: true\nExplanation: The numbers in s are: 1, 3, 4, 6, 12.\nThey are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.\nExample 2:\nInput: s = \"hello world 5 x 5\"\nOutput: false\nExplanation: The numbers in s are: 5, 5. They are not strictly increasing.\nExample 3:\nInput: s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"\nOutput: false\nExplanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.\n Constraints:\n3 <= s.length <= 200\ns consists of lowercase English letters, spaces, and digits from 0 to 9, inclusive.\nThe number of tokens in s is between 2 and 100, inclusive.\nThe tokens in s are separated by a single space.\nThere are at least two numbers in s.\nEach number in s is a positive number less than 100, with no leading zeros.\ns contains no leading or trailing spaces." }, { "post_href": "https://leetcode.com/problems/count-number-of-maximum-bitwise-or-subsets/discuss/1525225/Python3-top-down-dp", "python_solutions": "class Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n target = reduce(or_, nums)\n \n @cache\n def fn(i, mask): \n \"\"\"Return number of subsets to get target.\"\"\"\n if mask == target: return 2**(len(nums)-i)\n if i == len(nums): return 0 \n return fn(i+1, mask | nums[i]) + fn(i+1, mask)\n \n return fn(0, 0)", "slug": "count-number-of-maximum-bitwise-or-subsets", "post_title": "[Python3] top-down dp", "user": "ye15", "upvotes": 8, "views": 729, "problem_title": "count number of maximum bitwise or subsets", "number": 2044, "acceptance": 0.748, "difficulty": "Medium", "__index_level_0__": 28406, "question": "Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR.\nAn array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b. Two subsets are considered different if the indices of the elements chosen are different.\nThe bitwise OR of an array a is equal to a[0] OR a[1] OR ... OR a[a.length - 1] (0-indexed).\n Example 1:\nInput: nums = [3,1]\nOutput: 2\nExplanation: The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:\n- [3]\n- [3,1]\nExample 2:\nInput: nums = [2,2,2]\nOutput: 7\nExplanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.\nExample 3:\nInput: nums = [3,2,1,5]\nOutput: 6\nExplanation: The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:\n- [3,5]\n- [3,1,5]\n- [3,2,5]\n- [3,2,1,5]\n- [2,5]\n- [2,1,5]\n Constraints:\n1 <= nums.length <= 16\n1 <= nums[i] <= 105" }, { "post_href": "https://leetcode.com/problems/second-minimum-time-to-reach-destination/discuss/1525227/Python3-Dijkstra-and-BFS", "python_solutions": "class Solution:\n def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:\n graph = [[] for _ in range(n)]\n for u, v in edges: \n graph[u-1].append(v-1)\n graph[v-1].append(u-1)\n pq = [(0, 0)]\n seen = [[] for _ in range(n)]\n least = None\n while pq: \n t, u = heappop(pq)\n if u == n-1: \n if least is None: least = t\n elif least < t: return t \n if (t//change) & 1: t = (t//change+1)*change # waiting for green\n t += time\n for v in graph[u]: \n if not seen[v] or len(seen[v]) == 1 and seen[v][0] != t: \n seen[v].append(t)\n heappush(pq, (t, v))", "slug": "second-minimum-time-to-reach-destination", "post_title": "[Python3] Dijkstra & BFS", "user": "ye15", "upvotes": 6, "views": 462, "problem_title": "second minimum time to reach destination", "number": 2045, "acceptance": 0.389, "difficulty": "Hard", "__index_level_0__": 28417, "question": "A city is represented as a bi-directional connected graph with n vertices where each vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is time minutes.\nEach vertex has a traffic signal which changes its color from green to red and vice versa every change minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green.\nThe second minimum value is defined as the smallest value strictly larger than the minimum value.\nFor example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.\nGiven n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.\nNotes:\nYou can go through any vertex any number of times, including 1 and n.\nYou can assume that when the journey starts, all signals have just turned green.\n Example 1:\nInput: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5\nOutput: 13\nExplanation:\nThe figure on the left shows the given graph.\nThe blue path in the figure on the right is the minimum time path.\nThe time taken is:\n- Start at 1, time elapsed=0\n- 1 -> 4: 3 minutes, time elapsed=3\n- 4 -> 5: 3 minutes, time elapsed=6\nHence the minimum time needed is 6 minutes.\n\nThe red path shows the path to get the second minimum time.\n- Start at 1, time elapsed=0\n- 1 -> 3: 3 minutes, time elapsed=3\n- 3 -> 4: 3 minutes, time elapsed=6\n- Wait at 4 for 4 minutes, time elapsed=10\n- 4 -> 5: 3 minutes, time elapsed=13\nHence the second minimum time is 13 minutes. \nExample 2:\nInput: n = 2, edges = [[1,2]], time = 3, change = 2\nOutput: 11\nExplanation:\nThe minimum time path is 1 -> 2 with time = 3 minutes.\nThe second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.\n Constraints:\n2 <= n <= 104\nn - 1 <= edges.length <= min(2 * 104, n * (n - 1) / 2)\nedges[i].length == 2\n1 <= ui, vi <= n\nui != vi\nThere are no duplicate edges.\nEach vertex can be reached directly or indirectly from every other vertex.\n1 <= time, change <= 103" }, { "post_href": "https://leetcode.com/problems/number-of-valid-words-in-a-sentence/discuss/1537625/Python3-check-words", "python_solutions": "class Solution:\n def countValidWords(self, sentence: str) -> int:\n \n def fn(word): \n \"\"\"Return true if word is valid.\"\"\"\n seen = False \n for i, ch in enumerate(word): \n if ch.isdigit() or ch in \"!.,\" and i != len(word)-1: return False\n elif ch == '-': \n if seen or i == 0 or i == len(word)-1 or not word[i+1].isalpha(): return False \n seen = True \n return True \n \n return sum(fn(word) for word in sentence.split())", "slug": "number-of-valid-words-in-a-sentence", "post_title": "[Python3] check words", "user": "ye15", "upvotes": 20, "views": 1200, "problem_title": "number of valid words in a sentence", "number": 2047, "acceptance": 0.295, "difficulty": "Easy", "__index_level_0__": 28420, "question": "A sentence consists of lowercase letters ('a' to 'z'), digits ('0' to '9'), hyphens ('-'), punctuation marks ('!', '.', and ','), and spaces (' ') only. Each sentence can be broken down into one or more tokens separated by one or more spaces ' '.\nA token is a valid word if all three of the following are true:\nIt only contains lowercase letters, hyphens, and/or punctuation (no digits).\nThere is at most one hyphen '-'. If present, it must be surrounded by lowercase characters (\"a-b\" is valid, but \"-ab\" and \"ab-\" are not valid).\nThere is at most one punctuation mark. If present, it must be at the end of the token (\"ab,\", \"cd!\", and \".\" are valid, but \"a!b\" and \"c.,\" are not valid).\nExamples of valid words include \"a-b.\", \"afad\", \"ba-c\", \"a!\", and \"!\".\nGiven a string sentence, return the number of valid words in sentence.\n Example 1:\nInput: sentence = \"cat and dog\"\nOutput: 3\nExplanation: The valid words in the sentence are \"cat\", \"and\", and \"dog\".\nExample 2:\nInput: sentence = \"!this 1-s b8d!\"\nOutput: 0\nExplanation: There are no valid words in the sentence.\n\"!this\" is invalid because it starts with a punctuation mark.\n\"1-s\" and \"b8d\" are invalid because they contain digits.\nExample 3:\nInput: sentence = \"alice and bob are playing stone-game10\"\nOutput: 5\nExplanation: The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n\"stone-game10\" is invalid because it contains digits.\n Constraints:\n1 <= sentence.length <= 1000\nsentence only contains lowercase English letters, digits, ' ', '-', '!', '.', and ','.\nThere will be at least 1 token." }, { "post_href": "https://leetcode.com/problems/next-greater-numerically-balanced-number/discuss/1537537/Python3-brute-force", "python_solutions": "class Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n while True: \n n += 1\n nn = n \n freq = defaultdict(int)\n while nn: \n nn, d = divmod(nn, 10)\n freq[d] += 1\n if all(k == v for k, v in freq.items()): return n", "slug": "next-greater-numerically-balanced-number", "post_title": "[Python3] brute-force", "user": "ye15", "upvotes": 3, "views": 151, "problem_title": "next greater numerically balanced number", "number": 2048, "acceptance": 0.471, "difficulty": "Medium", "__index_level_0__": 28436, "question": "An integer x is numerically balanced if for every digit d in the number x, there are exactly d occurrences of that digit in x.\nGiven an integer n, return the smallest numerically balanced number strictly greater than n.\n Example 1:\nInput: n = 1\nOutput: 22\nExplanation: \n22 is numerically balanced since:\n- The digit 2 occurs 2 times. \nIt is also the smallest numerically balanced number strictly greater than 1.\nExample 2:\nInput: n = 1000\nOutput: 1333\nExplanation: \n1333 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times. \nIt is also the smallest numerically balanced number strictly greater than 1000.\nNote that 1022 cannot be the answer because 0 appeared more than 0 times.\nExample 3:\nInput: n = 3000\nOutput: 3133\nExplanation: \n3133 is numerically balanced since:\n- The digit 1 occurs 1 time.\n- The digit 3 occurs 3 times.\nIt is also the smallest numerically balanced number strictly greater than 3000.\n Constraints:\n0 <= n <= 106" }, { "post_href": "https://leetcode.com/problems/count-nodes-with-the-highest-score/discuss/1537603/Python-3-or-Graph-DFS-Post-order-Traversal-O(N)-or-Explanation", "python_solutions": "class Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n graph = collections.defaultdict(list)\n for node, parent in enumerate(parents): # build graph\n graph[parent].append(node)\n n = len(parents) # total number of nodes\n d = collections.Counter()\n def count_nodes(node): # number of children node + self\n p, s = 1, 0 # p: product, s: sum\n for child in graph[node]: # for each child (only 2 at maximum)\n res = count_nodes(child) # get its nodes count\n p *= res # take the product\n s += res # take the sum\n p *= max(1, n - 1 - s) # times up-branch (number of nodes other than left, right children ans itself)\n d[p] += 1 # count the product\n return s + 1 # return number of children node + 1 (self)\n count_nodes(0) # starting from root (0)\n return d[max(d.keys())] # return max count", "slug": "count-nodes-with-the-highest-score", "post_title": "Python 3 | Graph, DFS, Post-order Traversal, O(N) | Explanation", "user": "idontknoooo", "upvotes": 63, "views": 3300, "problem_title": "count nodes with the highest score", "number": 2049, "acceptance": 0.471, "difficulty": "Medium", "__index_level_0__": 28444, "question": "There is a binary tree rooted at 0 consisting of n nodes. The nodes are labeled from 0 to n - 1. You are given a 0-indexed integer array parents representing the tree, where parents[i] is the parent of node i. Since node 0 is the root, parents[0] == -1.\nEach node has a score. To find the score of a node, consider if the node and the edges connected to it were removed. The tree would become one or more non-empty subtrees. The size of a subtree is the number of the nodes in it. The score of the node is the product of the sizes of all those subtrees.\nReturn the number of nodes that have the highest score.\n Example 1:\nInput: parents = [-1,2,0,2,0]\nOutput: 3\nExplanation:\n- The score of node 0 is: 3 * 1 = 3\n- The score of node 1 is: 4 = 4\n- The score of node 2 is: 1 * 1 * 2 = 2\n- The score of node 3 is: 4 = 4\n- The score of node 4 is: 4 = 4\nThe highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.\nExample 2:\nInput: parents = [-1,2,0]\nOutput: 2\nExplanation:\n- The score of node 0 is: 2 = 2\n- The score of node 1 is: 2 = 2\n- The score of node 2 is: 1 * 1 = 1\nThe highest score is 2, and two nodes (node 0 and node 1) have the highest score.\n Constraints:\nn == parents.length\n2 <= n <= 105\nparents[0] == -1\n0 <= parents[i] <= n - 1 for i != 0\nparents represents a valid binary tree." }, { "post_href": "https://leetcode.com/problems/parallel-courses-iii/discuss/1546258/Python-solution-using-topology-sort-and-BFS", "python_solutions": "class Solution:\n def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:\n graph = { course:[] for course in range(n)}\n inDegree = [0]*n\n # 1- build graph\n # convert 1-base into 0-baseindexes and add to graph\n # Note: choose Prev->next since it helps to preserve the topology order\n for prevCourse,nextCourse in relations:\n prevCourse,nextCourse = prevCourse-1, nextCourse-1\n graph[prevCourse].append(nextCourse)\n inDegree[nextCourse] += 1\n\n # 2 Assign time cost\n q = collections.deque()\n cost = [0] * n\n for course in range(n):\n if inDegree[course] == 0:\n q.append(course)\n cost[course] = time[course] # number of months\n # 3- BFS\n while q:\n prevCourse = q.popleft()\n for nextCourse in graph[prevCourse]:\n # Update cost[nextCourse] using the maximum cost of the predecessor course\n cost[nextCourse] = max(cost[nextCourse], cost[prevCourse] + time[nextCourse])\n inDegree[nextCourse] -= 1\n if inDegree[nextCourse] == 0:\n q.append(nextCourse)\n return max(cost)\n\t\t```", "slug": "parallel-courses-iii", "post_title": "Python solution using topology sort and BFS", "user": "MAhmadian", "upvotes": 1, "views": 91, "problem_title": "parallel courses iii", "number": 2050, "acceptance": 0.595, "difficulty": "Hard", "__index_level_0__": 28452, "question": "You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.\nYou must find the minimum number of months needed to complete all the courses following these rules:\nYou may start taking a course at any time if the prerequisites are met.\nAny number of courses can be taken at the same time.\nReturn the minimum number of months needed to complete all the courses.\nNote: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).\n Example 1:\nInput: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]\nOutput: 8\nExplanation: The figure above represents the given graph and the time required to complete each course. \nWe start course 1 and course 2 simultaneously at month 0.\nCourse 1 takes 3 months and course 2 takes 2 months to complete respectively.\nThus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.\nExample 2:\nInput: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]\nOutput: 12\nExplanation: The figure above represents the given graph and the time required to complete each course.\nYou can start courses 1, 2, and 3 at month 0.\nYou can complete them after 1, 2, and 3 months respectively.\nCourse 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\nCourse 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.\nThus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.\n Constraints:\n1 <= n <= 5 * 104\n0 <= relations.length <= min(n * (n - 1) / 2, 5 * 104)\nrelations[j].length == 2\n1 <= prevCoursej, nextCoursej <= n\nprevCoursej != nextCoursej\nAll the pairs [prevCoursej, nextCoursej] are unique.\ntime.length == n\n1 <= time[i] <= 104\nThe given graph is a directed acyclic graph." }, { "post_href": "https://leetcode.com/problems/kth-distinct-string-in-an-array/discuss/1549003/Python3-freq-table", "python_solutions": "class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n freq = Counter(arr)\n for x in arr: \n if freq[x] == 1: k -= 1\n if k == 0: return x\n return \"\"", "slug": "kth-distinct-string-in-an-array", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 19, "views": 1200, "problem_title": "kth distinct string in an array", "number": 2053, "acceptance": 0.718, "difficulty": "Easy", "__index_level_0__": 28458, "question": "A distinct string is a string that is present only once in an array.\nGiven an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string \"\".\nNote that the strings are considered in the order in which they appear in the array.\n Example 1:\nInput: arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2\nOutput: \"a\"\nExplanation:\nThe only distinct strings in arr are \"d\" and \"a\".\n\"d\" appears 1st, so it is the 1st distinct string.\n\"a\" appears 2nd, so it is the 2nd distinct string.\nSince k == 2, \"a\" is returned. \nExample 2:\nInput: arr = [\"aaa\",\"aa\",\"a\"], k = 1\nOutput: \"aaa\"\nExplanation:\nAll strings in arr are distinct, so the 1st string \"aaa\" is returned.\nExample 3:\nInput: arr = [\"a\",\"b\",\"a\"], k = 3\nOutput: \"\"\nExplanation:\nThe only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".\n Constraints:\n1 <= k <= arr.length <= 1000\n1 <= arr[i].length <= 5\narr[i] consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/two-best-non-overlapping-events/discuss/1549284/Heap-oror-very-Easy-oror-Well-Explained", "python_solutions": "class Solution:\ndef maxTwoEvents(self, events: List[List[int]]) -> int:\n \n events.sort()\n heap = []\n res2,res1 = 0,0\n for s,e,p in events:\n while heap and heap[0][0] List[int]:\n n=len(s)\n prefcandle=[-1]*n #this stores the position of closest candle from current towards left\n suffcandle=[0]*n #this stores the position of closest candle from current towards right\n \n pref=[0]*n #stores the number of plates till ith position from 0 - for i = 0 -> n \n \n ind=-1\n c=0\n #The following method calculates number of plates(*) till ith position from 0 - for i = 0 -> n \n for i in range(n):\n if ind!=-1 and s[i]=='*':\n c+=1\n elif s[i]=='|':\n ind=i\n pref[i]=c\n \n #this method calculates the left nearest candle to a point\n #intial is -1 as to left of leftmost element no candle can be present\n ind =-1\n for i in range(n):\n if s[i] == '|':\n ind=i\n prefcandle[i]=ind\n \n #this method calculates the right nearest candle to a point\n #intial is infinity as to right of rightmost element no candle can be present\n ind = float('inf') \n for i in range(n-1, -1, -1):\n if s[i]=='|':\n ind=i\n suffcandle[i]=ind\n\n #m = no of queries\n m=len(qs)\n ans=[0]*m\n\n for i in range(m):\n c=0\n l=qs[i][0]\n r=qs[i][1]\n \n #check if left nearest candle of right boundary is after left boundary\n #check if right nearest candle of left boundary is before right boundary\n # to summarise - here we find if there is a pair of candle present within the given range or not\n if prefcandle[r]r:\n continue\n \n #desired answer is no of pplates(*) only inside 2 candles (|) inside the given boundary area\n ans[i]=pref[prefcandle[r]]-pref[suffcandle[l]]\n return ans", "slug": "plates-between-candles", "post_title": "100 % faster Linear Python solution | Prefix sum | O(N)", "user": "acloj97", "upvotes": 12, "views": 1200, "problem_title": "plates between candles", "number": 2055, "acceptance": 0.444, "difficulty": "Medium", "__index_level_0__": 28496, "question": "There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters '*' and '|' only, where a '*' represents a plate and a '|' represents a candle.\nYou are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti...righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.\nFor example, s = \"||**||**|*\", and a query [3, 8] denotes the substring \"*||**|\". The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.\nReturn an integer array answer where answer[i] is the answer to the ith query.\n Example 1:\nInput: s = \"**|**|***|\", queries = [[2,5],[5,9]]\nOutput: [2,3]\nExplanation:\n- queries[0] has two plates between candles.\n- queries[1] has three plates between candles.\nExample 2:\nInput: s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]\nOutput: [9,0,0,0,0]\nExplanation:\n- queries[0] has nine plates between candles.\n- The other queries have zero plates between candles.\n Constraints:\n3 <= s.length <= 105\ns consists of '*' and '|' characters.\n1 <= queries.length <= 105\nqueries[i].length == 2\n0 <= lefti <= righti < s.length" }, { "post_href": "https://leetcode.com/problems/number-of-valid-move-combinations-on-chessboard/discuss/2331905/Python3-or-DFS-with-backtracking-or-Clean-code-with-comments", "python_solutions": "class Solution:\n BOARD_SIZE = 8\n \n def diag(self, r, c):\n # Return all diagonal indices except (r, c)\n # Diagonal indices has the same r - c\n inv = r - c\n result = []\n for ri in range(self.BOARD_SIZE):\n ci = ri - inv\n if 0 <= ci < self.BOARD_SIZE and ri != r:\n result.append((ri, ci))\n\n return result\n \n def reverseDiag(self, r, c):\n # Return all reverse diagonal indices except (r, c)\n # Reverse diagonal indices has the same r + c\n inv = r + c\n result = []\n for ri in range(self.BOARD_SIZE):\n ci = inv - ri\n if 0 <= ci < self.BOARD_SIZE and ri != r:\n result.append((ri, ci))\n\n return result\n \n def generatePossiblePositions(self, piece, start):\n # Generate list of possible positions for every figure\n rs, cs = start[0] - 1, start[1] - 1\n\n # Start position\n result = [(rs, cs)]\n\n # Straight\n if piece == \"rook\" or piece == \"queen\":\n result.extend([(r, cs) for r in range(self.BOARD_SIZE) if r != rs])\n result.extend([(rs, c) for c in range(self.BOARD_SIZE) if c != cs])\n\n # Diagonal\n if piece == \"bishop\" or piece == \"queen\":\n result.extend(self.diag(rs, cs))\n result.extend(self.reverseDiag(rs, cs))\n\n return result\n \n def collide(self, start1, end1, start2, end2):\n # Check if two figures will collide\n # Collision occures if: \n # - two figures have the same end points\n # - one figure stands on the way of second one\n #\n # For this purpose let's model each step of two pieces \n # and compare their positions at every time step.\n \n def steps(start, end):\n # Total steps that should be done\n return abs(end - start)\n\n def step(start, end):\n # Step direction -1, 0, 1\n if steps(start, end) == 0:\n return 0\n return (end - start) / steps(start, end)\n\n (rstart1, cstart1), (rend1, cend1) = start1, end1\n (rstart2, cstart2), (rend2, cend2) = start2, end2\n\n # Find step direction for each piece\n rstep1, cstep1 = step(rstart1, rend1), step(cstart1, cend1)\n rstep2, cstep2 = step(rstart2, rend2), step(cstart2, cend2)\n\n # Find maximum number of steps for each piece\n max_step1 = max(steps(rstart1, rend1), steps(cstart1, cend1))\n max_step2 = max(steps(rstart2, rend2), steps(cstart2, cend2))\n\n # Move pieces step by step and compare their positions\n for step_i in range(max(max_step1, max_step2) + 1):\n step_i1 = min(step_i, max_step1)\n r1 = rstart1 + step_i1 * rstep1\n c1 = cstart1 + step_i1 * cstep1\n\n step_i2 = min(step_i, max_step2)\n r2 = rstart2 + step_i2 * rstep2\n c2 = cstart2 + step_i2 * cstep2\n\n # If positions are the same then collision occures\n if r1 == r2 and c1 == c2:\n return True\n\n return False\n \n def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int:\n if len(pieces) == 0:\n return 0\n\n n = len(pieces)\n \n # Make zero-indexed\n start_positions = [[r - 1, c - 1] for r, c in positions]\n \n # All possible positions\n possible_positions = [\n self.generatePossiblePositions(piece, start) \n for piece, start in zip(pieces, positions)\n ]\n \n # Let's use DFS with backtracking\n # For that we will keep set of already occupied coordinates\n # and current positions of pieces\n occupied = set()\n current_positions = [None] * n # None means that we didn't placed the piece\n \n def collision(start, end):\n # Helper to check if moving from start to end position will collide with someone\n for start2, end2 in zip(start_positions, current_positions):\n if end2 is not None and self.collide(start, end, start2, end2):\n return True\n return False\n\n def dfs(piece_i=0):\n # All pieces are placed\n if piece_i == n:\n return 1\n\n result = 0\n for position in possible_positions[piece_i]:\n # If position already occupied of collides with other pieces then skip it\n if position in occupied or collision(start_positions[piece_i], position):\n continue\n \n # Occupy the position\n occupied.add(position)\n current_positions[piece_i] = position\n \n # Run DFS for next piece\n result += dfs(piece_i + 1)\n \n # Release the position\n occupied.remove(position)\n current_positions[piece_i] = None\n \n return result\n\n return dfs()", "slug": "number-of-valid-move-combinations-on-chessboard", "post_title": "Python3 | DFS with backtracking | Clean code with comments", "user": "snorkin", "upvotes": 1, "views": 58, "problem_title": "number of valid move combinations on chessboard", "number": 2056, "acceptance": 0.59, "difficulty": "Hard", "__index_level_0__": 28506, "question": "There is an 8 x 8 chessboard containing n pieces (rooks, queens, or bishops). You are given a string array pieces of length n, where pieces[i] describes the type (rook, queen, or bishop) of the ith piece. In addition, you are given a 2D integer array positions also of length n, where positions[i] = [ri, ci] indicates that the ith piece is currently at the 1-based coordinate (ri, ci) on the chessboard.\nWhen making a move for a piece, you choose a destination square that the piece will travel toward and stop on.\nA rook can only travel horizontally or vertically from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), or (r, c-1).\nA queen can only travel horizontally, vertically, or diagonally from (r, c) to the direction of (r+1, c), (r-1, c), (r, c+1), (r, c-1), (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1).\nA bishop can only travel diagonally from (r, c) to the direction of (r+1, c+1), (r+1, c-1), (r-1, c+1), (r-1, c-1).\nYou must make a move for every piece on the board simultaneously. A move combination consists of all the moves performed on all the given pieces. Every second, each piece will instantaneously travel one square towards their destination if they are not already at it. All pieces start traveling at the 0th second. A move combination is invalid if, at a given time, two or more pieces occupy the same square.\nReturn the number of valid move combinations.\nNotes:\nNo two pieces will start in the same square.\nYou may choose the square a piece is already on as its destination.\nIf two pieces are directly adjacent to each other, it is valid for them to move past each other and swap positions in one second.\n Example 1:\nInput: pieces = [\"rook\"], positions = [[1,1]]\nOutput: 15\nExplanation: The image above shows the possible squares the piece can move to.\nExample 2:\nInput: pieces = [\"queen\"], positions = [[1,1]]\nOutput: 22\nExplanation: The image above shows the possible squares the piece can move to.\nExample 3:\nInput: pieces = [\"bishop\"], positions = [[4,3]]\nOutput: 12\nExplanation: The image above shows the possible squares the piece can move to.\n Constraints:\nn == pieces.length \nn == positions.length\n1 <= n <= 4\npieces only contains the strings \"rook\", \"queen\", and \"bishop\".\nThere will be at most one queen on the chessboard.\n1 <= xi, yi <= 8\nEach positions[i] is distinct." }, { "post_href": "https://leetcode.com/problems/smallest-index-with-equal-value/discuss/1549993/Python3-1-line", "python_solutions": "class Solution:\n def smallestEqual(self, nums: List[int]) -> int:\n return next((i for i, x in enumerate(nums) if i%10 == x), -1)", "slug": "smallest-index-with-equal-value", "post_title": "[Python3] 1-line", "user": "ye15", "upvotes": 10, "views": 646, "problem_title": "smallest index with equal value", "number": 2057, "acceptance": 0.7120000000000001, "difficulty": "Easy", "__index_level_0__": 28508, "question": "Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.\nx mod y denotes the remainder when x is divided by y.\n Example 1:\nInput: nums = [0,1,2]\nOutput: 0\nExplanation: \ni=0: 0 mod 10 = 0 == nums[0].\ni=1: 1 mod 10 = 1 == nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\nAll indices have i mod 10 == nums[i], so we return the smallest index 0.\nExample 2:\nInput: nums = [4,3,2,1]\nOutput: 2\nExplanation: \ni=0: 0 mod 10 = 0 != nums[0].\ni=1: 1 mod 10 = 1 != nums[1].\ni=2: 2 mod 10 = 2 == nums[2].\ni=3: 3 mod 10 = 3 != nums[3].\n2 is the only index which has i mod 10 == nums[i].\nExample 3:\nInput: nums = [1,2,3,4,5,6,7,8,9,0]\nOutput: -1\nExplanation: No index satisfies i mod 10 == nums[i].\n Constraints:\n1 <= nums.length <= 100\n0 <= nums[i] <= 9" }, { "post_href": "https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/discuss/1551353/Python-O(1)-memory-O(n)-time-beats-100.00", "python_solutions": "class Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n min_res = math.inf\n min_point = max_point = last_point = None\n prev_val = head.val\n head = head.next\n i = 1\n while head.next:\n if ((head.next.val < head.val and prev_val < head.val) or\n (head.next.val > head.val and prev_val > head.val)):\n \n if min_point is None:\n min_point = i\n else:\n max_point = i\n \n if last_point:\n min_res = min(min_res, i - last_point)\n \n last_point = i\n \n prev_val = head.val\n i += 1\n head = head.next\n \n if min_res == math.inf:\n min_res = -1\n max_res = max_point - min_point if max_point else -1\n \n return [min_res, max_res]", "slug": "find-the-minimum-and-maximum-number-of-nodes-between-critical-points", "post_title": "Python O(1) memory, O(n) time beats 100.00%", "user": "dereky4", "upvotes": 1, "views": 125, "problem_title": "find the minimum and maximum number of nodes between critical points", "number": 2058, "acceptance": 0.57, "difficulty": "Medium", "__index_level_0__": 28534, "question": "A critical point in a linked list is defined as either a local maxima or a local minima.\nA node is a local maxima if the current node has a value strictly greater than the previous node and the next node.\nA node is a local minima if the current node has a value strictly smaller than the previous node and the next node.\nNote that a node can only be a local maxima/minima if there exists both a previous node and a next node.\nGiven a linked list head, return an array of length 2 containing [minDistance, maxDistance] where minDistance is the minimum distance between any two distinct critical points and maxDistance is the maximum distance between any two distinct critical points. If there are fewer than two critical points, return [-1, -1].\n Example 1:\nInput: head = [3,1]\nOutput: [-1,-1]\nExplanation: There are no critical points in [3,1].\nExample 2:\nInput: head = [5,3,1,2,5,1,2]\nOutput: [1,3]\nExplanation: There are three critical points:\n- [5,3,1,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.\n- [5,3,1,2,5,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.\n- [5,3,1,2,5,1,2]: The sixth node is a local minima because 1 is less than 5 and 2.\nThe minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\nThe maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.\nExample 3:\nInput: head = [1,3,2,2,3,2,2,2,7]\nOutput: [3,3]\nExplanation: There are two critical points:\n- [1,3,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.\n- [1,3,2,2,3,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.\nBoth the minimum and maximum distances are between the second and the fifth node.\nThus, minDistance and maxDistance is 5 - 2 = 3.\nNote that the last node is not considered a local maxima because it does not have a next node.\n Constraints:\nThe number of nodes in the list is in the range [2, 105].\n1 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-convert-number/discuss/1550007/Python3-bfs", "python_solutions": "class Solution:\n def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:\n ans = 0\n seen = {start}\n queue = deque([start])\n while queue: \n for _ in range(len(queue)): \n val = queue.popleft()\n if val == goal: return ans \n if 0 <= val <= 1000: \n for x in nums: \n for op in (add, sub, xor): \n if op(val, x) not in seen: \n seen.add(op(val, x))\n queue.append(op(val, x))\n ans += 1\n return -1", "slug": "minimum-operations-to-convert-number", "post_title": "[Python3] bfs", "user": "ye15", "upvotes": 17, "views": 1200, "problem_title": "minimum operations to convert number", "number": 2059, "acceptance": 0.473, "difficulty": "Medium", "__index_level_0__": 28540, "question": "You are given a 0-indexed integer array nums containing distinct numbers, an integer start, and an integer goal. There is an integer x that is initially set to start, and you want to perform operations on x such that it is converted to goal. You can perform the following operation repeatedly on the number x:\nIf 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:\nx + nums[i]\nx - nums[i]\nx ^ nums[i] (bitwise-XOR)\nNote that you can use each nums[i] any number of times in any order. Operations that set x to be out of the range 0 <= x <= 1000 are valid, but no more operations can be done afterward.\nReturn the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.\n Example 1:\nInput: nums = [2,4,12], start = 2, goal = 12\nOutput: 2\nExplanation: We can go from 2 \u2192 14 \u2192 12 with the following 2 operations.\n- 2 + 12 = 14\n- 14 - 2 = 12\nExample 2:\nInput: nums = [3,5,7], start = 0, goal = -4\nOutput: 2\nExplanation: We can go from 0 \u2192 3 \u2192 -4 with the following 2 operations. \n- 0 + 3 = 3\n- 3 - 7 = -4\nNote that the last operation sets x out of the range 0 <= x <= 1000, which is valid.\nExample 3:\nInput: nums = [2,8,16], start = 0, goal = 1\nOutput: -1\nExplanation: There is no way to convert 0 into 1.\n Constraints:\n1 <= nums.length <= 1000\n-109 <= nums[i], goal <= 109\n0 <= start <= 1000\nstart != goal\nAll the integers in nums are distinct." }, { "post_href": "https://leetcode.com/problems/check-if-an-original-string-exists-given-two-encoded-strings/discuss/1550012/Python3-dp", "python_solutions": "class Solution:\n def possiblyEquals(self, s1: str, s2: str) -> bool:\n \n def gg(s): \n \"\"\"Return possible length\"\"\"\n ans = [int(s)]\n if len(s) == 2: \n if s[1] != '0': ans.append(int(s[0]) + int(s[1]))\n return ans\n elif len(s) == 3: \n if s[1] != '0': ans.append(int(s[:1]) + int(s[1:]))\n if s[2] != '0': ans.append(int(s[:2]) + int(s[2:]))\n if s[1] != '0' and s[2] != '0': ans.append(int(s[0]) + int(s[1]) + int(s[2]))\n return ans \n \n @cache\n def fn(i, j, diff): \n \"\"\"Return True if s1[i:] matches s2[j:] with given differences.\"\"\"\n if i == len(s1) and j == len(s2): return diff == 0\n if i < len(s1) and s1[i].isdigit(): \n ii = i\n while ii < len(s1) and s1[ii].isdigit(): ii += 1\n for x in gg(s1[i:ii]): \n if fn(ii, j, diff-x): return True \n elif j < len(s2) and s2[j].isdigit(): \n jj = j \n while jj < len(s2) and s2[jj].isdigit(): jj += 1\n for x in gg(s2[j:jj]): \n if fn(i, jj, diff+x): return True \n elif diff == 0: \n if i == len(s1) or j == len(s2) or s1[i] != s2[j]: return False \n return fn(i+1, j+1, 0)\n elif diff > 0: \n if i == len(s1): return False \n return fn(i+1, j, diff-1)\n else: \n if j == len(s2): return False \n return fn(i, j+1, diff+1)\n \n return fn(0, 0, 0)", "slug": "check-if-an-original-string-exists-given-two-encoded-strings", "post_title": "[Python3] dp", "user": "ye15", "upvotes": 82, "views": 6200, "problem_title": "check if an original string exists given two encoded strings", "number": 2060, "acceptance": 0.407, "difficulty": "Hard", "__index_level_0__": 28550, "question": "An original string, consisting of lowercase English letters, can be encoded by the following steps:\nArbitrarily split it into a sequence of some number of non-empty substrings.\nArbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).\nConcatenate the sequence as the encoded string.\nFor example, one way to encode an original string \"abcdefghijklmnop\" might be:\nSplit it as a sequence: [\"ab\", \"cdefghijklmn\", \"o\", \"p\"].\nChoose the second and third elements to be replaced by their lengths, respectively. The sequence becomes [\"ab\", \"12\", \"1\", \"p\"].\nConcatenate the elements of the sequence to get the encoded string: \"ab121p\".\nGiven two encoded strings s1 and s2, consisting of lowercase English letters and digits 1-9 (inclusive), return true if there exists an original string that could be encoded as both s1 and s2. Otherwise, return false.\nNote: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.\n Example 1:\nInput: s1 = \"internationalization\", s2 = \"i18n\"\nOutput: true\nExplanation: It is possible that \"internationalization\" was the original string.\n- \"internationalization\" \n -> Split: [\"internationalization\"]\n -> Do not replace any element\n -> Concatenate: \"internationalization\", which is s1.\n- \"internationalization\"\n -> Split: [\"i\", \"nternationalizatio\", \"n\"]\n -> Replace: [\"i\", \"18\", \"n\"]\n -> Concatenate: \"i18n\", which is s2\nExample 2:\nInput: s1 = \"l123e\", s2 = \"44\"\nOutput: true\nExplanation: It is possible that \"leetcode\" was the original string.\n- \"leetcode\" \n -> Split: [\"l\", \"e\", \"et\", \"cod\", \"e\"]\n -> Replace: [\"l\", \"1\", \"2\", \"3\", \"e\"]\n -> Concatenate: \"l123e\", which is s1.\n- \"leetcode\" \n -> Split: [\"leet\", \"code\"]\n -> Replace: [\"4\", \"4\"]\n -> Concatenate: \"44\", which is s2.\nExample 3:\nInput: s1 = \"a5b\", s2 = \"c5b\"\nOutput: false\nExplanation: It is impossible.\n- The original string encoded as s1 must start with the letter 'a'.\n- The original string encoded as s2 must start with the letter 'c'.\n Constraints:\n1 <= s1.length, s2.length <= 40\ns1 and s2 consist of digits 1-9 (inclusive), and lowercase English letters only.\nThe number of consecutive digits in s1 and s2 does not exceed 3." }, { "post_href": "https://leetcode.com/problems/count-vowel-substrings-of-a-string/discuss/1563707/Python3-sliding-window-O(N)", "python_solutions": "class Solution:\n def countVowelSubstrings(self, word: str) -> int:\n ans = 0 \n freq = defaultdict(int)\n for i, x in enumerate(word): \n if x in \"aeiou\": \n if not i or word[i-1] not in \"aeiou\": \n jj = j = i # set anchor\n freq.clear()\n freq[x] += 1\n while len(freq) == 5 and all(freq.values()): \n freq[word[j]] -= 1\n j += 1\n ans += j - jj\n return ans", "slug": "count-vowel-substrings-of-a-string", "post_title": "[Python3] sliding window O(N)", "user": "ye15", "upvotes": 16, "views": 1900, "problem_title": "count vowel substrings of a string", "number": 2062, "acceptance": 0.659, "difficulty": "Easy", "__index_level_0__": 28552, "question": "A substring is a contiguous (non-empty) sequence of characters within a string.\nA vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.\nGiven a string word, return the number of vowel substrings in word.\n Example 1:\nInput: word = \"aeiouu\"\nOutput: 2\nExplanation: The vowel substrings of word are as follows (underlined):\n- \"aeiouu\"\n- \"aeiouu\"\nExample 2:\nInput: word = \"unicornarihan\"\nOutput: 0\nExplanation: Not all 5 vowels are present, so there are no vowel substrings.\nExample 3:\nInput: word = \"cuaieuouac\"\nOutput: 7\nExplanation: The vowel substrings of word are as follows (underlined):\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n- \"cuaieuouac\"\n Constraints:\n1 <= word.length <= 100\nword consists of lowercase English letters only." }, { "post_href": "https://leetcode.com/problems/vowels-of-all-substrings/discuss/1564075/Detailed-explanation-of-why-(len-pos)-*-(pos-%2B-1)-works", "python_solutions": "class Solution:\n def countVowels(self, word: str) -> int:\n count = 0\n sz = len(word)\n \n for pos in range(sz):\n if word[pos] in 'aeiou':\n count += (sz - pos) * (pos + 1)\n \n return count", "slug": "vowels-of-all-substrings", "post_title": "Detailed explanation of why (len - pos) * (pos + 1) works", "user": "bitmasker", "upvotes": 77, "views": 2000, "problem_title": "vowels of all substrings", "number": 2063, "acceptance": 0.551, "difficulty": "Medium", "__index_level_0__": 28564, "question": "Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word.\nA substring is a contiguous (non-empty) sequence of characters within a string.\nNote: Due to the large constraints, the answer may not fit in a signed 32-bit integer. Please be careful during the calculations.\n Example 1:\nInput: word = \"aba\"\nOutput: 6\nExplanation: \nAll possible substrings are: \"a\", \"ab\", \"aba\", \"b\", \"ba\", and \"a\".\n- \"b\" has 0 vowels in it\n- \"a\", \"ab\", \"ba\", and \"a\" have 1 vowel each\n- \"aba\" has 2 vowels in it\nHence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. \nExample 2:\nInput: word = \"abc\"\nOutput: 3\nExplanation: \nAll possible substrings are: \"a\", \"ab\", \"abc\", \"b\", \"bc\", and \"c\".\n- \"a\", \"ab\", and \"abc\" have 1 vowel each\n- \"b\", \"bc\", and \"c\" have 0 vowels each\nHence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.\nExample 3:\nInput: word = \"ltcd\"\nOutput: 0\nExplanation: There are no vowels in any substring of \"ltcd\".\n Constraints:\n1 <= word.length <= 105\nword consists of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimized-maximum-of-products-distributed-to-any-store/discuss/1563731/Python3-binary-search", "python_solutions": "class Solution:\n def minimizedMaximum(self, n: int, quantities: List[int]) -> int:\n lo, hi = 1, max(quantities)\n while lo < hi: \n mid = lo + hi >> 1\n if sum(ceil(qty/mid) for qty in quantities) <= n: hi = mid \n else: lo = mid + 1\n return lo", "slug": "minimized-maximum-of-products-distributed-to-any-store", "post_title": "[Python3] binary search", "user": "ye15", "upvotes": 9, "views": 296, "problem_title": "minimized maximum of products distributed to any store", "number": 2064, "acceptance": 0.5, "difficulty": "Medium", "__index_level_0__": 28577, "question": "You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.\nYou need to distribute all products to the retail stores following these rules:\nA store can only be given at most one product type but can be given any amount of it.\nAfter distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.\nReturn the minimum possible x.\n Example 1:\nInput: n = 6, quantities = [11,6]\nOutput: 3\nExplanation: One optimal way is:\n- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3\n- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3\nThe maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.\nExample 2:\nInput: n = 7, quantities = [15,10,10]\nOutput: 5\nExplanation: One optimal way is:\n- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5\n- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5\n- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5\nThe maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.\nExample 3:\nInput: n = 1, quantities = [100000]\nOutput: 100000\nExplanation: The only optimal way is:\n- The 100000 products of type 0 are distributed to the only store.\nThe maximum number of products given to any store is max(100000) = 100000.\n Constraints:\nm == quantities.length\n1 <= m <= n <= 105\n1 <= quantities[i] <= 105" }, { "post_href": "https://leetcode.com/problems/maximum-path-quality-of-a-graph/discuss/1564102/Python-DFS-and-BFS-solution", "python_solutions": "class Solution:\n def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:\n ans = 0\n graph = collections.defaultdict(dict)\n for u, v, t in edges:\n graph[u][v] = t\n graph[v][u] = t\n \n def dfs(curr, visited, score, cost):\n if curr == 0:\n nonlocal ans\n ans = max(ans, score)\n \n for nxt, time in graph[curr].items():\n if time <= cost:\n dfs(nxt, visited|set([nxt]), score+values[nxt]*(nxt not in visited), cost-time)\n \n dfs(0, set([0]), values[0], maxTime)\n return ans", "slug": "maximum-path-quality-of-a-graph", "post_title": "[Python] DFS and BFS solution", "user": "nightybear", "upvotes": 2, "views": 424, "problem_title": "maximum path quality of a graph", "number": 2065, "acceptance": 0.5760000000000001, "difficulty": "Hard", "__index_level_0__": 28583, "question": "There is an undirected graph with n nodes numbered from 0 to n - 1 (inclusive). You are given a 0-indexed integer array values where values[i] is the value of the ith node. You are also given a 0-indexed 2D integer array edges, where each edges[j] = [uj, vj, timej] indicates that there is an undirected edge between the nodes uj and vj, and it takes timej seconds to travel between the two nodes. Finally, you are given an integer maxTime.\nA valid path in the graph is any path that starts at node 0, ends at node 0, and takes at most maxTime seconds to complete. You may visit the same node multiple times. The quality of a valid path is the sum of the values of the unique nodes visited in the path (each node's value is added at most once to the sum).\nReturn the maximum quality of a valid path.\nNote: There are at most four edges connected to each node.\n Example 1:\nInput: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49\nOutput: 75\nExplanation:\nOne possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.\nExample 2:\nInput: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30\nOutput: 25\nExplanation:\nOne possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\nThe nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.\nExample 3:\nInput: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50\nOutput: 7\nExplanation:\nOne possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\nThe nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.\n Constraints:\nn == values.length\n1 <= n <= 1000\n0 <= values[i] <= 108\n0 <= edges.length <= 2000\nedges[j].length == 3 \n0 <= uj < vj <= n - 1\n10 <= timej, maxTime <= 100\nAll the pairs [uj, vj] are unique.\nThere are at most four edges connected to each node.\nThe graph may not be connected." }, { "post_href": "https://leetcode.com/problems/check-whether-two-strings-are-almost-equivalent/discuss/1576339/Python3-freq-table", "python_solutions": "class Solution:\n def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:\n freq = [0]*26\n for x in word1: freq[ord(x)-97] += 1\n for x in word2: freq[ord(x)-97] -= 1\n return all(abs(x) <= 3 for x in freq)", "slug": "check-whether-two-strings-are-almost-equivalent", "post_title": "[Python3] freq table", "user": "ye15", "upvotes": 2, "views": 140, "problem_title": "check whether two strings are almost equivalent", "number": 2068, "acceptance": 0.6459999999999999, "difficulty": "Easy", "__index_level_0__": 28589, "question": "Two strings word1 and word2 are considered almost equivalent if the differences between the frequencies of each letter from 'a' to 'z' between word1 and word2 is at most 3.\nGiven two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.\nThe frequency of a letter x is the number of times it occurs in the string.\n Example 1:\nInput: word1 = \"aaaa\", word2 = \"bccb\"\nOutput: false\nExplanation: There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\nThe difference is 4, which is more than the allowed 3.\nExample 2:\nInput: word1 = \"abcdeef\", word2 = \"abaaacc\"\nOutput: true\nExplanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 1 time in word1 and 4 times in word2. The difference is 3.\n- 'b' appears 1 time in word1 and 1 time in word2. The difference is 0.\n- 'c' appears 1 time in word1 and 2 times in word2. The difference is 1.\n- 'd' appears 1 time in word1 and 0 times in word2. The difference is 1.\n- 'e' appears 2 times in word1 and 0 times in word2. The difference is 2.\n- 'f' appears 1 time in word1 and 0 times in word2. The difference is 1.\nExample 3:\nInput: word1 = \"cccddabba\", word2 = \"babababab\"\nOutput: true\nExplanation: The differences between the frequencies of each letter in word1 and word2 are at most 3:\n- 'a' appears 2 times in word1 and 4 times in word2. The difference is 2.\n- 'b' appears 2 times in word1 and 5 times in word2. The difference is 3.\n- 'c' appears 3 times in word1 and 0 times in word2. The difference is 3.\n- 'd' appears 2 times in word1 and 0 times in word2. The difference is 2.\n Constraints:\nn == word1.length == word2.length\n1 <= n <= 100\nword1 and word2 consist only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/most-beautiful-item-for-each-query/discuss/1596922/Well-Explained-oror-99-faster-oror-Mainly-for-Beginners", "python_solutions": "class Solution:\n\tdef maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:\n\n\t\titems.sort()\n\t\tdic = dict()\n\t\tres = []\n\t\tgmax = 0\n\t\tfor p,b in items:\n\t\t\tgmax = max(b,gmax)\n\t\t\tdic[p] = gmax\n\n\t\tkeys = sorted(dic.keys())\n\t\tfor q in queries:\n\t\t\tind = bisect.bisect_left(keys,q)\n\t\t\tif ind int:\n # workers sorted in reverse order, tasks sorted in normal order\n def can_assign(n):\n task_i = 0\n task_temp = deque()\n n_pills = pills\n for i in range(n-1,-1,-1):\n while task_i < n and tasks[task_i] <= workers[i]+strength:\n task_temp.append(tasks[task_i])\n task_i += 1\n \n if len(task_temp) == 0:\n return False\n if workers[i] >= task_temp[0]:\n task_temp.popleft()\n elif n_pills > 0:\n task_temp.pop()\n n_pills -= 1\n else:\n return False\n return True\n \n tasks.sort()\n workers.sort(reverse = True)\n \n l = 0\n r = min(len(tasks), len(workers))\n res = -1\n while l <= r:\n m = (l+r)//2\n if can_assign(m):\n res = m\n l = m+1\n else:\n r = m-1\n return res", "slug": "maximum-number-of-tasks-you-can-assign", "post_title": "[python] binary search + greedy with deque O(nlogn)", "user": "hkwu6013", "upvotes": 9, "views": 403, "problem_title": "maximum number of tasks you can assign", "number": 2071, "acceptance": 0.346, "difficulty": "Hard", "__index_level_0__": 28622, "question": "You have n tasks and m workers. Each task has a strength requirement stored in a 0-indexed integer array tasks, with the ith task requiring tasks[i] strength to complete. The strength of each worker is stored in a 0-indexed integer array workers, with the jth worker having workers[j] strength. Each worker can only be assigned to a single task and must have a strength greater than or equal to the task's strength requirement (i.e., workers[j] >= tasks[i]).\nAdditionally, you have pills magical pills that will increase a worker's strength by strength. You can decide which workers receive the magical pills, however, you may only give each worker at most one magical pill.\nGiven the 0-indexed integer arrays tasks and workers and the integers pills and strength, return the maximum number of tasks that can be completed.\n Example 1:\nInput: tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1\nOutput: 3\nExplanation:\nWe can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 2 (0 + 1 >= 1)\n- Assign worker 1 to task 1 (3 >= 2)\n- Assign worker 2 to task 0 (3 >= 3)\nExample 2:\nInput: tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5\nOutput: 1\nExplanation:\nWe can assign the magical pill and tasks as follows:\n- Give the magical pill to worker 0.\n- Assign worker 0 to task 0 (0 + 5 >= 5)\nExample 3:\nInput: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\nOutput: 2\nExplanation:\nWe can assign the magical pills and tasks as follows:\n- Give the magical pill to worker 0 and worker 1.\n- Assign worker 0 to task 0 (0 + 10 >= 10)\n- Assign worker 1 to task 1 (10 + 10 >= 15)\nThe last pill is not given because it will not make any worker strong enough for the last task.\n Constraints:\nn == tasks.length\nm == workers.length\n1 <= n, m <= 5 * 104\n0 <= pills <= m\n0 <= tasks[i], workers[j], strength <= 109" }, { "post_href": "https://leetcode.com/problems/time-needed-to-buy-tickets/discuss/1577018/Python-or-BruteForce-and-O(N)", "python_solutions": "class Solution:\n def timeRequiredToBuy(self, tickets: list[int], k: int) -> int:\n secs = 0 \n i = 0\n while tickets[k] != 0:\n if tickets[i] != 0: # if it is zero that means we dont have to count it anymore\n tickets[i] -= 1 # decrease the value by 1 everytime\n secs += 1 # increase secs by 1\n\n i = (i + 1) % len(tickets) # since after getting to the end of the array we have to return to the first value so we use the mod operator\n \n return secs", "slug": "time-needed-to-buy-tickets", "post_title": "[Python] | BruteForce and O(N)", "user": "GigaMoksh", "upvotes": 30, "views": 1600, "problem_title": "time needed to buy tickets", "number": 2073, "acceptance": 0.62, "difficulty": "Easy", "__index_level_0__": 28625, "question": "There are n people in a line queuing to buy tickets, where the 0th person is at the front of the line and the (n - 1)th person is at the back of the line.\nYou are given a 0-indexed integer array tickets of length n where the number of tickets that the ith person would like to buy is tickets[i].\nEach person takes exactly 1 second to buy a ticket. A person can only buy 1 ticket at a time and has to go back to the end of the line (which happens instantaneously) in order to buy more tickets. If a person does not have any tickets left to buy, the person will leave the line.\nReturn the time taken for the person at position k (0-indexed) to finish buying tickets.\n Example 1:\nInput: tickets = [2,3,2], k = 2\nOutput: 6\nExplanation: \n- In the first pass, everyone in the line buys a ticket and the line becomes [1, 2, 1].\n- In the second pass, everyone in the line buys a ticket and the line becomes [0, 1, 0].\nThe person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.\nExample 2:\nInput: tickets = [5,1,1,1], k = 0\nOutput: 8\nExplanation:\n- In the first pass, everyone in the line buys a ticket and the line becomes [4, 0, 0, 0].\n- In the next 4 passes, only the person in position 0 is buying tickets.\nThe person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.\n Constraints:\nn == tickets.length\n1 <= n <= 100\n1 <= tickets[i] <= 100\n0 <= k < n" }, { "post_href": "https://leetcode.com/problems/reverse-nodes-in-even-length-groups/discuss/1577058/Python3-using-stack", "python_solutions": "class Solution:\n def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n n, node = 0, head\n while node: n, node = n+1, node.next\n \n k, node = 0, head \n while n: \n k += 1\n size = min(k, n)\n stack = []\n if not size & 1: \n temp = node \n for _ in range(size): \n stack.append(temp.val)\n temp = temp.next \n for _ in range(size): \n if stack: node.val = stack.pop()\n node = node.next \n n -= size\n return head", "slug": "reverse-nodes-in-even-length-groups", "post_title": "[Python3] using stack", "user": "ye15", "upvotes": 11, "views": 445, "problem_title": "reverse nodes in even length groups", "number": 2074, "acceptance": 0.521, "difficulty": "Medium", "__index_level_0__": 28656, "question": "You are given the head of a linked list.\nThe nodes in the linked list are sequentially assigned to non-empty groups whose lengths form the sequence of the natural numbers (1, 2, 3, 4, ...). The length of a group is the number of nodes assigned to it. In other words,\nThe 1st node is assigned to the first group.\nThe 2nd and the 3rd nodes are assigned to the second group.\nThe 4th, 5th, and 6th nodes are assigned to the third group, and so on.\nNote that the length of the last group may be less than or equal to 1 + the length of the second to last group.\nReverse the nodes in each group with an even length, and return the head of the modified linked list.\n Example 1:\nInput: head = [5,2,6,3,9,1,7,3,8,4]\nOutput: [5,6,2,3,9,1,4,8,3,7]\nExplanation:\n- The length of the first group is 1, which is odd, hence no reversal occurs.\n- The length of the second group is 2, which is even, hence the nodes are reversed.\n- The length of the third group is 3, which is odd, hence no reversal occurs.\n- The length of the last group is 4, which is even, hence the nodes are reversed.\nExample 2:\nInput: head = [1,1,0,6]\nOutput: [1,0,1,6]\nExplanation:\n- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 1. No reversal occurs.\nExample 3:\nInput: head = [1,1,0,6,5]\nOutput: [1,0,1,5,6]\nExplanation:\n- The length of the first group is 1. No reversal occurs.\n- The length of the second group is 2. The nodes are reversed.\n- The length of the last group is 2. The nodes are reversed.\n Constraints:\nThe number of nodes in the list is in the range [1, 105].\n0 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/decode-the-slanted-ciphertext/discuss/1576914/Jump-Columns-%2B-1", "python_solutions": "class Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n cols, res = len(encodedText) // rows, \"\"\n for i in range(cols):\n for j in range(i, len(encodedText), cols + 1):\n res += encodedText[j]\n return res.rstrip()", "slug": "decode-the-slanted-ciphertext", "post_title": "Jump Columns + 1", "user": "votrubac", "upvotes": 57, "views": 2000, "problem_title": "decode the slanted ciphertext", "number": 2075, "acceptance": 0.502, "difficulty": "Medium", "__index_level_0__": 28663, "question": "A string originalText is encoded using a slanted transposition cipher to a string encodedText with the help of a matrix having a fixed number of rows rows.\noriginalText is placed first in a top-left to bottom-right manner.\nThe blue cells are filled first, followed by the red cells, then the yellow cells, and so on, until we reach the end of originalText. The arrow indicates the order in which the cells are filled. All empty cells are filled with ' '. The number of columns is chosen such that the rightmost column will not be empty after filling in originalText.\nencodedText is then formed by appending all characters of the matrix in a row-wise fashion.\nThe characters in the blue cells are appended first to encodedText, then the red cells, and so on, and finally the yellow cells. The arrow indicates the order in which the cells are accessed.\nFor example, if originalText = \"cipher\" and rows = 3, then we encode it in the following manner:\nThe blue arrows depict how originalText is placed in the matrix, and the red arrows denote the order in which encodedText is formed. In the above example, encodedText = \"ch ie pr\".\nGiven the encoded string encodedText and number of rows rows, return the original string originalText.\nNote: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.\n Example 1:\nInput: encodedText = \"ch ie pr\", rows = 3\nOutput: \"cipher\"\nExplanation: This is the same example described in the problem description.\nExample 2:\nInput: encodedText = \"iveo eed l te olc\", rows = 4\nOutput: \"i love leetcode\"\nExplanation: The figure above denotes the matrix that was used to encode originalText. \nThe blue arrows show how we can find originalText from encodedText.\nExample 3:\nInput: encodedText = \"coding\", rows = 1\nOutput: \"coding\"\nExplanation: Since there is only 1 row, both originalText and encodedText are the same.\n Constraints:\n0 <= encodedText.length <= 106\nencodedText consists of lowercase English letters and ' ' only.\nencodedText is a valid encoding of some originalText that does not have trailing spaces.\n1 <= rows <= 1000\nThe testcases are generated such that there is only one possible originalText." }, { "post_href": "https://leetcode.com/problems/process-restricted-friend-requests/discuss/1577153/Python-272-ms36-MB-Maintain-connected-components-of-the-graph", "python_solutions": "class Solution:\n def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]: \n result = [False for _ in requests]\n \n connected_components = [{i} for i in range(n)]\n \n connected_comp_dict = {}\n for i in range(n):\n connected_comp_dict[i] = i\n \n banned_by_comps = [set() for i in range(n)]\n for res in restrictions:\n banned_by_comps[res[0]].add(res[1])\n banned_by_comps[res[1]].add(res[0])\n for i,r in enumerate(requests):\n n1, n2 = r[0], r[1]\n c1, c2 = connected_comp_dict[n1], connected_comp_dict[n2]\n if c1 == c2:\n result[i] = True\n else:\n if not (connected_components[c1].intersection(banned_by_comps[c2]) or connected_components[c2].intersection(banned_by_comps[c1])):\n connected_components[c1].update(connected_components[c2])\n banned_by_comps[c1].update(banned_by_comps[c2])\n for node in connected_components[c2]:\n connected_comp_dict[node] = c1\n result[i] = True\n \n return result", "slug": "process-restricted-friend-requests", "post_title": "[Python] [272 ms,36 MB] Maintain connected components of the graph", "user": "LonelyQuantum", "upvotes": 2, "views": 189, "problem_title": "process restricted friend requests", "number": 2076, "acceptance": 0.532, "difficulty": "Hard", "__index_level_0__": 28677, "question": "You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.\nYou are also given a 0-indexed 2D integer array restrictions, where restrictions[i] = [xi, yi] means that person xi and person yi cannot become friends, either directly or indirectly through other people.\nInitially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array requests, where requests[j] = [uj, vj] is a friend request between person uj and person vj.\nA friend request is successful if uj and vj can be friends. Each friend request is processed in the given order (i.e., requests[j] occurs before requests[j + 1]), and upon a successful request, uj and vj become direct friends for all future friend requests.\nReturn a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.\nNote: If uj and vj are already direct friends, the request is still successful.\n Example 1:\nInput: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 0 and person 2 can be friends, so they become direct friends. \nRequest 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).\nExample 2:\nInput: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\nOutput: [true,false]\nExplanation:\nRequest 0: Person 1 and person 2 can be friends, so they become direct friends.\nRequest 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).\nExample 3:\nInput: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\nOutput: [true,false,true,false]\nExplanation:\nRequest 0: Person 0 and person 4 can be friends, so they become direct friends.\nRequest 1: Person 1 and person 2 cannot be friends since they are directly restricted.\nRequest 2: Person 3 and person 1 can be friends, so they become direct friends.\nRequest 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).\n Constraints:\n2 <= n <= 1000\n0 <= restrictions.length <= 1000\nrestrictions[i].length == 2\n0 <= xi, yi <= n - 1\nxi != yi\n1 <= requests.length <= 1000\nrequests[j].length == 2\n0 <= uj, vj <= n - 1\nuj != vj" }, { "post_href": "https://leetcode.com/problems/two-furthest-houses-with-different-colors/discuss/1589119/Python3-one-of-end-points-will-be-used", "python_solutions": "class Solution:\n def maxDistance(self, colors: List[int]) -> int:\n ans = 0 \n for i, x in enumerate(colors): \n if x != colors[0]: ans = max(ans, i)\n if x != colors[-1]: ans = max(ans, len(colors)-1-i)\n return ans", "slug": "two-furthest-houses-with-different-colors", "post_title": "[Python3] one of end points will be used", "user": "ye15", "upvotes": 25, "views": 887, "problem_title": "two furthest houses with different colors", "number": 2078, "acceptance": 0.6709999999999999, "difficulty": "Easy", "__index_level_0__": 28678, "question": "There are n houses evenly lined up on the street, and each house is beautifully painted. You are given a 0-indexed integer array colors of length n, where colors[i] represents the color of the ith house.\nReturn the maximum distance between two houses with different colors.\nThe distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.\n Example 1:\nInput: colors = [1,1,1,6,1,1,1]\nOutput: 3\nExplanation: In the above image, color 1 is blue, and color 6 is red.\nThe furthest two houses with different colors are house 0 and house 3.\nHouse 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\nNote that houses 3 and 6 can also produce the optimal answer.\nExample 2:\nInput: colors = [1,8,3,8,3]\nOutput: 4\nExplanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\nThe furthest two houses with different colors are house 0 and house 4.\nHouse 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.\nExample 3:\nInput: colors = [0,1]\nOutput: 1\nExplanation: The furthest two houses with different colors are house 0 and house 1.\nHouse 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.\n Constraints:\nn == colors.length\n2 <= n <= 100\n0 <= colors[i] <= 100\nTest data are generated such that at least two houses have different colors." }, { "post_href": "https://leetcode.com/problems/watering-plants/discuss/1589030/Python3-simulation", "python_solutions": "class Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n ans = 0\n can = capacity\n for i, x in enumerate(plants): \n if can < x: \n ans += 2*i\n can = capacity\n ans += 1\n can -= x\n return ans", "slug": "watering-plants", "post_title": "[Python3] simulation", "user": "ye15", "upvotes": 19, "views": 1000, "problem_title": "watering plants", "number": 2079, "acceptance": 0.8, "difficulty": "Medium", "__index_level_0__": 28701, "question": "You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at.\nEach plant needs a specific amount of water. You will water the plants in the following way:\nWater the plants in order from left to right.\nAfter watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can.\nYou cannot refill the watering can early.\nYou are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants.\n Example 1:\nInput: plants = [2,2,3,3], capacity = 5\nOutput: 14\nExplanation: Start at the river with a full watering can:\n- Walk to plant 0 (1 step) and water it. Watering can has 3 units of water.\n- Walk to plant 1 (1 step) and water it. Watering can has 1 unit of water.\n- Since you cannot completely water plant 2, walk back to the river to refill (2 steps).\n- Walk to plant 2 (3 steps) and water it. Watering can has 2 units of water.\n- Since you cannot completely water plant 3, walk back to the river to refill (3 steps).\n- Walk to plant 3 (4 steps) and water it.\nSteps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.\nExample 2:\nInput: plants = [1,1,1,4,2,3], capacity = 4\nOutput: 30\nExplanation: Start at the river with a full watering can:\n- Water plants 0, 1, and 2 (3 steps). Return to river (3 steps).\n- Water plant 3 (4 steps). Return to river (4 steps).\n- Water plant 4 (5 steps). Return to river (5 steps).\n- Water plant 5 (6 steps).\nSteps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.\nExample 3:\nInput: plants = [7,7,7,7,7,7,7], capacity = 8\nOutput: 49\nExplanation: You have to refill before watering each plant.\nSteps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.\n Constraints:\nn == plants.length\n1 <= n <= 1000\n1 <= plants[i] <= 106\nmax(plants[i]) <= capacity <= 109" }, { "post_href": "https://leetcode.com/problems/sum-of-k-mirror-numbers/discuss/1589048/Python3-enumerate-k-symmetric-numbers", "python_solutions": "class Solution:\n def kMirror(self, k: int, n: int) -> int:\n \n def fn(x):\n \"\"\"Return next k-symmetric number.\"\"\"\n n = len(x)//2\n for i in range(n, len(x)): \n if int(x[i])+1 < k: \n x[i] = x[~i] = str(int(x[i])+1)\n for ii in range(n, i): x[ii] = x[~ii] = '0'\n return x\n return [\"1\"] + [\"0\"]*(len(x)-1) + [\"1\"]\n \n x = [\"0\"]\n ans = 0\n for _ in range(n): \n while True: \n x = fn(x)\n val = int(\"\".join(x), k)\n if str(val)[::-1] == str(val): break\n ans += val\n return ans", "slug": "sum-of-k-mirror-numbers", "post_title": "[Python3] enumerate k-symmetric numbers", "user": "ye15", "upvotes": 41, "views": 2700, "problem_title": "sum of k mirror numbers", "number": 2081, "acceptance": 0.421, "difficulty": "Hard", "__index_level_0__": 28741, "question": "A k-mirror number is a positive integer without leading zeros that reads the same both forward and backward in base-10 as well as in base-k.\nFor example, 9 is a 2-mirror number. The representation of 9 in base-10 and base-2 are 9 and 1001 respectively, which read the same both forward and backward.\nOn the contrary, 4 is not a 2-mirror number. The representation of 4 in base-2 is 100, which does not read the same both forward and backward.\nGiven the base k and the number n, return the sum of the n smallest k-mirror numbers.\n Example 1:\nInput: k = 2, n = 5\nOutput: 25\nExplanation:\nThe 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:\n base-10 base-2\n 1 1\n 3 11\n 5 101\n 7 111\n 9 1001\nTheir sum = 1 + 3 + 5 + 7 + 9 = 25. \nExample 2:\nInput: k = 3, n = 7\nOutput: 499\nExplanation:\nThe 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:\n base-10 base-3\n 1 1\n 2 2\n 4 11\n 8 22\n 121 11111\n 151 12121\n 212 21212\nTheir sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.\nExample 3:\nInput: k = 7, n = 17\nOutput: 20379000\nExplanation: The 17 smallest 7-mirror numbers are:\n1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596\n Constraints:\n2 <= k <= 9\n1 <= n <= 30" }, { "post_href": "https://leetcode.com/problems/count-common-words-with-one-occurrence/discuss/1598944/Python3-2-line-freq-table", "python_solutions": "class Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n freq1, freq2 = Counter(words1), Counter(words2)\n return len({w for w, v in freq1.items() if v == 1} & {w for w, v in freq2.items() if v == 1})", "slug": "count-common-words-with-one-occurrence", "post_title": "[Python3] 2-line freq table", "user": "ye15", "upvotes": 10, "views": 1200, "problem_title": "count common words with one occurrence", "number": 2085, "acceptance": 0.6970000000000001, "difficulty": "Easy", "__index_level_0__": 28746, "question": "Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.\n Example 1:\nInput: words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]\nOutput: 2\nExplanation:\n- \"leetcode\" appears exactly once in each of the two arrays. We count this string.\n- \"amazing\" appears exactly once in each of the two arrays. We count this string.\n- \"is\" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.\n- \"as\" appears once in words1, but does not appear in words2. We do not count this string.\nThus, there are 2 strings that appear exactly once in each of the two arrays.\nExample 2:\nInput: words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]\nOutput: 0\nExplanation: There are no strings that appear in each of the two arrays.\nExample 3:\nInput: words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]\nOutput: 1\nExplanation: The only string that appears exactly once in each of the two arrays is \"ab\".\n Constraints:\n1 <= words1.length, words2.length <= 1000\n1 <= words1[i].length, words2[j].length <= 30\nwords1[i] and words2[j] consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/minimum-number-of-food-buckets-to-feed-the-hamsters/discuss/1598954/Python3-greedy", "python_solutions": "class Solution:\n def minimumBuckets(self, street: str) -> int:\n street = list(street)\n ans = 0 \n for i, ch in enumerate(street): \n if ch == 'H' and (i == 0 or street[i-1] != '#'): \n if i+1 < len(street) and street[i+1] == '.': street[i+1] = '#'\n elif i and street[i-1] == '.': street[i-1] = '#'\n else: return -1\n ans += 1\n return ans", "slug": "minimum-number-of-food-buckets-to-feed-the-hamsters", "post_title": "[Python3] greedy", "user": "ye15", "upvotes": 10, "views": 541, "problem_title": "minimum number of food buckets to feed the hamsters", "number": 2086, "acceptance": 0.451, "difficulty": "Medium", "__index_level_0__": 28788, "question": "You are given a 0-indexed string hamsters where hamsters[i] is either:\n'H' indicating that there is a hamster at index i, or\n'.' indicating that index i is empty.\nYou will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index i can be fed if you place a food bucket at index i - 1 and/or at index i + 1.\nReturn the minimum number of food buckets you should place at empty indices to feed all the hamsters or -1 if it is impossible to feed all of them.\n Example 1:\nInput: hamsters = \"H..H\"\nOutput: 2\nExplanation: We place two food buckets at indices 1 and 2.\nIt can be shown that if we place only one food bucket, one of the hamsters will not be fed.\nExample 2:\nInput: hamsters = \".H.H.\"\nOutput: 1\nExplanation: We place one food bucket at index 2.\nExample 3:\nInput: hamsters = \".HHH.\"\nOutput: -1\nExplanation: If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat.\n Constraints:\n1 <= hamsters.length <= 105\nhamsters[i] is either'H' or '.'." }, { "post_href": "https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/discuss/1598918/Greedy-Approach-oror-Well-Coded-and-Explained-oror-95-faster", "python_solutions": "class Solution:\ndef minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n src_x,src_y = startPos[0],startPos[1]\n end_x,end_y = homePos[0], homePos[1]\n \n if src_x < end_x:\n rc = sum(rowCosts[src_x+1:end_x+1])\n elif src_x > end_x:\n rc = sum(rowCosts[end_x:src_x])\n else:\n rc=0\n \n if src_y < end_y:\n cc = sum(colCosts[src_y+1:end_y+1])\n elif src_y > end_y:\n cc = sum(colCosts[end_y:src_y])\n else:\n cc=0\n \n return cc+rc", "slug": "minimum-cost-homecoming-of-a-robot-in-a-grid", "post_title": "\ud83d\udccc\ud83d\udccc Greedy Approach || Well-Coded and Explained || 95% faster \ud83d\udc0d", "user": "abhi9Rai", "upvotes": 3, "views": 276, "problem_title": "minimum cost homecoming of a robot in a grid", "number": 2087, "acceptance": 0.513, "difficulty": "Medium", "__index_level_0__": 28797, "question": "There is an m x n grid, where (0, 0) is the top-left cell and (m - 1, n - 1) is the bottom-right cell. You are given an integer array startPos where startPos = [startrow, startcol] indicates that initially, a robot is at the cell (startrow, startcol). You are also given an integer array homePos where homePos = [homerow, homecol] indicates that its home is at the cell (homerow, homecol).\nThe robot needs to go to its home. It can move one cell in four directions: left, right, up, or down, and it can not move outside the boundary. Every move incurs some cost. You are further given two 0-indexed integer arrays: rowCosts of length m and colCosts of length n.\nIf the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].\nIf the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].\nReturn the minimum total cost for this robot to return home.\n Example 1:\nInput: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\nOutput: 18\nExplanation: One optimal path is that:\nStarting from (1, 0)\n-> It goes down to (2, 0). This move costs rowCosts[2] = 3.\n-> It goes right to (2, 1). This move costs colCosts[1] = 2.\n-> It goes right to (2, 2). This move costs colCosts[2] = 6.\n-> It goes right to (2, 3). This move costs colCosts[3] = 7.\nThe total cost is 3 + 2 + 6 + 7 = 18\nExample 2:\nInput: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\nOutput: 0\nExplanation: The robot is already at its home. Since no moves occur, the total cost is 0.\n Constraints:\nm == rowCosts.length\nn == colCosts.length\n1 <= m, n <= 105\n0 <= rowCosts[r], colCosts[c] <= 104\nstartPos.length == 2\nhomePos.length == 2\n0 <= startrow, homerow < m\n0 <= startcol, homecol < n" }, { "post_href": "https://leetcode.com/problems/count-fertile-pyramids-in-a-land/discuss/1598873/Python3-just-count", "python_solutions": "class Solution:\n def countPyramids(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n vals = [[inf]*n for _ in range(m)]\n for i in range(m):\n for j in range(n): \n if grid[i][j] == 0: vals[i][j] = 0\n elif j == 0: vals[i][j] = 1\n else: vals[i][j] = min(vals[i][j], 1 + vals[i][j-1])\n if grid[i][~j] == 0: vals[i][~j] = 0\n elif j == 0: vals[i][~j] = 1\n else: vals[i][~j] = min(vals[i][~j], 1 + vals[i][~j+1])\n \n def fn(vals): \n \"\"\"Return count of pyramid in given grid.\"\"\"\n ans = 0 \n for j in range(n):\n width = 0\n for i in range(m): \n if vals[i][j]: width = min(width+1, vals[i][j])\n else: width = 0\n ans += max(0, width-1)\n return ans \n \n return fn(vals) + fn(vals[::-1])", "slug": "count-fertile-pyramids-in-a-land", "post_title": "[Python3] just count", "user": "ye15", "upvotes": 5, "views": 415, "problem_title": "count fertile pyramids in a land", "number": 2088, "acceptance": 0.635, "difficulty": "Hard", "__index_level_0__": 28802, "question": "A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren.\nA pyramidal plot of land can be defined as a set of cells with the following criteria:\nThe number of cells in the set has to be greater than 1 and all cells must be fertile.\nThe apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r).\nAn inverse pyramidal plot of land can be defined as a set of cells with similar criteria:\nThe number of cells in the set has to be greater than 1 and all cells must be fertile.\nThe apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).\nSome examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.\nGiven a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.\n Example 1:\nInput: grid = [[0,1,1,0],[1,1,1,1]]\nOutput: 2\nExplanation: The 2 possible pyramidal plots are shown in blue and red respectively.\nThere are no inverse pyramidal plots in this grid. \nHence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.\nExample 2:\nInput: grid = [[1,1,1],[1,1,1]]\nOutput: 2\nExplanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \nHence the total number of plots is 1 + 1 = 2.\nExample 3:\nInput: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]\nOutput: 13\nExplanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\nThere are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\nThe total number of plots is 7 + 6 = 13.\n Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 1000\n1 <= m * n <= 105\ngrid[i][j] is either 0 or 1." }, { "post_href": "https://leetcode.com/problems/find-target-indices-after-sorting-array/discuss/2024498/Python-Solution-%2B-One-Line!", "python_solutions": "class Solution:\n def targetIndices(self, nums, target):\n ans = []\n for i,num in enumerate(sorted(nums)):\n if num == target: ans.append(i)\n return ans", "slug": "find-target-indices-after-sorting-array", "post_title": "Python - Solution + One-Line!", "user": "domthedeveloper", "upvotes": 10, "views": 377, "problem_title": "find target indices after sorting array", "number": 2089, "acceptance": 0.7659999999999999, "difficulty": "Easy", "__index_level_0__": 28813, "question": "You are given a 0-indexed integer array nums and a target element target.\nA target index is an index i such that nums[i] == target.\nReturn a list of the target indices of nums after sorting nums in non-decreasing order. If there are no target indices, return an empty list. The returned list must be sorted in increasing order.\n Example 1:\nInput: nums = [1,2,5,2,3], target = 2\nOutput: [1,2]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe indices where nums[i] == 2 are 1 and 2.\nExample 2:\nInput: nums = [1,2,5,2,3], target = 3\nOutput: [3]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 3 is 3.\nExample 3:\nInput: nums = [1,2,5,2,3], target = 5\nOutput: [4]\nExplanation: After sorting, nums is [1,2,2,3,5].\nThe index where nums[i] == 5 is 4.\n Constraints:\n1 <= nums.length <= 100\n1 <= nums[i], target <= 100" }, { "post_href": "https://leetcode.com/problems/k-radius-subarray-averages/discuss/1599973/Python-3-or-Sliding-Window-or-Illustration-with-picture", "python_solutions": "class Solution:\n def getAverages(self, nums: List[int], k: int) -> List[int]:\n res = [-1]*len(nums)\n\n left, curWindowSum, diameter = 0, 0, 2*k+1\n for right in range(len(nums)):\n curWindowSum += nums[right]\n if (right-left+1 >= diameter):\n res[left+k] = curWindowSum//diameter\n curWindowSum -= nums[left]\n left += 1\n return res", "slug": "k-radius-subarray-averages", "post_title": "Python 3 | Sliding Window | Illustration with picture", "user": "ndus", "upvotes": 48, "views": 1300, "problem_title": "k radius subarray averages", "number": 2090, "acceptance": 0.426, "difficulty": "Medium", "__index_level_0__": 28861, "question": "You are given a 0-indexed array nums of n integers, and an integer k.\nThe k-radius average for a subarray of nums centered at some index i with the radius k is the average of all elements in nums between the indices i - k and i + k (inclusive). If there are less than k elements before or after the index i, then the k-radius average is -1.\nBuild and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.\nThe average of x elements is the sum of the x elements divided by x, using integer division. The integer division truncates toward zero, which means losing its fractional part.\nFor example, the average of four elements 2, 3, 1, and 5 is (2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75, which truncates to 2.\n Example 1:\nInput: nums = [7,4,3,9,1,8,5,2,6], k = 3\nOutput: [-1,-1,-1,5,4,4,-1,-1,-1]\nExplanation:\n- avg[0], avg[1], and avg[2] are -1 because there are less than k elements before each index.\n- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.\n Using integer division, avg[3] = 37 / 7 = 5.\n- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.\n- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.\n- avg[6], avg[7], and avg[8] are -1 because there are less than k elements after each index.\nExample 2:\nInput: nums = [100000], k = 0\nOutput: [100000]\nExplanation:\n- The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.\nExample 3:\nInput: nums = [8], k = 100000\nOutput: [-1]\nExplanation: \n- avg[0] is -1 because there are less than k elements before and after index 0.\n Constraints:\nn == nums.length\n1 <= n <= 105\n0 <= nums[i], k <= 105" }, { "post_href": "https://leetcode.com/problems/removing-minimum-and-maximum-from-array/discuss/1599862/Python3-3-candidates", "python_solutions": "class Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n imin = nums.index(min(nums))\n imax = nums.index(max(nums))\n return min(max(imin, imax)+1, len(nums)-min(imin, imax), len(nums)+1+min(imin, imax)-max(imin, imax))", "slug": "removing-minimum-and-maximum-from-array", "post_title": "[Python3] 3 candidates", "user": "ye15", "upvotes": 5, "views": 226, "problem_title": "removing minimum and maximum from array", "number": 2091, "acceptance": 0.5660000000000001, "difficulty": "Medium", "__index_level_0__": 28879, "question": "You are given a 0-indexed array of distinct integers nums.\nThere is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.\nA deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.\nReturn the minimum number of deletions it would take to remove both the minimum and maximum element from the array.\n Example 1:\nInput: nums = [2,10,7,5,4,1,8,6]\nOutput: 5\nExplanation: \nThe minimum element in the array is nums[5], which is 1.\nThe maximum element in the array is nums[1], which is 10.\nWe can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\nThis results in 2 + 3 = 5 deletions, which is the minimum number possible.\nExample 2:\nInput: nums = [0,-4,19,1,8,-2,-3,5]\nOutput: 3\nExplanation: \nThe minimum element in the array is nums[1], which is -4.\nThe maximum element in the array is nums[2], which is 19.\nWe can remove both the minimum and maximum by removing 3 elements from the front.\nThis results in only 3 deletions, which is the minimum number possible.\nExample 3:\nInput: nums = [101]\nOutput: 1\nExplanation: \nThere is only one element in the array, which makes it both the minimum and maximum element.\nWe can remove it with 1 deletion.\n Constraints:\n1 <= nums.length <= 105\n-105 <= nums[i] <= 105\nThe integers in nums are distinct." }, { "post_href": "https://leetcode.com/problems/find-all-people-with-secret/discuss/1599870/Python3-BFS-or-DFS-by-group", "python_solutions": "class Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n can = {0, firstPerson}\n for _, grp in groupby(sorted(meetings, key=lambda x: x[2]), key=lambda x: x[2]): \n queue = set()\n graph = defaultdict(list)\n for x, y, _ in grp: \n graph[x].append(y)\n graph[y].append(x)\n if x in can: queue.add(x)\n if y in can: queue.add(y)\n \n queue = deque(queue)\n while queue: \n x = queue.popleft()\n for y in graph[x]: \n if y not in can: \n can.add(y)\n queue.append(y)\n return can", "slug": "find-all-people-with-secret", "post_title": "[Python3] BFS or DFS by group", "user": "ye15", "upvotes": 29, "views": 3100, "problem_title": "find all people with secret", "number": 2092, "acceptance": 0.342, "difficulty": "Hard", "__index_level_0__": 28900, "question": "You are given an integer n indicating there are n people numbered from 0 to n - 1. You are also given a 0-indexed 2D integer array meetings where meetings[i] = [xi, yi, timei] indicates that person xi and person yi have a meeting at timei. A person may attend multiple meetings at the same time. Finally, you are given an integer firstPerson.\nPerson 0 has a secret and initially shares the secret with a person firstPerson at time 0. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person xi has the secret at timei, then they will share the secret with person yi, and vice versa.\nThe secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame.\nReturn a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.\n Example 1:\nInput: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1\nOutput: [0,1,2,3,5]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 5, person 1 shares the secret with person 2.\nAt time 8, person 2 shares the secret with person 3.\nAt time 10, person 1 shares the secret with person 5.\nThus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.\nExample 2:\nInput: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3\nOutput: [0,1,3]\nExplanation:\nAt time 0, person 0 shares the secret with person 3.\nAt time 2, neither person 1 nor person 2 know the secret.\nAt time 3, person 3 shares the secret with person 0 and person 1.\nThus, people 0, 1, and 3 know the secret after all the meetings.\nExample 3:\nInput: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1\nOutput: [0,1,2,3,4]\nExplanation:\nAt time 0, person 0 shares the secret with person 1.\nAt time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\nNote that person 2 can share the secret at the same time as receiving it.\nAt time 2, person 3 shares the secret with person 4.\nThus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.\n Constraints:\n2 <= n <= 105\n1 <= meetings.length <= 105\nmeetings[i].length == 3\n0 <= xi, yi <= n - 1\nxi != yi\n1 <= timei <= 105\n1 <= firstPerson <= n - 1" }, { "post_href": "https://leetcode.com/problems/finding-3-digit-even-numbers/discuss/1611987/Python3-brute-force", "python_solutions": "class Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n ans = set()\n for x, y, z in permutations(digits, 3): \n if x != 0 and z & 1 == 0: \n ans.add(100*x + 10*y + z) \n return sorted(ans)", "slug": "finding-3-digit-even-numbers", "post_title": "[Python3] brute-force", "user": "ye15", "upvotes": 29, "views": 1900, "problem_title": "finding 3 digit even numbers", "number": 2094, "acceptance": 0.574, "difficulty": "Easy", "__index_level_0__": 28911, "question": "You are given an integer array digits, where each element is a digit. The array may contain duplicates.\nYou need to find all the unique integers that follow the given requirements:\nThe integer consists of the concatenation of three elements from digits in any arbitrary order.\nThe integer does not have leading zeros.\nThe integer is even.\nFor example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements.\nReturn a sorted array of the unique integers.\n Example 1:\nInput: digits = [2,1,3,0]\nOutput: [102,120,130,132,210,230,302,310,312,320]\nExplanation: All the possible integers that follow the requirements are in the output array. \nNotice that there are no odd integers or integers with leading zeros.\nExample 2:\nInput: digits = [2,2,8,8,2]\nOutput: [222,228,282,288,822,828,882]\nExplanation: The same digit can be used as many times as it appears in digits. \nIn this example, the digit 8 is used twice each time in 288, 828, and 882. \nExample 3:\nInput: digits = [3,7,5]\nOutput: []\nExplanation: No even integers can be formed using the given digits.\n Constraints:\n3 <= digits.length <= 100\n0 <= digits[i] <= 9" }, { "post_href": "https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/discuss/2700533/Fastest-python-solution-TC%3A-O(N)SC%3A-O(1)", "python_solutions": "class Solution:\n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n slow,fast,prev=head,head,None\n while fast and fast.next:\n prev=slow\n slow=slow.next\n fast=fast.next.next\n if prev==None:\n return None\n prev.next=slow.next\n return head", "slug": "delete-the-middle-node-of-a-linked-list", "post_title": "Fastest python solution TC: O(N),SC: O(1)", "user": "shubham_1307", "upvotes": 12, "views": 1200, "problem_title": "delete the middle node of a linked list", "number": 2095, "acceptance": 0.605, "difficulty": "Medium", "__index_level_0__": 28930, "question": "You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.\nThe middle node of a linked list of size n is the \u230an / 2\u230bth node from the start using 0-based indexing, where \u230ax\u230b denotes the largest integer less than or equal to x.\nFor n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.\n Example 1:\nInput: head = [1,3,4,7,1,2,6]\nOutput: [1,3,4,1,2,6]\nExplanation:\nThe above figure represents the given linked list. The indices of the nodes are written below.\nSince n = 7, node 3 with value 7 is the middle node, which is marked in red.\nWe return the new list after removing this node. \nExample 2:\nInput: head = [1,2,3,4]\nOutput: [1,2,4]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 4, node 2 with value 3 is the middle node, which is marked in red.\nExample 3:\nInput: head = [2,1]\nOutput: [2]\nExplanation:\nThe above figure represents the given linked list.\nFor n = 2, node 1 with value 1 is the middle node, which is marked in red.\nNode 0 with value 2 is the only node remaining after removing node 1.\n Constraints:\nThe number of nodes in the list is in the range [1, 105].\n1 <= Node.val <= 105" }, { "post_href": "https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/discuss/1612179/Python3-lca", "python_solutions": "class Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \n def lca(node): \n \"\"\"Return lowest common ancestor of start and dest nodes.\"\"\"\n if not node or node.val in (startValue , destValue): return node \n left, right = lca(node.left), lca(node.right)\n return node if left and right else left or right\n \n root = lca(root) # only this sub-tree matters\n \n ps = pd = \"\"\n stack = [(root, \"\")]\n while stack: \n node, path = stack.pop()\n if node.val == startValue: ps = path \n if node.val == destValue: pd = path\n if node.left: stack.append((node.left, path + \"L\"))\n if node.right: stack.append((node.right, path + \"R\"))\n return \"U\"*len(ps) + pd", "slug": "step-by-step-directions-from-a-binary-tree-node-to-another", "post_title": "[Python3] lca", "user": "ye15", "upvotes": 108, "views": 8100, "problem_title": "step by step directions from a binary tree node to another", "number": 2096, "acceptance": 0.488, "difficulty": "Medium", "__index_level_0__": 28951, "question": "You are given the root of a binary tree with n nodes. Each node is uniquely assigned a value from 1 to n. You are also given an integer startValue representing the value of the start node s, and a different integer destValue representing the value of the destination node t.\nFind the shortest path starting from node s and ending at node t. Generate step-by-step directions of such path as a string consisting of only the uppercase letters 'L', 'R', and 'U'. Each letter indicates a specific direction:\n'L' means to go from a node to its left child node.\n'R' means to go from a node to its right child node.\n'U' means to go from a node to its parent node.\nReturn the step-by-step directions of the shortest path from node s to node t.\n Example 1:\nInput: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\nOutput: \"UURL\"\nExplanation: The shortest path is: 3 \u2192 1 \u2192 5 \u2192 2 \u2192 6.\nExample 2:\nInput: root = [2,1], startValue = 2, destValue = 1\nOutput: \"L\"\nExplanation: The shortest path is: 2 \u2192 1.\n Constraints:\nThe number of nodes in the tree is n.\n2 <= n <= 105\n1 <= Node.val <= n\nAll the values in the tree are unique.\n1 <= startValue, destValue <= n\nstartValue != destValue" }, { "post_href": "https://leetcode.com/problems/valid-arrangement-of-pairs/discuss/1612010/Python3-Hierholzer's-algo", "python_solutions": "class Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n graph = defaultdict(list)\n degree = defaultdict(int) # net out degree \n for x, y in pairs: \n graph[x].append(y)\n degree[x] += 1\n degree[y] -= 1\n \n for k in degree: \n if degree[k] == 1: \n x = k\n break \n \n ans = []\n\n def fn(x): \n \"\"\"Return Eulerian path via dfs.\"\"\"\n while graph[x]: fn(graph[x].pop()) \n ans.append(x)\n \n fn(x)\n ans.reverse()\n return [[ans[i], ans[i+1]] for i in range(len(ans)-1)]", "slug": "valid-arrangement-of-pairs", "post_title": "[Python3] Hierholzer's algo", "user": "ye15", "upvotes": 32, "views": 1400, "problem_title": "valid arrangement of pairs", "number": 2097, "acceptance": 0.41, "difficulty": "Hard", "__index_level_0__": 28970, "question": "You are given a 0-indexed 2D integer array pairs where pairs[i] = [starti, endi]. An arrangement of pairs is valid if for every index i where 1 <= i < pairs.length, we have endi-1 == starti.\nReturn any valid arrangement of pairs.\nNote: The inputs will be generated such that there exists a valid arrangement of pairs.\n Example 1:\nInput: pairs = [[5,1],[4,5],[11,9],[9,4]]\nOutput: [[11,9],[9,4],[4,5],[5,1]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 9 == 9 = start1 \nend1 = 4 == 4 = start2\nend2 = 5 == 5 = start3\nExample 2:\nInput: pairs = [[1,3],[3,2],[2,1]]\nOutput: [[1,3],[3,2],[2,1]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 3 == 3 = start1\nend1 = 2 == 2 = start2\nThe arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.\nExample 3:\nInput: pairs = [[1,2],[1,3],[2,1]]\nOutput: [[1,2],[2,1],[1,3]]\nExplanation:\nThis is a valid arrangement since endi-1 always equals starti.\nend0 = 2 == 2 = start1\nend1 = 1 == 1 = start2\n Constraints:\n1 <= pairs.length <= 105\npairs[i].length == 2\n0 <= starti, endi <= 109\nstarti != endi\nNo two pairs are exactly the same.\nThere exists a valid arrangement of pairs." }, { "post_href": "https://leetcode.com/problems/find-subsequence-of-length-k-with-the-largest-sum/discuss/1705383/Python-Simple-Solution-or-100-Time", "python_solutions": "class Solution:\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n tuple_heap = [] # Stores (value, index) as min heap\n for i, val in enumerate(nums):\n if len(tuple_heap) == k:\n heappushpop(tuple_heap, (val, i)) # To prevent size of heap growing larger than k\n else:\n heappush(tuple_heap, (val, i))\n\t\t# heap now contains only the k largest elements with their indices as well.\n tuple_heap.sort(key=lambda x: x[1]) # To get the original order of values. That is why we sort it by index(x[1]) & not value(x[0])\n ans = []\n for i in tuple_heap:\n ans.append(i[0])\n return ans", "slug": "find-subsequence-of-length-k-with-the-largest-sum", "post_title": "Python Simple Solution | 100% Time", "user": "anCoderr", "upvotes": 10, "views": 806, "problem_title": "find subsequence of length k with the largest sum", "number": 2099, "acceptance": 0.425, "difficulty": "Easy", "__index_level_0__": 28973, "question": "You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum.\nReturn any such subsequence as an integer array of length k.\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n Example 1:\nInput: nums = [2,1,3,3], k = 2\nOutput: [3,3]\nExplanation:\nThe subsequence has the largest sum of 3 + 3 = 6.\nExample 2:\nInput: nums = [-1,-2,3,4], k = 3\nOutput: [-1,3,4]\nExplanation: \nThe subsequence has the largest sum of -1 + 3 + 4 = 6.\nExample 3:\nInput: nums = [3,4,3,3], k = 2\nOutput: [3,4]\nExplanation:\nThe subsequence has the largest sum of 3 + 4 = 7. \nAnother possible subsequence is [4, 3].\n Constraints:\n1 <= nums.length <= 1000\n-105 <= nums[i] <= 105\n1 <= k <= nums.length" }, { "post_href": "https://leetcode.com/problems/find-good-days-to-rob-the-bank/discuss/1623325/Python3-prefix-and-suffix", "python_solutions": "class Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n suffix = [0]*len(security)\n for i in range(len(security)-2, 0, -1): \n if security[i] <= security[i+1]: suffix[i] = suffix[i+1] + 1\n \n ans = []\n prefix = 0\n for i in range(len(security)-time): \n if i and security[i-1] >= security[i]: prefix += 1\n else: prefix = 0\n if prefix >= time and suffix[i] >= time: ans.append(i)\n return ans", "slug": "find-good-days-to-rob-the-bank", "post_title": "[Python3] prefix & suffix", "user": "ye15", "upvotes": 5, "views": 243, "problem_title": "find good days to rob the bank", "number": 2100, "acceptance": 0.492, "difficulty": "Medium", "__index_level_0__": 29003, "question": "You and a gang of thieves are planning on robbing a bank. You are given a 0-indexed integer array security, where security[i] is the number of guards on duty on the ith day. The days are numbered starting from 0. You are also given an integer time.\nThe ith day is a good day to rob the bank if:\nThere are at least time days before and after the ith day,\nThe number of guards at the bank for the time days before i are non-increasing, and\nThe number of guards at the bank for the time days after i are non-decreasing.\nMore formally, this means day i is a good day to rob the bank if and only if security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time].\nReturn a list of all days (0-indexed) that are good days to rob the bank. The order that the days are returned in does not matter.\n Example 1:\nInput: security = [5,3,3,3,5,6,2], time = 2\nOutput: [2,3]\nExplanation:\nOn day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\nOn day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\nNo other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.\nExample 2:\nInput: security = [1,1,1,1,1], time = 0\nOutput: [0,1,2,3,4]\nExplanation:\nSince time equals 0, every day is a good day to rob the bank, so return every day.\nExample 3:\nInput: security = [1,2,3,4,5,6], time = 2\nOutput: []\nExplanation:\nNo day has 2 days before it that have a non-increasing number of guards.\nThus, no day is a good day to rob the bank, so return an empty list.\n Constraints:\n1 <= security.length <= 105\n0 <= security[i], time <= 105" }, { "post_href": "https://leetcode.com/problems/detonate-the-maximum-bombs/discuss/1870271/Python-Solution-that-you-want-%3A", "python_solutions": "class Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n if len(bombs)==1:\n return 1\n \n adlist={i:[] for i in range(len(bombs))}\n \n for i in range(len(bombs)):\n x1,y1,r1=bombs[i]\n for j in range(i+1,len(bombs)):\n x2,y2,r2=bombs[j]\n dist=((x2-x1)**2+(y2-y1)**2)**(1/2)\n if dist<=r1:\n adlist[i].append(j) \n if dist<=r2:\n adlist[j].append(i)\n \n def dfs(adlist,seen,start):\n seen.add(start)\n for i in adlist[start]:\n if i not in seen:\n dfs(adlist,seen,i)\n maxx=1 \n for v in adlist:\n seen=set()\n seen.add(v)\n dfs(adlist,seen,v)\n maxx=max(maxx,len(seen))\n return maxx", "slug": "detonate-the-maximum-bombs", "post_title": "Python Solution that you want :", "user": "goxy_coder", "upvotes": 2, "views": 201, "problem_title": "detonate the maximum bombs", "number": 2101, "acceptance": 0.413, "difficulty": "Medium", "__index_level_0__": 29011, "question": "You are given a list of bombs. The range of a bomb is defined as the area where its effect can be felt. This area is in the shape of a circle with the center as the location of the bomb.\nThe bombs are represented by a 0-indexed 2D integer array bombs where bombs[i] = [xi, yi, ri]. xi and yi denote the X-coordinate and Y-coordinate of the location of the ith bomb, whereas ri denotes the radius of its range.\nYou may choose to detonate a single bomb. When a bomb is detonated, it will detonate all bombs that lie in its range. These bombs will further detonate the bombs that lie in their ranges.\nGiven the list of bombs, return the maximum number of bombs that can be detonated if you are allowed to detonate only one bomb.\n Example 1:\nInput: bombs = [[2,1,3],[6,1,4]]\nOutput: 2\nExplanation:\nThe above figure shows the positions and ranges of the 2 bombs.\nIf we detonate the left bomb, the right bomb will not be affected.\nBut if we detonate the right bomb, both bombs will be detonated.\nSo the maximum bombs that can be detonated is max(1, 2) = 2.\nExample 2:\nInput: bombs = [[1,1,5],[10,10,5]]\nOutput: 1\nExplanation:\nDetonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.\nExample 3:\nInput: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]\nOutput: 5\nExplanation:\nThe best bomb to detonate is bomb 0 because:\n- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.\n- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.\n- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.\nThus all 5 bombs are detonated.\n Constraints:\n1 <= bombs.length <= 100\nbombs[i].length == 3\n1 <= xi, yi, ri <= 105" }, { "post_href": "https://leetcode.com/problems/rings-and-rods/discuss/2044864/Python-simple-solution", "python_solutions": "class Solution:\n def countPoints(self, r: str) -> int:\n ans = 0\n for i in range(10):\n i = str(i)\n if 'R'+i in r and 'G'+i in r and 'B'+i in r:\n ans += 1\n return ans", "slug": "rings-and-rods", "post_title": "Python simple solution", "user": "StikS32", "upvotes": 7, "views": 353, "problem_title": "rings and rods", "number": 2103, "acceptance": 0.8140000000000001, "difficulty": "Easy", "__index_level_0__": 29018, "question": "There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9.\nYou are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where:\nThe first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').\nThe second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').\nFor example, \"R3G2B1\" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.\nReturn the number of rods that have all three colors of rings on them.\n Example 1:\nInput: rings = \"B0B6G0R6R0R6G9\"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.\n- The rod labeled 6 holds 3 rings, but it only has red and blue.\n- The rod labeled 9 holds only a green ring.\nThus, the number of rods with all three colors is 1.\nExample 2:\nInput: rings = \"B0R0G0R9R0B0G0\"\nOutput: 1\nExplanation: \n- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.\n- The rod labeled 9 holds only a red ring.\nThus, the number of rods with all three colors is 1.\nExample 3:\nInput: rings = \"G4\"\nOutput: 0\nExplanation: \nOnly one ring is given. Thus, no rods have all three colors.\n Constraints:\nrings.length == 2 * n\n1 <= n <= 100\nrings[i] where i is even is either 'R', 'G', or 'B' (0-indexed).\nrings[i] where i is odd is a digit from '0' to '9' (0-indexed)." }, { "post_href": "https://leetcode.com/problems/sum-of-subarray-ranges/discuss/1624416/Python3-stack", "python_solutions": "class Solution:\n def subArrayRanges(self, nums: List[int]) -> int:\n \n def fn(op): \n \"\"\"Return min sum (if given gt) or max sum (if given lt).\"\"\"\n ans = 0 \n stack = []\n for i in range(len(nums) + 1): \n while stack and (i == len(nums) or op(nums[stack[-1]], nums[i])): \n mid = stack.pop()\n ii = stack[-1] if stack else -1 \n ans += nums[mid] * (i - mid) * (mid - ii)\n stack.append(i)\n return ans \n \n return fn(lt) - fn(gt)", "slug": "sum-of-subarray-ranges", "post_title": "[Python3] stack", "user": "ye15", "upvotes": 17, "views": 3900, "problem_title": "sum of subarray ranges", "number": 2104, "acceptance": 0.602, "difficulty": "Medium", "__index_level_0__": 29052, "question": "You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.\nReturn the sum of all subarray ranges of nums.\nA subarray is a contiguous non-empty sequence of elements within an array.\n Example 1:\nInput: nums = [1,2,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0 \n[2], range = 2 - 2 = 0\n[3], range = 3 - 3 = 0\n[1,2], range = 2 - 1 = 1\n[2,3], range = 3 - 2 = 1\n[1,2,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.\nExample 2:\nInput: nums = [1,3,3]\nOutput: 4\nExplanation: The 6 subarrays of nums are the following:\n[1], range = largest - smallest = 1 - 1 = 0\n[3], range = 3 - 3 = 0\n[3], range = 3 - 3 = 0\n[1,3], range = 3 - 1 = 2\n[3,3], range = 3 - 3 = 0\n[1,3,3], range = 3 - 1 = 2\nSo the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.\nExample 3:\nInput: nums = [4,-2,-3,4,1]\nOutput: 59\nExplanation: The sum of all subarray ranges of nums is 59.\n Constraints:\n1 <= nums.length <= 1000\n-109 <= nums[i] <= 109\n Follow-up: Could you find a solution with O(n) time complexity?" }, { "post_href": "https://leetcode.com/problems/watering-plants-ii/discuss/1624252/Python3-2-pointers", "python_solutions": "class Solution:\n def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n ans = 0 \n lo, hi = 0, len(plants)-1\n canA, canB = capacityA, capacityB\n while lo < hi: \n if canA < plants[lo]: ans += 1; canA = capacityA\n canA -= plants[lo]\n if canB < plants[hi]: ans += 1; canB = capacityB\n canB -= plants[hi]\n lo, hi = lo+1, hi-1\n if lo == hi and max(canA, canB) < plants[lo]: ans += 1\n return ans", "slug": "watering-plants-ii", "post_title": "[Python3] 2 pointers", "user": "ye15", "upvotes": 8, "views": 340, "problem_title": "watering plants ii", "number": 2105, "acceptance": 0.501, "difficulty": "Medium", "__index_level_0__": 29071, "question": "Alice and Bob want to water n plants in their garden. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i.\nEach plant needs a specific amount of water. Alice and Bob have a watering can each, initially full. They water the plants in the following way:\nAlice waters the plants in order from left to right, starting from the 0th plant. Bob waters the plants in order from right to left, starting from the (n - 1)th plant. They begin watering the plants simultaneously.\nIt takes the same amount of time to water each plant regardless of how much water it needs.\nAlice/Bob must water the plant if they have enough in their can to fully water it. Otherwise, they first refill their can (instantaneously) then water the plant.\nIn case both Alice and Bob reach the same plant, the one with more water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant.\nGiven a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and two integers capacityA and capacityB representing the capacities of Alice's and Bob's watering cans respectively, return the number of times they have to refill to water all the plants.\n Example 1:\nInput: plants = [2,2,3,3], capacityA = 5, capacityB = 5\nOutput: 1\nExplanation:\n- Initially, Alice and Bob have 5 units of water each in their watering cans.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 3 units and 2 units of water respectively.\n- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.\nSo, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.\nExample 2:\nInput: plants = [2,2,3,3], capacityA = 3, capacityB = 4\nOutput: 2\nExplanation:\n- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.\n- Alice waters plant 0, Bob waters plant 3.\n- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.\n- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.\nSo, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.\nExample 3:\nInput: plants = [5], capacityA = 10, capacityB = 8\nOutput: 0\nExplanation:\n- There is only one plant.\n- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.\nSo, the total number of times they have to refill is 0.\n Constraints:\nn == plants.length\n1 <= n <= 105\n1 <= plants[i] <= 106\nmax(plants[i]) <= capacityA, capacityB <= 109" }, { "post_href": "https://leetcode.com/problems/maximum-fruits-harvested-after-at-most-k-steps/discuss/1624294/Sliding-Window-or-Prefix-Suffix-Sum-or-Easy-to-understand", "python_solutions": "class Solution:\n def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n \n fruitMap = defaultdict(int)\n \n for position, amount in fruits:\n fruitMap[position] = amount\n \n \n if k == 0:\n return fruitMap[startPos]\n \n totalLeft = 0 # max sum if we go k steps to the left\n totalRight = 0 # max sum if we go k steps to the right\n inBetween = 0 # max sum if we go x steps to the left & k steps to the right (ensuring that we don't move more than k steps in total)\n \n dp = dict()\n \n for i in range(startPos,startPos-k-1, -1):\n totalLeft += fruitMap[i]\n dp[i] = totalLeft\n \n for i in range(startPos,startPos+k+1):\n totalRight += fruitMap[i]\n dp[i] = totalRight\n \n \n leftSteps = 1\n rightSteps = k-2\n \n while rightSteps > 0:\n currAmount = 0\n \n # go right & collect\n currAmount += dp[startPos-leftSteps]\n # go left & collect\n currAmount += dp[startPos+rightSteps]\n \n \n inBetween = max(inBetween, currAmount-fruitMap[startPos])\n \n leftSteps += 1\n rightSteps -= 2\n \n \n leftSteps = k-2\n rightSteps = 1\n \n while leftSteps > 0:\n currAmount = 0\n \n # go right & collect\n currAmount += dp[startPos-leftSteps]\n # go left & collect\n currAmount += dp[startPos+rightSteps]\n \n inBetween = max(inBetween, currAmount-fruitMap[startPos])\n \n leftSteps -= 2\n rightSteps += 1\n \n \n return max(totalLeft, totalRight, inBetween)", "slug": "maximum-fruits-harvested-after-at-most-k-steps", "post_title": "\u2705 Sliding Window | Prefix Suffix Sum | Easy to understand", "user": "CaptainX", "upvotes": 1, "views": 268, "problem_title": "maximum fruits harvested after at most k steps", "number": 2106, "acceptance": 0.351, "difficulty": "Hard", "__index_level_0__": 29081, "question": "Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array fruits where fruits[i] = [positioni, amounti] depicts amounti fruits at the position positioni. fruits is already sorted by positioni in ascending order, and each positioni is unique.\nYou are also given an integer startPos and an integer k. Initially, you are at the position startPos. From any position, you can either walk to the left or right. It takes one step to move one unit on the x-axis, and you can walk at most k steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.\nReturn the maximum total number of fruits you can harvest.\n Example 1:\nInput: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\nOutput: 9\nExplanation: \nThe optimal way is to:\n- Move right to position 6 and harvest 3 fruits\n- Move right to position 8 and harvest 6 fruits\nYou moved 3 steps and harvested 3 + 6 = 9 fruits in total.\nExample 2:\nInput: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\nOutput: 14\nExplanation: \nYou can move at most k = 4 steps, so you cannot reach position 0 nor 10.\nThe optimal way is to:\n- Harvest the 7 fruits at the starting position 5\n- Move left to position 4 and harvest 1 fruit\n- Move right to position 6 and harvest 2 fruits\n- Move right to position 7 and harvest 4 fruits\nYou moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.\nExample 3:\nInput: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\nOutput: 0\nExplanation:\nYou can move at most k = 2 steps and cannot reach any position with fruits.\n Constraints:\n1 <= fruits.length <= 105\nfruits[i].length == 2\n0 <= startPos, positioni <= 2 * 105\npositioni-1 < positioni for any i > 0 (0-indexed)\n1 <= amounti <= 104\n0 <= k <= 2 * 105" }, { "post_href": "https://leetcode.com/problems/find-first-palindromic-string-in-the-array/discuss/2022159/Python-Clean-and-Simple-%2B-One-Liner!", "python_solutions": "class Solution:\n def firstPalindrome(self, words):\n for word in words:\n if word == word[::-1]: return word\n return \"\"", "slug": "find-first-palindromic-string-in-the-array", "post_title": "Python - Clean and Simple + One-Liner!", "user": "domthedeveloper", "upvotes": 3, "views": 128, "problem_title": "find first palindromic string in the array", "number": 2108, "acceptance": 0.7859999999999999, "difficulty": "Easy", "__index_level_0__": 29084, "question": "Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string \"\".\nA string is palindromic if it reads the same forward and backward.\n Example 1:\nInput: words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]\nOutput: \"ada\"\nExplanation: The first string that is palindromic is \"ada\".\nNote that \"racecar\" is also palindromic, but it is not the first.\nExample 2:\nInput: words = [\"notapalindrome\",\"racecar\"]\nOutput: \"racecar\"\nExplanation: The first and only string that is palindromic is \"racecar\".\nExample 3:\nInput: words = [\"def\",\"ghi\"]\nOutput: \"\"\nExplanation: There are no palindromic strings, so the empty string is returned.\n Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 100\nwords[i] consists only of lowercase English letters." }, { "post_href": "https://leetcode.com/problems/adding-spaces-to-a-string/discuss/1635075/Python-Split-and-Join-to-the-rescue.-From-TLE-to-Accepted-!-Straightforward", "python_solutions": "class Solution:\n def addSpaces(self, s: str, spaces: List[int]) -> str:\n \n arr = []\n prev = 0\n for space in spaces:\n arr.append(s[prev:space])\n prev = space\n arr.append(s[space:])\n \n return \" \".join(arr)", "slug": "adding-spaces-to-a-string", "post_title": "[Python] Split and Join to the rescue. From TLE to Accepted ! Straightforward", "user": "mostlyAditya", "upvotes": 8, "views": 388, "problem_title": "adding spaces to a string", "number": 2109, "acceptance": 0.563, "difficulty": "Medium", "__index_level_0__": 29132, "question": "You are given a 0-indexed string s and a 0-indexed integer array spaces that describes the indices in the original string where spaces will be added. Each space should be inserted before the character at the given index.\nFor example, given s = \"EnjoyYourCoffee\" and spaces = [5, 9], we place spaces before 'Y' and 'C', which are at indices 5 and 9 respectively. Thus, we obtain \"Enjoy Your Coffee\".\nReturn the modified string after the spaces have been added.\n Example 1:\nInput: s = \"LeetcodeHelpsMeLearn\", spaces = [8,13,15]\nOutput: \"Leetcode Helps Me Learn\"\nExplanation: \nThe indices 8, 13, and 15 correspond to the underlined characters in \"LeetcodeHelpsMeLearn\".\nWe then place spaces before those characters.\nExample 2:\nInput: s = \"icodeinpython\", spaces = [1,5,7,9]\nOutput: \"i code in py thon\"\nExplanation:\nThe indices 1, 5, 7, and 9 correspond to the underlined characters in \"icodeinpython\".\nWe then place spaces before those characters.\nExample 3:\nInput: s = \"spacing\", spaces = [0,1,2,3,4,5,6]\nOutput: \" s p a c i n g\"\nExplanation:\nWe are also able to place spaces before the first character of the string.\n Constraints:\n1 <= s.length <= 3 * 105\ns consists only of lowercase and uppercase English letters.\n1 <= spaces.length <= 3 * 105\n0 <= spaces[i] <= s.length - 1\nAll the values of spaces are strictly increasing." }, { "post_href": "https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/discuss/1635103/Python3-counting", "python_solutions": "class Solution:\n def getDescentPeriods(self, prices: List[int]) -> int:\n ans = 0 \n for i, x in enumerate(prices): \n if i == 0 or prices[i-1] != x + 1: cnt = 0\n cnt += 1\n ans += cnt \n return ans", "slug": "number-of-smooth-descent-periods-of-a-stock", "post_title": "[Python3] counting", "user": "ye15", "upvotes": 6, "views": 279, "problem_title": "number of smooth descent periods of a stock", "number": 2110, "acceptance": 0.5760000000000001, "difficulty": "Medium", "__index_level_0__": 29164, "question": "You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith day.\nA smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule.\nReturn the number of smooth descent periods.\n Example 1:\nInput: prices = [3,2,1,4]\nOutput: 7\nExplanation: There are 7 smooth descent periods:\n[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\nNote that a period with one day is a smooth descent period by the definition.\nExample 2:\nInput: prices = [8,6,7,7]\nOutput: 4\nExplanation: There are 4 smooth descent periods: [8], [6], [7], and [7]\nNote that [8,6] is not a smooth descent period as 8 - 6 \u2260 1.\nExample 3:\nInput: prices = [1]\nOutput: 1\nExplanation: There is 1 smooth descent period: [1]\n Constraints:\n1 <= prices.length <= 105\n1 <= prices[i] <= 105" }, { "post_href": "https://leetcode.com/problems/minimum-operations-to-make-the-array-k-increasing/discuss/1635109/Python3-almost-LIS", "python_solutions": "class Solution:\n def kIncreasing(self, arr: List[int], k: int) -> int:\n \n def fn(sub): \n \"\"\"Return ops to make sub non-decreasing.\"\"\"\n vals = []\n for x in sub: \n k = bisect_right(vals, x)\n if k == len(vals): vals.append(x)\n else: vals[k] = x\n return len(sub) - len(vals)\n \n return sum(fn(arr[i:len(arr):k]) for i in range(k))", "slug": "minimum-operations-to-make-the-array-k-increasing", "post_title": "[Python3] almost LIS", "user": "ye15", "upvotes": 2, "views": 177, "problem_title": "minimum operations to make the array k increasing", "number": 2111, "acceptance": 0.3779999999999999, "difficulty": "Hard", "__index_level_0__": 29178, "question": "You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k.\nThe array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1.\nFor example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because:\narr[0] <= arr[2] (4 <= 5)\narr[1] <= arr[3] (1 <= 2)\narr[2] <= arr[4] (5 <= 6)\narr[3] <= arr[5] (2 <= 2)\nHowever, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]).\nIn one operation, you can choose an index i and change arr[i] into any positive integer.\nReturn the minimum number of operations required to make the array K-increasing for the given k.\n Example 1:\nInput: arr = [5,4,3,2,1], k = 1\nOutput: 4\nExplanation:\nFor k = 1, the resultant array has to be non-decreasing.\nSome of the K-increasing arrays that can be formed are [5,6,7,8,9], [1,1,1,1,1], [2,2,3,4,4]. All of them require 4 operations.\nIt is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\nIt can be shown that we cannot make the array K-increasing in less than 4 operations.\nExample 2:\nInput: arr = [4,1,5,2,6,2], k = 2\nOutput: 0\nExplanation:\nThis is the same example as the one in the problem description.\nHere, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i].\nSince the given array is already K-increasing, we do not need to perform any operations.\nExample 3:\nInput: arr = [4,1,5,2,6,2], k = 3\nOutput: 2\nExplanation:\nIndices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\nOne of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\nThe array will now be [4,1,5,4,6,5].\nNote that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.\n Constraints:\n1 <= arr.length <= 105\n1 <= arr[i], k <= arr.length" }, { "post_href": "https://leetcode.com/problems/maximum-number-of-words-found-in-sentences/discuss/1646786/Count-Spaces", "python_solutions": "class Solution:\n def mostWordsFound(self, ss: List[str]) -> int:\n return max(s.count(\" \") for s in ss) + 1", "slug": "maximum-number-of-words-found-in-sentences", "post_title": "Count Spaces", "user": "votrubac", "upvotes": 64, "views": 8100, "problem_title": "maximum number of words found in sentences", "number": 2114, "acceptance": 0.88, "difficulty": "Easy", "__index_level_0__": 29184, "question": "A sentence is a list of words that are separated by a single space with no leading or trailing spaces.\nYou are given an array of strings sentences, where each sentences[i] represents a single sentence.\nReturn the maximum number of words that appear in a single sentence.\n Example 1:\nInput: sentences = [\"alice and bob love leetcode\", \"i think so too\", \"this is great thanks very much\"]\nOutput: 6\nExplanation: \n- The first sentence, \"alice and bob love leetcode\", has 5 words in total.\n- The second sentence, \"i think so too\", has 4 words in total.\n- The third sentence, \"this is great thanks very much\", has 6 words in total.\nThus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.\nExample 2:\nInput: sentences = [\"please wait\", \"continue to fight\", \"continue to win\"]\nOutput: 3\nExplanation: It is possible that multiple sentences contain the same number of words. \nIn this example, the second and third sentences (underlined) have the same number of words.\n Constraints:\n1 <= sentences.length <= 100\n1 <= sentences[i].length <= 100\nsentences[i] consists only of lowercase English letters and ' ' only.\nsentences[i] does not have leading or trailing spaces.\nAll the words in sentences[i] are separated by a single space." }, { "post_href": "https://leetcode.com/problems/find-all-possible-recipes-from-given-supplies/discuss/1646903/DFS", "python_solutions": "class Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n graph, can_make, supplies = {recipe : [] for recipe in recipes}, {}, set(supplies)\n def dfs(recipe : str) -> bool:\n if recipe not in can_make:\n can_make[recipe] = False\n can_make[recipe] = all([dfs(ingr) for ingr in graph[recipe]])\n return can_make[recipe]\n for i, recipe in enumerate(recipes):\n for ingr in ingredients[i]:\n if ingr not in supplies:\n graph[recipe].append(ingr if ingr in graph else recipe)\n return [recipe for recipe in recipes if dfs(recipe)]", "slug": "find-all-possible-recipes-from-given-supplies", "post_title": "DFS", "user": "votrubac", "upvotes": 62, "views": 7200, "problem_title": "find all possible recipes from given supplies", "number": 2115, "acceptance": 0.485, "difficulty": "Medium", "__index_level_0__": 29230, "question": "You have information about n different recipes. You are given a string array recipes and a 2D string array ingredients. The ith recipe has the name recipes[i], and you can create it if you have all the needed ingredients from ingredients[i]. Ingredients to a recipe may need to be created from other recipes, i.e., ingredients[i] may contain a string that is in recipes.\nYou are also given a string array supplies containing all the ingredients that you initially have, and you have an infinite supply of all of them.\nReturn a list of all the recipes that you can create. You may return the answer in any order.\nNote that two recipes may contain each other in their ingredients.\n Example 1:\nInput: recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]\nOutput: [\"bread\"]\nExplanation:\nWe can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nExample 2:\nInput: recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\nOutput: [\"bread\",\"sandwich\"]\nExplanation:\nWe can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\nExample 3:\nInput: recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\nOutput: [\"bread\",\"sandwich\",\"burger\"]\nExplanation:\nWe can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\nWe can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\nWe can create \"burger\" since we have the ingredient \"meat\" and can create the ingredients \"bread\" and \"sandwich\".\n Constraints:\nn == recipes.length == ingredients.length\n1 <= n <= 100\n1 <= ingredients[i].length, supplies.length <= 100\n1 <= recipes[i].length, ingredients[i][j].length, supplies[k].length <= 10\nrecipes[i], ingredients[i][j], and supplies[k] consist only of lowercase English letters.\nAll the values of recipes and supplies combined are unique.\nEach ingredients[i] does not contain any duplicate values." }, { "post_href": "https://leetcode.com/problems/check-if-a-parentheses-string-can-be-valid/discuss/1646594/Left-to-right-and-right-to-left", "python_solutions": "class Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n def validate(s: str, locked: str, op: str) -> bool:\n bal, wild = 0, 0\n for i in range(len(s)):\n if locked[i] == \"1\":\n bal += 1 if s[i] == op else -1\n else:\n wild += 1\n if wild + bal < 0:\n return False\n return bal <= wild\n return len(s) % 2 == 0 and validate(s, locked, '(') and validate(s[::-1], locked[::-1], ')')", "slug": "check-if-a-parentheses-string-can-be-valid", "post_title": "Left-to-right and right-to-left", "user": "votrubac", "upvotes": 175, "views": 8600, "problem_title": "check if a parentheses string can be valid", "number": 2116, "acceptance": 0.315, "difficulty": "Medium", "__index_level_0__": 29255, "question": "A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:\nIt is ().\nIt can be written as AB (A concatenated with B), where A and B are valid parentheses strings.\nIt can be written as (A), where A is a valid parentheses string.\nYou are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked,\nIf locked[i] is '1', you cannot change s[i].\nBut if locked[i] is '0', you can change s[i] to either '(' or ')'.\nReturn true if you can make s a valid parentheses string. Otherwise, return false.\n Example 1:\nInput: s = \"))()))\", locked = \"010100\"\nOutput: true\nExplanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\nWe change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.\nExample 2:\nInput: s = \"()()\", locked = \"0000\"\nOutput: true\nExplanation: We do not need to make any changes because s is already valid.\nExample 3:\nInput: s = \")\", locked = \"0\"\nOutput: false\nExplanation: locked permits us to change s[0]. \nChanging s[0] to either '(' or ')' will not make s valid.\n Constraints:\nn == s.length == locked.length\n1 <= n <= 105\ns[i] is either '(' or ')'.\nlocked[i] is either '0' or '1'." }, { "post_href": "https://leetcode.com/problems/abbreviating-the-product-of-a-range/discuss/1646615/Python3-quasi-brute-force", "python_solutions": "class Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n ans = prefix = suffix = 1\n trailing = 0 \n flag = False \n for x in range(left, right+1): \n if not flag: \n ans *= x\n while ans % 10 == 0: ans //= 10 \n if ans >= 1e10: flag = True \n prefix *= x\n suffix *= x\n while prefix >= 1e12: prefix //= 10 \n while suffix % 10 == 0: \n trailing += 1\n suffix //= 10 \n if suffix >= 1e10: suffix %= 10_000_000_000\n while prefix >= 100000: prefix //= 10 \n suffix %= 100000\n if flag: return f\"{prefix}...{suffix:>05}e{trailing}\"\n return f\"{ans}e{trailing}\"", "slug": "abbreviating-the-product-of-a-range", "post_title": "[Python3] quasi brute-force", "user": "ye15", "upvotes": 10, "views": 525, "problem_title": "abbreviating the product of a range", "number": 2117, "acceptance": 0.28, "difficulty": "Hard", "__index_level_0__": 29260, "question": "You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right].\nSince the product may be very large, you will abbreviate it following these steps:\nCount all trailing zeros in the product and remove them. Let us denote this count as C.\nFor example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546.\nDenote the remaining number of digits in the product as d. If d > 10, then express the product as
... where 
 denotes the first 5 digits of the product, and  denotes the last 5 digits of the product after removing all trailing zeros. If d <= 10, we keep it unchanged.\nFor example, we express 1234567654321 as 12345...54321, but 1234567 is represented as 1234567.\nFinally, represent the product as a string \"
...eC\".\nFor example, 12345678987600000 will be represented as \"12345...89876e5\".\nReturn a string denoting the abbreviated product of all integers in the inclusive range [left, right].\n  Example 1:\nInput: left = 1, right = 4\nOutput: \"24e0\"\nExplanation: The product is 1 \u00d7 2 \u00d7 3 \u00d7 4 = 24.\nThere are no trailing zeros, so 24 remains the same. The abbreviation will end with \"e0\".\nSince the number of digits is 2, which is less than 10, we do not have to abbreviate it further.\nThus, the final representation is \"24e0\".\nExample 2:\nInput: left = 2, right = 11\nOutput: \"399168e2\"\nExplanation: The product is 39916800.\nThere are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with \"e2\".\nThe number of digits after removing the trailing zeros is 6, so we do not abbreviate it further.\nHence, the abbreviated product is \"399168e2\".\nExample 3:\nInput: left = 371, right = 375\nOutput: \"7219856259e3\"\nExplanation: The product is 7219856259000.\n  Constraints:\n1 <= left <= right <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/a-number-after-a-double-reversal/discuss/1648940/Python3-1-Liner-or-O(1)-Time-and-Space-or-Short-and-Clean-Explanation",
      "python_solutions": "class Solution:\n    def isSameAfterReversals(self, num: int) -> bool:\n        return not num or num % 10",
      "slug": "a-number-after-a-double-reversal",
      "post_title": "[Python3] 1 Liner | O(1) Time and Space | Short and Clean Explanation",
      "user": "PatrickOweijane",
      "upvotes": 12,
      "views": 578,
      "problem_title": "a number after a double reversal",
      "number": 2119,
      "acceptance": 0.758,
      "difficulty": "Easy",
      "__index_level_0__": 29265,
      "question": "Reversing an integer means to reverse all its digits.\nFor example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.\nGiven an integer num, reverse num to get reversed1, then reverse reversed1 to get reversed2. Return true if reversed2 equals num. Otherwise return false.\n  Example 1:\nInput: num = 526\nOutput: true\nExplanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.\nExample 2:\nInput: num = 1800\nOutput: false\nExplanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.\nExample 3:\nInput: num = 0\nOutput: true\nExplanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.\n  Constraints:\n0 <= num <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/discuss/2838969/Python-Straight-forward-O(n-2)-solution-(still-fast-85)",
      "python_solutions": "class Solution:\n    def executeInstructions(self, n: int, startPos: list[int], s: str) -> list[int]:\n\n        def num_of_valid_instructions(s, pos, start, end):\n            row, colon = pos\n            k = 0\n            for i in range(start, end):\n                cur = s[i]\n                row += (cur == 'D') - (cur == 'U')\n                colon += (cur == 'R') - (cur == 'L')\n                if not (0 <= row < n and 0 <= colon < n):\n                    return k\n                k += 1\n            return k\n\n        ans = []\n        for i in range(len(s)):\n            ans.append(num_of_valid_instructions(s, startPos, i, len(s)))\n        return ans",
      "slug": "execution-of-all-suffix-instructions-staying-in-a-grid",
      "post_title": "[Python] Straight-forward O(n ^ 2) solution (still fast - 85%)",
      "user": "Mark_computer",
      "upvotes": 1,
      "views": 4,
      "problem_title": "execution of all suffix instructions staying in a grid",
      "number": 2120,
      "acceptance": 0.836,
      "difficulty": "Medium",
      "__index_level_0__": 29307,
      "question": "There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).\nYou are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).\nThe robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met:\nThe next instruction will move the robot off the grid.\nThere are no more instructions left to execute.\nReturn an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.\n  Example 1:\nInput: n = 3, startPos = [0,1], s = \"RRDDLU\"\nOutput: [1,5,4,3,1,0]\nExplanation: Starting from startPos and beginning execution from the ith instruction:\n- 0th: \"RRDDLU\". Only one instruction \"R\" can be executed before it moves off the grid.\n- 1st:  \"RDDLU\". All five instructions can be executed while it stays in the grid and ends at (1, 1).\n- 2nd:   \"DDLU\". All four instructions can be executed while it stays in the grid and ends at (1, 0).\n- 3rd:    \"DLU\". All three instructions can be executed while it stays in the grid and ends at (0, 0).\n- 4th:     \"LU\". Only one instruction \"L\" can be executed before it moves off the grid.\n- 5th:      \"U\". If moving up, it would move off the grid.\nExample 2:\nInput: n = 2, startPos = [1,1], s = \"LURD\"\nOutput: [4,1,0,0]\nExplanation:\n- 0th: \"LURD\".\n- 1st:  \"URD\".\n- 2nd:   \"RD\".\n- 3rd:    \"D\".\nExample 3:\nInput: n = 1, startPos = [0,0], s = \"LRUD\"\nOutput: [0,0,0,0]\nExplanation: No matter which instruction the robot begins execution from, it would move off the grid.\n  Constraints:\nm == s.length\n1 <= n, m <= 500\nstartPos.length == 2\n0 <= startrow, startcol < n\ns consists of 'L', 'R', 'U', and 'D'."
    },
    {
      "post_href": "https://leetcode.com/problems/intervals-between-identical-elements/discuss/1647480/Python3-prefix-sum",
      "python_solutions": "class Solution:\n    def getDistances(self, arr: List[int]) -> List[int]:\n        loc = defaultdict(list)\n        for i, x in enumerate(arr): loc[x].append(i)\n        \n        for k, idx in loc.items(): \n            prefix = list(accumulate(idx, initial=0))\n            vals = []\n            for i, x in enumerate(idx): \n                vals.append(prefix[-1] - prefix[i] - prefix[i+1] - (len(idx)-2*i-1)*x)\n            loc[k] = deque(vals)\n        \n        return [loc[x].popleft() for x in arr]",
      "slug": "intervals-between-identical-elements",
      "post_title": "[Python3] prefix sum",
      "user": "ye15",
      "upvotes": 9,
      "views": 1100,
      "problem_title": "intervals between identical elements",
      "number": 2121,
      "acceptance": 0.433,
      "difficulty": "Medium",
      "__index_level_0__": 29326,
      "question": "You are given a 0-indexed array of n integers arr.\nThe interval between two elements in arr is defined as the absolute difference between their indices. More formally, the interval between arr[i] and arr[j] is |i - j|.\nReturn an array intervals of length n where intervals[i] is the sum of intervals between arr[i] and each element in arr with the same value as arr[i].\nNote: |x| is the absolute value of x.\n  Example 1:\nInput: arr = [2,1,3,1,2,3,3]\nOutput: [4,2,7,2,4,4,5]\nExplanation:\n- Index 0: Another 2 is found at index 4. |0 - 4| = 4\n- Index 1: Another 1 is found at index 3. |1 - 3| = 2\n- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7\n- Index 3: Another 1 is found at index 1. |3 - 1| = 2\n- Index 4: Another 2 is found at index 0. |4 - 0| = 4\n- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4\n- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5\nExample 2:\nInput: arr = [10,5,10,10]\nOutput: [5,0,3,4]\nExplanation:\n- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5\n- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.\n- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3\n- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4\n  Constraints:\nn == arr.length\n1 <= n <= 105\n1 <= arr[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/recover-the-original-array/discuss/1647488/Python3-brute-force",
      "python_solutions": "class Solution:\n    def recoverArray(self, nums: List[int]) -> List[int]:\n        nums.sort()\n        cnt = Counter(nums)\n        for i in range(1, len(nums)): \n            diff = nums[i] - nums[0]\n            if diff and diff&1 == 0: \n                ans = []\n                freq = cnt.copy()\n                for k, v in freq.items(): \n                    if v: \n                        if freq[k+diff] < v: break \n                        ans.extend([k+diff//2]*v)\n                        freq[k+diff] -= v\n                else: return ans",
      "slug": "recover-the-original-array",
      "post_title": "[Python3] brute-force",
      "user": "ye15",
      "upvotes": 11,
      "views": 503,
      "problem_title": "recover the original array",
      "number": 2122,
      "acceptance": 0.381,
      "difficulty": "Hard",
      "__index_level_0__": 29336,
      "question": "Alice had a 0-indexed array arr consisting of n positive integers. She chose an arbitrary positive integer k and created two new 0-indexed integer arrays lower and higher in the following manner:\nlower[i] = arr[i] - k, for every index i where 0 <= i < n\nhigher[i] = arr[i] + k, for every index i where 0 <= i < n\nUnfortunately, Alice lost all three arrays. However, she remembers the integers that were present in the arrays lower and higher, but not the array each integer belonged to. Help Alice and recover the original array.\nGiven an array nums consisting of 2n integers, where exactly n of the integers were present in lower and the remaining in higher, return the original array arr. In case the answer is not unique, return any valid array.\nNote: The test cases are generated such that there exists at least one valid array arr.\n  Example 1:\nInput: nums = [2,10,6,4,8,12]\nOutput: [3,7,11]\nExplanation:\nIf arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\nCombining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\nAnother valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. \nExample 2:\nInput: nums = [1,1,3,3]\nOutput: [2,2]\nExplanation:\nIf arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\nCombining lower and higher gives us [1,1,3,3], which is equal to nums.\nNote that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\nThis is invalid since k must be positive.\nExample 3:\nInput: nums = [5,435]\nOutput: [220]\nExplanation:\nThe only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].\n  Constraints:\n2 * n == nums.length\n1 <= n <= 1000\n1 <= nums[i] <= 109\nThe test cases are generated such that there exists at least one valid array arr."
    },
    {
      "post_href": "https://leetcode.com/problems/check-if-all-as-appears-before-all-bs/discuss/1662586/Python-O(NlogN)-sort-solution-and-O(N)-linear-scan-solution",
      "python_solutions": "class Solution:\n    def checkString(self, s: str) -> bool:\n        return ''.join(sorted(s)) == s",
      "slug": "check-if-all-as-appears-before-all-bs",
      "post_title": "[Python] O(NlogN) sort solution and O(N) linear scan solution",
      "user": "kryuki",
      "upvotes": 4,
      "views": 193,
      "problem_title": "check if all as appears before all bs",
      "number": 2124,
      "acceptance": 0.716,
      "difficulty": "Easy",
      "__index_level_0__": 29341,
      "question": "Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.\n  Example 1:\nInput: s = \"aaabbb\"\nOutput: true\nExplanation:\nThe 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\nHence, every 'a' appears before every 'b' and we return true.\nExample 2:\nInput: s = \"abab\"\nOutput: false\nExplanation:\nThere is an 'a' at index 2 and a 'b' at index 1.\nHence, not every 'a' appears before every 'b' and we return false.\nExample 3:\nInput: s = \"bbb\"\nOutput: true\nExplanation:\nThere are no 'a's, hence, every 'a' appears before every 'b' and we return true.\n  Constraints:\n1 <= s.length <= 100\ns[i] is either 'a' or 'b'."
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-laser-beams-in-a-bank/discuss/2272999/PYTHON-3-99.13-LESS-MEMORY-or-94.93-FASTER-or-EXPLANATION",
      "python_solutions": "class Solution:\n    def numberOfBeams(self, bank: List[str]) -> int:\n        a, s = [x.count(\"1\") for x in bank if x.count(\"1\")], 0\n\n\t\t# ex: bank is [[00101], [01001], [00000], [11011]]\n\t\t# a would return [2, 2, 4]\n\n        for c in range(len(a)-1):\n            s += (a[c]*a[c+1])\n\n\t\t\t# basic math to find the total amount of lasers\n\t\t\t# for the first iteration: s += 2*2\n\t\t\t# for the second iteration: s += 2*4\n\t\t\t# returns s = 12\n\n        return s",
      "slug": "number-of-laser-beams-in-a-bank",
      "post_title": "[PYTHON 3] 99.13% LESS MEMORY | 94.93% FASTER | EXPLANATION",
      "user": "omkarxpatel",
      "upvotes": 7,
      "views": 130,
      "problem_title": "number of laser beams in a bank",
      "number": 2125,
      "acceptance": 0.826,
      "difficulty": "Medium",
      "__index_level_0__": 29379,
      "question": "Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device.\nThere is one laser beam between any two security devices if both conditions are met:\nThe two devices are located on two different rows: r1 and r2, where r1 < r2.\nFor each row i where r1 < i < r2, there are no security devices in the ith row.\nLaser beams are independent, i.e., one beam does not interfere nor join with another.\nReturn the total number of laser beams in the bank.\n  Example 1:\nInput: bank = [\"011001\",\"000000\",\"010100\",\"001000\"]\nOutput: 8\nExplanation: Between each of the following device pairs, there is one beam. In total, there are 8 beams:\n * bank[0][1] -- bank[2][1]\n * bank[0][1] -- bank[2][3]\n * bank[0][2] -- bank[2][1]\n * bank[0][2] -- bank[2][3]\n * bank[0][5] -- bank[2][1]\n * bank[0][5] -- bank[2][3]\n * bank[2][1] -- bank[3][2]\n * bank[2][3] -- bank[3][2]\nNote that there is no beam between any device on the 0th row with any on the 3rd row.\nThis is because the 2nd row contains security devices, which breaks the second condition.\nExample 2:\nInput: bank = [\"000\",\"111\",\"000\"]\nOutput: 0\nExplanation: There does not exist two devices located on two different rows.\n  Constraints:\nm == bank.length\nn == bank[i].length\n1 <= m, n <= 500\nbank[i][j] is either '0' or '1'."
    },
    {
      "post_href": "https://leetcode.com/problems/destroying-asteroids/discuss/1775912/Simple-python-solution-or-85-lesser-memory",
      "python_solutions": "class Solution:\n    def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n        asteroids = sorted(asteroids)\n        for i in asteroids:\n            if i <= mass:\n                mass += i\n            else:\n                return False\n        return True",
      "slug": "destroying-asteroids",
      "post_title": "\u2714Simple python solution | 85% lesser memory",
      "user": "Coding_Tan3",
      "upvotes": 2,
      "views": 129,
      "problem_title": "destroying asteroids",
      "number": 2126,
      "acceptance": 0.495,
      "difficulty": "Medium",
      "__index_level_0__": 29412,
      "question": "You are given an integer mass, which represents the original mass of a planet. You are further given an integer array asteroids, where asteroids[i] is the mass of the ith asteroid.\nYou can arrange for the planet to collide with the asteroids in any arbitrary order. If the mass of the planet is greater than or equal to the mass of the asteroid, the asteroid is destroyed and the planet gains the mass of the asteroid. Otherwise, the planet is destroyed.\nReturn true if all asteroids can be destroyed. Otherwise, return false.\n  Example 1:\nInput: mass = 10, asteroids = [3,9,19,5,21]\nOutput: true\nExplanation: One way to order the asteroids is [9,19,5,3,21]:\n- The planet collides with the asteroid with a mass of 9. New planet mass: 10 + 9 = 19\n- The planet collides with the asteroid with a mass of 19. New planet mass: 19 + 19 = 38\n- The planet collides with the asteroid with a mass of 5. New planet mass: 38 + 5 = 43\n- The planet collides with the asteroid with a mass of 3. New planet mass: 43 + 3 = 46\n- The planet collides with the asteroid with a mass of 21. New planet mass: 46 + 21 = 67\nAll asteroids are destroyed.\nExample 2:\nInput: mass = 5, asteroids = [4,9,23,4]\nOutput: false\nExplanation: \nThe planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\nAfter the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\nThis is less than 23, so a collision would not destroy the last asteroid.\n  Constraints:\n1 <= mass <= 105\n1 <= asteroids.length <= 105\n1 <= asteroids[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-employees-to-be-invited-to-a-meeting/discuss/1661041/Python3-quite-a-tedious-solution",
      "python_solutions": "class Solution:\n    def maximumInvitations(self, favorite: List[int]) -> int:\n        n = len(favorite)\n        graph = [[] for _ in range(n)]\n        for i, x in enumerate(favorite): graph[x].append(i)\n        \n        def bfs(x, seen): \n            \"\"\"Return longest arm of x.\"\"\"\n            ans = 0 \n            queue = deque([x])\n            while queue: \n                for _ in range(len(queue)): \n                    u = queue.popleft()\n                    for v in graph[u]: \n                        if v not in seen: \n                            seen.add(v)\n                            queue.append(v)\n                ans += 1\n            return ans \n        \n        ans = 0 \n        seen = [False]*n\n        for i, x in enumerate(favorite): \n            if favorite[x] == i and not seen[i]: \n                seen[i] = seen[x] = True \n                ans += bfs(i, {i, x}) + bfs(x, {i, x})\n                \n        dp = [0]*n\n        for i, x in enumerate(favorite): \n            if dp[i] == 0: \n                ii, val = i, 0\n                memo = {}\n                while ii not in memo: \n                    if dp[ii]: \n                        cycle = dp[ii]\n                        break\n                    memo[ii] = val\n                    val += 1\n                    ii = favorite[ii]\n                else: cycle = val - memo[ii]\n                for k in memo: dp[k] = cycle\n        return max(ans, max(dp))",
      "slug": "maximum-employees-to-be-invited-to-a-meeting",
      "post_title": "[Python3] quite a tedious solution",
      "user": "ye15",
      "upvotes": 5,
      "views": 1000,
      "problem_title": "maximum employees to be invited to a meeting",
      "number": 2127,
      "acceptance": 0.337,
      "difficulty": "Hard",
      "__index_level_0__": 29427,
      "question": "A company is organizing a meeting and has a list of n employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees.\nThe employees are numbered from 0 to n - 1. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself.\nGiven a 0-indexed integer array favorite, where favorite[i] denotes the favorite person of the ith employee, return the maximum number of employees that can be invited to the meeting.\n  Example 1:\nInput: favorite = [2,2,1,2]\nOutput: 3\nExplanation:\nThe above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\nAll employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\nNote that the company can also invite employees 1, 2, and 3, and give them their desired seats.\nThe maximum number of employees that can be invited to the meeting is 3. \nExample 2:\nInput: favorite = [1,2,0]\nOutput: 3\nExplanation: \nEach employee is the favorite person of at least one other employee, and the only way the company can invite them is if they invite every employee.\nThe seating arrangement will be the same as that in the figure given in example 1:\n- Employee 0 will sit between employees 2 and 1.\n- Employee 1 will sit between employees 0 and 2.\n- Employee 2 will sit between employees 1 and 0.\nThe maximum number of employees that can be invited to the meeting is 3.\nExample 3:\nInput: favorite = [3,0,1,4,1]\nOutput: 4\nExplanation:\nThe above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\nEmployee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\nSo the company leaves them out of the meeting.\nThe maximum number of employees that can be invited to the meeting is 4.\n  Constraints:\nn == favorite.length\n2 <= n <= 105\n0 <= favorite[i] <= n - 1\nfavorite[i] != i"
    },
    {
      "post_href": "https://leetcode.com/problems/capitalize-the-title/discuss/1716077/Python-Easy-Solution",
      "python_solutions": "class Solution:\n    def capitalizeTitle(self, title: str) -> str:\n        title = title.split()\n        word = \"\"\n        for i in range(len(title)):\n            if len(title[i]) < 3:\n                word = word + title[i].lower() + \" \"\n            else:\n                word = word + title[i].capitalize() + \" \"\n        return word[:-1]",
      "slug": "capitalize-the-title",
      "post_title": "Python Easy Solution",
      "user": "yashitanamdeo",
      "upvotes": 4,
      "views": 413,
      "problem_title": "capitalize the title",
      "number": 2129,
      "acceptance": 0.603,
      "difficulty": "Easy",
      "__index_level_0__": 29428,
      "question": "You are given a string title consisting of one or more words separated by a single space, where each word consists of English letters. Capitalize the string by changing the capitalization of each word such that:\nIf the length of the word is 1 or 2 letters, change all letters to lowercase.\nOtherwise, change the first letter to uppercase and the remaining letters to lowercase.\nReturn the capitalized title.\n  Example 1:\nInput: title = \"capiTalIze tHe titLe\"\nOutput: \"Capitalize The Title\"\nExplanation:\nSince all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.\nExample 2:\nInput: title = \"First leTTeR of EACH Word\"\nOutput: \"First Letter of Each Word\"\nExplanation:\nThe word \"of\" has length 2, so it is all lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.\nExample 3:\nInput: title = \"i lOve leetcode\"\nOutput: \"i Love Leetcode\"\nExplanation:\nThe word \"i\" has length 1, so it is lowercase.\nThe remaining words have a length of at least 3, so the first letter of each remaining word is uppercase, and the remaining letters are lowercase.\n  Constraints:\n1 <= title.length <= 100\ntitle consists of words separated by a single space without any leading or trailing spaces.\nEach word consists of uppercase and lowercase English letters and is non-empty."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/discuss/1676025/Need-to-know-O(1)-space-solution-in-Python",
      "python_solutions": "class Solution:\n    def pairSum(self, head: Optional[ListNode]) -> int:\n        nums = []\n        curr = head\n        while curr:\n            nums.append(curr.val)\n            curr = curr.next\n        \n        N = len(nums)\n        res = 0\n        for i in range(N // 2):\n            res = max(res, nums[i] + nums[N - i - 1])\n        return res",
      "slug": "maximum-twin-sum-of-a-linked-list",
      "post_title": "Need-to-know O(1) space solution in Python",
      "user": "kryuki",
      "upvotes": 16,
      "views": 1900,
      "problem_title": "maximum twin sum of a linked list",
      "number": 2130,
      "acceptance": 0.8140000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 29470,
      "question": "In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.\nFor example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.\nThe twin sum is defined as the sum of a node and its twin.\nGiven the head of a linked list with even length, return the maximum twin sum of the linked list.\n  Example 1:\nInput: head = [5,4,2,1]\nOutput: 6\nExplanation:\nNodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\nThere are no other nodes with twins in the linked list.\nThus, the maximum twin sum of the linked list is 6. \nExample 2:\nInput: head = [4,2,2,3]\nOutput: 7\nExplanation:\nThe nodes with twins present in this linked list are:\n- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.\n- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.\nThus, the maximum twin sum of the linked list is max(7, 4) = 7. \nExample 3:\nInput: head = [1,100000]\nOutput: 100001\nExplanation:\nThere is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.\n  Constraints:\nThe number of nodes in the list is an even integer in the range [2, 105].\n1 <= Node.val <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/discuss/2772128/using-dictnory-in-TCN",
      "python_solutions": "class Solution:\n    def longestPalindrome(self, words: List[str]) -> int:\n        dc=defaultdict(lambda:0)\n        for a in words:\n            dc[a]+=1\n        count=0\n        palindromswords=0\n        inmiddle=0\n        wds=set(words)\n        for a in wds:\n            if(a==a[::-1]):\n                if(dc[a]%2==1):\n                    inmiddle=1\n                palindromswords+=(dc[a]//2)*2\n            elif(dc[a[::-1]]>0):\n                count+=(2*(min(dc[a],dc[a[::-1]])))\n                dc[a]=0\n        return (palindromswords+count+inmiddle)*2\n        ``",
      "slug": "longest-palindrome-by-concatenating-two-letter-words",
      "post_title": "using dictnory in TC=N",
      "user": "droj",
      "upvotes": 5,
      "views": 349,
      "problem_title": "longest palindrome by concatenating two letter words",
      "number": 2131,
      "acceptance": 0.491,
      "difficulty": "Medium",
      "__index_level_0__": 29493,
      "question": "You are given an array of strings words. Each element of words consists of two lowercase English letters.\nCreate the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.\nReturn the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.\nA palindrome is a string that reads the same forward and backward.\n  Example 1:\nInput: words = [\"lc\",\"cl\",\"gg\"]\nOutput: 6\nExplanation: One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\nNote that \"clgglc\" is another longest palindrome that can be created.\nExample 2:\nInput: words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\nOutput: 8\nExplanation: One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\nNote that \"lcyttycl\" is another longest palindrome that can be created.\nExample 3:\nInput: words = [\"cc\",\"ll\",\"xx\"]\nOutput: 2\nExplanation: One longest palindrome is \"cc\", of length 2.\nNote that \"ll\" is another longest palindrome that can be created, and so is \"xx\".\n  Constraints:\n1 <= words.length <= 105\nwords[i].length == 2\nwords[i] consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/stamping-the-grid/discuss/2489712/Python3-solution%3A-faster-than-most-submissions-oror-Very-simple",
      "python_solutions": "class Solution:\n    def prefix_sum(self, grid: List[List[int]]) -> List[List[int]]:\n            ps = [[grid[row][col] for col in range(len(grid[0]))]for row in range(len(grid))]\n            \n            for row in range(len(grid)):\n                for col in range(1, len(grid[0])):\n                    ps[row][col] = ps[row][col-1] + grid[row][col]\n            \n            for row in range(1, len(grid)):\n                for col in range(len(grid[0])):\n                    ps[row][col] = ps[row-1][col] + ps[row][col]\n            \n            return ps\n\t\t\t\n    def sumRegion(self, ps, row1: int, col1: int, row2: int, col2: int) -> int:\n            ans = 0\n            if row1 == 0 and col1 == 0:\n                ans = ps[row2][col2]\n            elif row1 == 0:\n                ans = ps[row2][col2] - ps[row2][col1-1]\n            elif col1 == 0:\n                ans = ps[row2][col2] - ps[row1-1][col2]\n            else:\n                ans = ps[row2][col2] - ps[row1-1][col2] - ps[row2][col1-1] + ps[row1-1][col1-1]\n            return ans\n\n    def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool:\n        diff = [[0 for col in range(len(grid[0])+1)]for row in range(len(grid)+1)]\n        \n        ps = self.prefix_sum(grid)\n        cover = 0\n        \n        for row in range(len(grid)-(stampHeight-1)):\n            for col in range(len(grid[0])-(stampWidth-1)):\n                sub_sum = self.sumRegion(ps, row, col, row+stampHeight-1, col+stampWidth-1)\n                if sub_sum == 0:\n                    diff[row][col] += 1\n                    diff[row][col+stampWidth] -= 1\n                    diff[row+stampHeight][col] -= 1\n                    diff[row+stampHeight][col+stampWidth] = 1\n        pref_diff = self.prefix_sum(diff)\n        m, n = len(grid), len(grid[0])\n        \n        for row in range(len(grid)):\n            for col in range(len(grid[0])):\n                if grid[row][col] == 0 and pref_diff[row][col] == 0: return False \n        \n        return True",
      "slug": "stamping-the-grid",
      "post_title": "\u2714\ufe0f Python3 solution: faster than most submissions || Very simple",
      "user": "Omegang",
      "upvotes": 0,
      "views": 40,
      "problem_title": "stamping the grid",
      "number": 2132,
      "acceptance": 0.309,
      "difficulty": "Hard",
      "__index_level_0__": 29544,
      "question": "You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).\nYou are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements:\nCover all the empty cells.\nDo not cover any of the occupied cells.\nWe can put as many stamps as we want.\nStamps can overlap with each other.\nStamps are not allowed to be rotated.\nStamps must stay completely inside the grid.\nReturn true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.\n  Example 1:\nInput: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3\nOutput: true\nExplanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.\nExample 2:\nInput: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 \nOutput: false \nExplanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.\n  Constraints:\nm == grid.length\nn == grid[r].length\n1 <= m, n <= 105\n1 <= m * n <= 2 * 105\ngrid[r][c] is either 0 or 1.\n1 <= stampHeight, stampWidth <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/check-if-every-row-and-column-contains-all-numbers/discuss/1775747/Python-3-or-7-Line-solution-or-87-Faster-runtime-or-92.99-lesser-memory",
      "python_solutions": "class Solution:\n    def checkValid(self, matrix: List[List[int]]) -> bool:\n        lst = [0]*len(matrix)\n        for i in matrix:\n            if len(set(i)) != len(matrix):\n                return False\n            for j in range(len(i)):\n                lst[j] += i[j]\n        return len(set(lst)) == 1",
      "slug": "check-if-every-row-and-column-contains-all-numbers",
      "post_title": "\u2714Python 3 | 7 Line solution | 87% Faster runtime | 92.99% lesser memory",
      "user": "Coding_Tan3",
      "upvotes": 6,
      "views": 855,
      "problem_title": "check if every row and column contains all numbers",
      "number": 2133,
      "acceptance": 0.53,
      "difficulty": "Easy",
      "__index_level_0__": 29546,
      "question": "An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).\nGiven an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.\n  Example 1:\nInput: matrix = [[1,2,3],[3,1,2],[2,3,1]]\nOutput: true\nExplanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\nHence, we return true.\nExample 2:\nInput: matrix = [[1,1,1],[1,2,3],[1,2,3]]\nOutput: false\nExplanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\nHence, we return false.\n  Constraints:\nn == matrix.length == matrix[i].length\n1 <= n <= 100\n1 <= matrix[i][j] <= n"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-swaps-to-group-all-1s-together-ii/discuss/1677262/Sliding-window-with-comments-Python",
      "python_solutions": "class Solution:\n    def minSwaps(self, nums: List[int]) -> int:\n        width = sum(num == 1 for num in nums) #width of the window\n        nums += nums\n        res = width\n        curr_zeros = sum(num == 0 for num in nums[:width]) #the first window is nums[:width]\n        \n        for i in range(width, len(nums)):\n            curr_zeros -= (nums[i - width] == 0) #remove the leftmost 0 if exists\n            curr_zeros += (nums[i] == 0) #add the rightmost 0 if exists\n            res = min(res, curr_zeros) #update if needed\n        \n        return res",
      "slug": "minimum-swaps-to-group-all-1s-together-ii",
      "post_title": "Sliding window with comments, Python",
      "user": "kryuki",
      "upvotes": 21,
      "views": 645,
      "problem_title": "minimum swaps to group all 1s together ii",
      "number": 2134,
      "acceptance": 0.507,
      "difficulty": "Medium",
      "__index_level_0__": 29587,
      "question": "A swap is defined as taking two distinct positions in an array and swapping the values in them.\nA circular array is defined as an array where we consider the first element and the last element to be adjacent.\nGiven a binary circular array nums, return the minimum number of swaps required to group all 1's present in the array together at any location.\n  Example 1:\nInput: nums = [0,1,0,1,1,0,0]\nOutput: 1\nExplanation: Here are a few of the ways to group all the 1's together:\n[0,0,1,1,1,0,0] using 1 swap.\n[0,1,1,1,0,0,0] using 1 swap.\n[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).\nThere is no way to group all 1's together with 0 swaps.\nThus, the minimum number of swaps required is 1.\nExample 2:\nInput: nums = [0,1,1,1,0,0,1,1,0]\nOutput: 2\nExplanation: Here are a few of the ways to group all the 1's together:\n[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).\n[1,1,1,1,1,0,0,0,0] using 2 swaps.\nThere is no way to group all 1's together with 0 or 1 swaps.\nThus, the minimum number of swaps required is 2.\nExample 3:\nInput: nums = [1,1,0,0,1]\nOutput: 0\nExplanation: All the 1's are already grouped together due to the circular property of the array.\nThus, the minimum number of swaps required is 0.\n  Constraints:\n1 <= nums.length <= 105\nnums[i] is either 0 or 1."
    },
    {
      "post_href": "https://leetcode.com/problems/count-words-obtained-after-adding-a-letter/discuss/1676852/Python3-bitmask",
      "python_solutions": "class Solution:\n    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n        seen = set()\n        for word in startWords: \n            m = 0\n            for ch in word: m ^= 1 << ord(ch)-97\n            seen.add(m)\n            \n        ans = 0 \n        for word in targetWords: \n            m = 0 \n            for ch in word: m ^= 1 << ord(ch)-97\n            for ch in word: \n                if m ^ (1 << ord(ch)-97) in seen: \n                    ans += 1\n                    break \n        return ans",
      "slug": "count-words-obtained-after-adding-a-letter",
      "post_title": "[Python3] bitmask",
      "user": "ye15",
      "upvotes": 84,
      "views": 5900,
      "problem_title": "count words obtained after adding a letter",
      "number": 2135,
      "acceptance": 0.428,
      "difficulty": "Medium",
      "__index_level_0__": 29602,
      "question": "You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.\nFor each string in targetWords, check if it is possible to choose a string from startWords and perform a conversion operation on it to be equal to that from targetWords.\nThe conversion operation is described in the following two steps:\nAppend any lowercase letter that is not present in the string to its end.\nFor example, if the string is \"abc\", the letters 'd', 'e', or 'y' can be added to it, but not 'a'. If 'd' is added, the resulting string will be \"abcd\".\nRearrange the letters of the new string in any arbitrary order.\nFor example, \"abcd\" can be rearranged to \"acbd\", \"bacd\", \"cbda\", and so on. Note that it can also be rearranged to \"abcd\" itself.\nReturn the number of strings in targetWords that can be obtained by performing the operations on any string of startWords.\nNote that you will only be verifying if the string in targetWords can be obtained from a string in startWords by performing the operations. The strings in startWords do not actually change during this process.\n  Example 1:\nInput: startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]\nOutput: 2\nExplanation:\n- In order to form targetWords[0] = \"tack\", we use startWords[1] = \"act\", append 'k' to it, and rearrange \"actk\" to \"tack\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"act\".\n  Note that \"act\" does exist in startWords, but we must append one letter to the string before rearranging it.\n- In order to form targetWords[2] = \"acti\", we use startWords[1] = \"act\", append 'i' to it, and rearrange \"acti\" to \"acti\" itself.\nExample 2:\nInput: startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]\nOutput: 1\nExplanation:\n- In order to form targetWords[0] = \"abc\", we use startWords[0] = \"ab\", add 'c' to it, and rearrange it to \"abc\".\n- There is no string in startWords that can be used to obtain targetWords[1] = \"abcd\".\n  Constraints:\n1 <= startWords.length, targetWords.length <= 5 * 104\n1 <= startWords[i].length, targetWords[j].length <= 26\nEach string of startWords and targetWords consists of lowercase English letters only.\nNo letter occurs more than once in any string of startWords or targetWords."
    },
    {
      "post_href": "https://leetcode.com/problems/earliest-possible-day-of-full-bloom/discuss/1676837/Grow-then-plant",
      "python_solutions": "class Solution:\n    def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n        res = 0\n        for grow, plant in sorted(zip(growTime, plantTime)):\n            res = max(res, grow) + plant\n        return res",
      "slug": "earliest-possible-day-of-full-bloom",
      "post_title": "Grow then plant",
      "user": "votrubac",
      "upvotes": 203,
      "views": 6900,
      "problem_title": "earliest possible day of full bloom",
      "number": 2136,
      "acceptance": 0.7490000000000001,
      "difficulty": "Hard",
      "__index_level_0__": 29614,
      "question": "You have n flower seeds. Every seed must be planted first before it can begin to grow, then bloom. Planting a seed takes time and so does the growth of a seed. You are given two 0-indexed integer arrays plantTime and growTime, of length n each:\nplantTime[i] is the number of full days it takes you to plant the ith seed. Every day, you can work on planting exactly one seed. You do not have to work on planting the same seed on consecutive days, but the planting of a seed is not complete until you have worked plantTime[i] days on planting it in total.\ngrowTime[i] is the number of full days it takes the ith seed to grow after being completely planted. After the last day of its growth, the flower blooms and stays bloomed forever.\nFrom the beginning of day 0, you can plant the seeds in any order.\nReturn the earliest possible day where all seeds are blooming.\n  Example 1:\nInput: plantTime = [1,4,3], growTime = [2,3,1]\nOutput: 9\nExplanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3.\nOn days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8.\nOn days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.\nExample 2:\nInput: plantTime = [1,2,3,2], growTime = [2,1,2,1]\nOutput: 9\nExplanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\nOne optimal way is:\nOn day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4.\nOn days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5.\nOn days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8.\nOn days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9.\nThus, on day 9, all the seeds are blooming.\nExample 3:\nInput: plantTime = [1], growTime = [1]\nOutput: 2\nExplanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2.\nThus, on day 2, all the seeds are blooming.\n  Constraints:\nn == plantTime.length == growTime.length\n1 <= n <= 105\n1 <= plantTime[i], growTime[i] <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/discuss/1694807/Python-O(n)-solution",
      "python_solutions": "class Solution:\n    def divideString(self, s: str, k: int, fill: str) -> List[str]:\n        length = len(s)\n        res=[]\n        for i in range(0,length,k):\n            if i+k>length:\n                break\n            res.append(s[i:i+k])\n        mod =length%k \n        \n        if mod!= 0:\n            fill_str = fill *(k-mod)\n            add_str = s[i:]+fill_str\n            res.append(add_str)\n            \n        return res",
      "slug": "divide-a-string-into-groups-of-size-k",
      "post_title": "Python O(n) solution",
      "user": "SamyakKrSahoo",
      "upvotes": 2,
      "views": 100,
      "problem_title": "divide a string into groups of size k",
      "number": 2138,
      "acceptance": 0.652,
      "difficulty": "Easy",
      "__index_level_0__": 29649,
      "question": "A string s can be partitioned into groups of size k using the following procedure:\nThe first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each character can be a part of exactly one group.\nFor the last group, if the string does not have k characters remaining, a character fill is used to complete the group.\nNote that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.\nGiven the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.\n  Example 1:\nInput: s = \"abcdefghi\", k = 3, fill = \"x\"\nOutput: [\"abc\",\"def\",\"ghi\"]\nExplanation:\nThe first 3 characters \"abc\" form the first group.\nThe next 3 characters \"def\" form the second group.\nThe last 3 characters \"ghi\" form the third group.\nSince all groups can be completely filled by characters from the string, we do not need to use fill.\nThus, the groups formed are \"abc\", \"def\", and \"ghi\".\nExample 2:\nInput: s = \"abcdefghij\", k = 3, fill = \"x\"\nOutput: [\"abc\",\"def\",\"ghi\",\"jxx\"]\nExplanation:\nSimilar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\nFor the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\nThus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".\n  Constraints:\n1 <= s.length <= 100\ns consists of lowercase English letters only.\n1 <= k <= 100\nfill is a lowercase English letter."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-moves-to-reach-target-score/discuss/1722491/Easy-Solution-python-explained-30ms",
      "python_solutions": "class Solution:\n   def minMoves(self, target: int, maxDoubles: int) -> int:\n       moves = 0\n       while maxDoubles > 0 and target > 1:\n           if target % 2 == 1:\n               target -= 1\n           else:\n               target //= 2\n               maxDoubles -= 1\n           moves += 1\n       moves += target - 1\n       return moves",
      "slug": "minimum-moves-to-reach-target-score",
      "post_title": "Easy Solution python explained 30ms",
      "user": "Volver805",
      "upvotes": 2,
      "views": 83,
      "problem_title": "minimum moves to reach target score",
      "number": 2139,
      "acceptance": 0.484,
      "difficulty": "Medium",
      "__index_level_0__": 29687,
      "question": "You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.\nIn one move, you can either:\nIncrement the current integer by one (i.e., x = x + 1).\nDouble the current integer (i.e., x = 2 * x).\nYou can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.\nGiven the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.\n  Example 1:\nInput: target = 5, maxDoubles = 0\nOutput: 4\nExplanation: Keep incrementing by 1 until you reach target.\nExample 2:\nInput: target = 19, maxDoubles = 2\nOutput: 7\nExplanation: Initially, x = 1\nIncrement 3 times so x = 4\nDouble once so x = 8\nIncrement once so x = 9\nDouble again so x = 18\nIncrement once so x = 19\nExample 3:\nInput: target = 10, maxDoubles = 4\nOutput: 4\nExplanation: Initially, x = 1\nIncrement once so x = 2\nDouble once so x = 4\nIncrement once so x = 5\nDouble again so x = 10\n  Constraints:\n1 <= target <= 109\n0 <= maxDoubles <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/solving-questions-with-brainpower/discuss/1692963/DP",
      "python_solutions": "class Solution:\n    def mostPoints(self, q: List[List[int]]) -> int:\n        @cache\n        def dfs(i: int) -> int:\n            return 0 if i >= len(q) else max(dfs(i + 1), q[i][0] + dfs(i + 1 + q[i][1]))\n        return dfs(0)",
      "slug": "solving-questions-with-brainpower",
      "post_title": "DP",
      "user": "votrubac",
      "upvotes": 132,
      "views": 5500,
      "problem_title": "solving questions with brainpower",
      "number": 2140,
      "acceptance": 0.46,
      "difficulty": "Medium",
      "__index_level_0__": 29711,
      "question": "You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri].\nThe array describes the questions of an exam, where you have to process the questions in order (i.e., starting from question 0) and make a decision whether to solve or skip each question. Solving question i will earn you pointsi points but you will be unable to solve each of the next brainpoweri questions. If you skip question i, you get to make the decision on the next question.\nFor example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]:\nIf question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2.\nIf instead, question 0 is skipped and question 1 is solved, you will earn 4 points but you will be unable to solve questions 2 and 3.\nReturn the maximum points you can earn for the exam.\n  Example 1:\nInput: questions = [[3,2],[4,3],[4,4],[2,5]]\nOutput: 5\nExplanation: The maximum points can be earned by solving questions 0 and 3.\n- Solve question 0: Earn 3 points, will be unable to solve the next 2 questions\n- Unable to solve questions 1 and 2\n- Solve question 3: Earn 2 points\nTotal points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.\nExample 2:\nInput: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]\nOutput: 7\nExplanation: The maximum points can be earned by solving questions 1 and 4.\n- Skip question 0\n- Solve question 1: Earn 2 points, will be unable to solve the next 2 questions\n- Unable to solve questions 2 and 3\n- Solve question 4: Earn 5 points\nTotal points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.\n  Constraints:\n1 <= questions.length <= 105\nquestions[i].length == 2\n1 <= pointsi, brainpoweri <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-running-time-of-n-computers/discuss/1692965/Python3-greedy",
      "python_solutions": "class Solution:\n    def maxRunTime(self, n: int, batteries: List[int]) -> int:\n        batteries.sort()\n        extra = sum(batteries[:-n])\n        batteries = batteries[-n:]\n        \n        ans = prefix = 0 \n        for i, x in enumerate(batteries): \n            prefix += x \n            if i+1 < len(batteries) and batteries[i+1]*(i+1) - prefix > extra: return (prefix + extra) // (i+1)\n        return (prefix + extra) // n",
      "slug": "maximum-running-time-of-n-computers",
      "post_title": "[Python3] greedy",
      "user": "ye15",
      "upvotes": 39,
      "views": 1400,
      "problem_title": "maximum running time of n computers",
      "number": 2141,
      "acceptance": 0.389,
      "difficulty": "Hard",
      "__index_level_0__": 29741,
      "question": "You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries.\nInitially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.\nNote that the batteries cannot be recharged.\nReturn the maximum number of minutes you can run all the n computers simultaneously.\n  Example 1:\nInput: n = 2, batteries = [3,3,3]\nOutput: 4\nExplanation: \nInitially, insert battery 0 into the first computer and battery 1 into the second computer.\nAfter two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\nAt the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.\nBy the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\nWe can run the two computers simultaneously for at most 4 minutes, so we return 4.\nExample 2:\nInput: n = 2, batteries = [1,1,1,1]\nOutput: 2\nExplanation: \nInitially, insert battery 0 into the first computer and battery 2 into the second computer. \nAfter one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. \nAfter another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\nWe can run the two computers simultaneously for at most 2 minutes, so we return 2.\n  Constraints:\n1 <= n <= batteries.length <= 105\n1 <= batteries[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/discuss/1712364/Python-Simple-solution-or-100-faster-or-O(N-logN)-Time-or-O(1)-Space",
      "python_solutions": "class Solution:\n    def minimumCost(self, cost: List[int]) -> int:\n        cost.sort(reverse=True)\n        res, i, N = 0, 0, len(cost)\n        while i < N:\n            res += sum(cost[i : i + 2])\n            i += 3\n        return res",
      "slug": "minimum-cost-of-buying-candies-with-discount",
      "post_title": "[Python] Simple solution | 100% faster | O(N logN) Time | O(1) Space",
      "user": "eshikashah",
      "upvotes": 9,
      "views": 454,
      "problem_title": "minimum cost of buying candies with discount",
      "number": 2144,
      "acceptance": 0.609,
      "difficulty": "Easy",
      "__index_level_0__": 29744,
      "question": "A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.\nThe customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.\nFor example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4.\nGiven a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.\n  Example 1:\nInput: cost = [1,2,3]\nOutput: 5\nExplanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\nThe total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.\nNote that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\nThe cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.\nExample 2:\nInput: cost = [6,5,7,9,2,2]\nOutput: 23\nExplanation: The way in which we can get the minimum cost is described below:\n- Buy candies with costs 9 and 7\n- Take the candy with cost 6 for free\n- We buy candies with costs 5 and 2\n- Take the last remaining candy with cost 2 for free\nHence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.\nExample 3:\nInput: cost = [5,5]\nOutput: 10\nExplanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\nHence, the minimum cost to buy all candies is 5 + 5 = 10.\n  Constraints:\n1 <= cost.length <= 100\n1 <= cost[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/count-the-hidden-sequences/discuss/1714246/Right-Left",
      "python_solutions": "class Solution:\n    def numberOfArrays(self, diff: List[int], lower: int, upper: int) -> int:\n        diff = list(accumulate(diff, initial = 0))\n        return max(0, upper - lower - (max(diff) - min(diff)) + 1)",
      "slug": "count-the-hidden-sequences",
      "post_title": "Right - Left",
      "user": "votrubac",
      "upvotes": 5,
      "views": 266,
      "problem_title": "count the hidden sequences",
      "number": 2145,
      "acceptance": 0.365,
      "difficulty": "Medium",
      "__index_level_0__": 29769,
      "question": "You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].\nYou are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain.\nFor example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive).\n[3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.\n[5, 6, 3, 7] is not possible since it contains an element greater than 6.\n[1, 2, 3, 4] is not possible since the differences are not correct.\nReturn the number of possible hidden sequences there are. If there are no possible sequences, return 0.\n  Example 1:\nInput: differences = [1,-3,4], lower = 1, upper = 6\nOutput: 2\nExplanation: The possible hidden sequences are:\n- [3, 4, 1, 5]\n- [4, 5, 2, 6]\nThus, we return 2.\nExample 2:\nInput: differences = [3,-4,5,1,-2], lower = -4, upper = 5\nOutput: 4\nExplanation: The possible hidden sequences are:\n- [-3, 0, -4, 1, 2, 0]\n- [-2, 1, -3, 2, 3, 1]\n- [-1, 2, -2, 3, 4, 2]\n- [0, 3, -1, 4, 5, 3]\nThus, we return 4.\nExample 3:\nInput: differences = [4,-7,2], lower = 3, upper = 6\nOutput: 0\nExplanation: There are no possible hidden sequences. Thus, we return 0.\n  Constraints:\nn == differences.length\n1 <= n <= 105\n-105 <= differences[i] <= 105\n-105 <= lower <= upper <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/k-highest-ranked-items-within-a-price-range/discuss/1709702/Python3-bfs",
      "python_solutions": "class Solution:\n    def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:\n        m, n = len(grid), len(grid[0])\n        ans = []\n        queue = deque([(0, *start)])\n        grid[start[0]][start[1]] *= -1 \n        while queue: \n            x, i, j = queue.popleft()\n            if pricing[0] <= -grid[i][j] <= pricing[1]: ans.append((x, -grid[i][j], i, j))\n            for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n                if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] > 0: \n                    queue.append((x+1, ii, jj))\n                    grid[ii][jj] *= -1\n        return [[i, j] for _, _, i, j in sorted(ans)[:k]]",
      "slug": "k-highest-ranked-items-within-a-price-range",
      "post_title": "[Python3] bfs",
      "user": "ye15",
      "upvotes": 1,
      "views": 32,
      "problem_title": "k highest ranked items within a price range",
      "number": 2146,
      "acceptance": 0.412,
      "difficulty": "Medium",
      "__index_level_0__": 29779,
      "question": "You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following:\n0 represents a wall that you cannot pass through.\n1 represents an empty cell that you can freely move to and from.\nAll other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.\nIt takes 1 step to travel between adjacent grid cells.\nYou are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k.\nYou are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different:\nDistance, defined as the length of the shortest path from the start (shorter distance has a higher rank).\nPrice (lower price has a higher rank, but it must be in the price range).\nThe row number (smaller row number has a higher rank).\nThe column number (smaller column number has a higher rank).\nReturn the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.\n  Example 1:\nInput: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3\nOutput: [[0,1],[1,1],[2,1]]\nExplanation: You start at (0,0).\nWith a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\nThe ranks of these items are:\n- (0,1) with distance 1\n- (1,1) with distance 2\n- (2,1) with distance 3\n- (2,2) with distance 4\nThus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).\nExample 2:\nInput: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2\nOutput: [[2,1],[1,2]]\nExplanation: You start at (2,3).\nWith a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\nThe ranks of these items are:\n- (2,1) with distance 2, price 2\n- (1,2) with distance 2, price 3\n- (1,1) with distance 3\n- (0,1) with distance 4\nThus, the 2 highest ranked items in the price range are (2,1) and (1,2).\nExample 3:\nInput: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3\nOutput: [[2,1],[2,0]]\nExplanation: You start at (0,0).\nWith a price range of [2,3], we can take items from (2,0) and (2,1). \nThe ranks of these items are: \n- (2,1) with distance 5\n- (2,0) with distance 6\nThus, the 2 highest ranked items in the price range are (2,1) and (2,0). \nNote that k = 3 but there are only 2 reachable items within the price range.\n  Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 105\n1 <= m * n <= 105\n0 <= grid[i][j] <= 105\npricing.length == 2\n2 <= low <= high <= 105\nstart.length == 2\n0 <= row <= m - 1\n0 <= col <= n - 1\ngrid[row][col] > 0\n1 <= k <= m * n"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/discuss/1709706/simple-Python-solution-(time%3A-O(N)-space%3A-O(1))",
      "python_solutions": "class Solution:\n    def numberOfWays(self, corridor: str) -> int:\n        #edge case\n        num_S = corridor.count('S')\n        if num_S == 0 or num_S % 2 == 1:\n            return 0\n        \n        mod = 10 ** 9 + 7\n        curr_s = 0\n        divide_spots = []\n        \n        for char in corridor:\n\t\t\tcurr_s += (char == 'S')\n            if curr_s > 0 and curr_s % 2 == 0:\n                divide_spots[-1] += 1\n            else:\n                if not divide_spots or divide_spots[-1] > 0:\n                    divide_spots.append(0)\n        \n        res = 1\n        for num in divide_spots[:-1]:\n            res = res * num % mod\n        return res",
      "slug": "number-of-ways-to-divide-a-long-corridor",
      "post_title": "simple Python solution (time: O(N), space: O(1))",
      "user": "kryuki",
      "upvotes": 2,
      "views": 92,
      "problem_title": "number of ways to divide a long corridor",
      "number": 2147,
      "acceptance": 0.3989999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 29783,
      "question": "Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant.\nOne room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.\nDivide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way.\nReturn the number of ways to divide the corridor. Since the answer may be very large, return it modulo 109 + 7. If there is no way, return 0.\n  Example 1:\nInput: corridor = \"SSPPSPS\"\nOutput: 3\nExplanation: There are 3 different ways to divide the corridor.\nThe black bars in the above image indicate the two room dividers already installed.\nNote that in each of the ways, each section has exactly two seats.\nExample 2:\nInput: corridor = \"PPSPSP\"\nOutput: 1\nExplanation: There is only 1 way to divide the corridor, by not installing any additional dividers.\nInstalling any would create some section that does not have exactly two seats.\nExample 3:\nInput: corridor = \"S\"\nOutput: 0\nExplanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.\n  Constraints:\nn == corridor.length\n1 <= n <= 105\ncorridor[i] is either 'S' or 'P'."
    },
    {
      "post_href": "https://leetcode.com/problems/count-elements-with-strictly-smaller-and-greater-elements/discuss/2507825/Very-very-easy-code-in-just-3-lines-using-Python",
      "python_solutions": "class Solution:\n    def countElements(self, nums: List[int]) -> int:\n        res = 0\n        mn = min(nums)\n        mx = max(nums)\n        for i in nums:\n            if i > mn and i < mx:\n                res += 1\n        return res",
      "slug": "count-elements-with-strictly-smaller-and-greater-elements",
      "post_title": "Very very easy code in just 3 lines using Python",
      "user": "ankurbhambri",
      "upvotes": 7,
      "views": 44,
      "problem_title": "count elements with strictly smaller and greater elements",
      "number": 2148,
      "acceptance": 0.6,
      "difficulty": "Easy",
      "__index_level_0__": 29793,
      "question": "Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.\n  Example 1:\nInput: nums = [11,7,2,15]\nOutput: 2\nExplanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\nElement 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\nIn total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\nExample 2:\nInput: nums = [-3,3,3,90]\nOutput: 2\nExplanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\nSince there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\n  Constraints:\n1 <= nums.length <= 100\n-105 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/rearrange-array-elements-by-sign/discuss/1711329/Two-Pointers",
      "python_solutions": "class Solution:\n    def rearrangeArray(self, nums: List[int]) -> List[int]:\n        return [i for t in zip([p for p in nums if p > 0], [n for n in nums if n < 0]) for i in t]",
      "slug": "rearrange-array-elements-by-sign",
      "post_title": "Two Pointers",
      "user": "votrubac",
      "upvotes": 20,
      "views": 5200,
      "problem_title": "rearrange array elements by sign",
      "number": 2149,
      "acceptance": 0.8109999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 29821,
      "question": "You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.\nYou should return the array of nums such that the the array follows the given conditions:\nEvery consecutive pair of integers have opposite signs.\nFor all integers with the same sign, the order in which they were present in nums is preserved.\nThe rearranged array begins with a positive integer.\nReturn the modified array after rearranging the elements to satisfy the aforementioned conditions.\n  Example 1:\nInput: nums = [3,1,-2,-5,2,-4]\nOutput: [3,-2,1,-5,2,-4]\nExplanation:\nThe positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\nThe only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\nOther ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  \nExample 2:\nInput: nums = [-1,1]\nOutput: [1,-1]\nExplanation:\n1 is the only positive integer and -1 the only negative integer in nums.\nSo nums is rearranged to [1,-1].\n  Constraints:\n2 <= nums.length <= 2 * 105\nnums.length is even\n1 <= |nums[i]| <= 105\nnums consists of equal number of positive and negative integers.\n  It is not required to do the modifications in-place."
    },
    {
      "post_href": "https://leetcode.com/problems/find-all-lonely-numbers-in-the-array/discuss/1711316/Counter",
      "python_solutions": "class Solution:\n    def findLonely(self, nums: List[int]) -> List[int]:\n        m = Counter(nums)\n        return [n for n in nums if m[n] == 1 and m[n - 1] + m[n + 1] == 0]",
      "slug": "find-all-lonely-numbers-in-the-array",
      "post_title": "Counter",
      "user": "votrubac",
      "upvotes": 43,
      "views": 3400,
      "problem_title": "find all lonely numbers in the array",
      "number": 2150,
      "acceptance": 0.608,
      "difficulty": "Medium",
      "__index_level_0__": 29862,
      "question": "You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.\nReturn all lonely numbers in nums. You may return the answer in any order.\n  Example 1:\nInput: nums = [10,6,5,8]\nOutput: [10,8]\nExplanation: \n- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.\n- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.\n- 5 is not a lonely number since 6 appears in nums and vice versa.\nHence, the lonely numbers in nums are [10, 8].\nNote that [8, 10] may also be returned.\nExample 2:\nInput: nums = [1,3,5,3]\nOutput: [1,5]\nExplanation: \n- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.\n- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.\n- 3 is not a lonely number since it appears twice.\nHence, the lonely numbers in nums are [1, 5].\nNote that [5, 1] may also be returned.\n  Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-good-people-based-on-statements/discuss/1711677/Python-3-or-Itertools-and-Bitmask-or-Explanation",
      "python_solutions": "class Solution:\n    def maximumGood(self, statements: List[List[int]]) -> int:\n        ans, n = 0, len(statements)\n        for person in itertools.product([0, 1], repeat=n): # use itertools to create a list only contains 0 or 1\n            valid = True                                   # initially, we think the `person` list is valid\n            for i in range(n):\n                if not person[i]: continue                 # only `good` person's statement can lead to a contradiction, we don't care what `bad` person says\n                for j in range(n):\n                    if statements[i][j] == 2: continue     # ignore is no statement was made\n                    if statements[i][j] != person[j]:      # if there is a contradiction, then valid = False\n                        valid = False\n                        break                              # optimization: break the loop when not valid\n                if not valid:                              # optimization: break the loop when not valid\n                    break        \n            if valid: \n                ans = max(ans, sum(person))                # count sum only when valid == True\n        return ans",
      "slug": "maximum-good-people-based-on-statements",
      "post_title": "Python 3 | Itertools & Bitmask | Explanation",
      "user": "idontknoooo",
      "upvotes": 2,
      "views": 126,
      "problem_title": "maximum good people based on statements",
      "number": 2151,
      "acceptance": 0.486,
      "difficulty": "Hard",
      "__index_level_0__": 29880,
      "question": "There are two types of persons:\nThe good person: The person who always tells the truth.\nThe bad person: The person who might tell the truth and might lie.\nYou are given a 0-indexed 2D integer array statements of size n x n that represents the statements made by n people about each other. More specifically, statements[i][j] could be one of the following:\n0 which represents a statement made by person i that person j is a bad person.\n1 which represents a statement made by person i that person j is a good person.\n2 represents that no statement is made by person i about person j.\nAdditionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n.\nReturn the maximum number of people who can be good based on the statements made by the n people.\n  Example 1:\nInput: statements = [[2,1,2],[1,2,2],[2,0,2]]\nOutput: 2\nExplanation: Each person makes a single statement.\n- Person 0 states that person 1 is good.\n- Person 1 states that person 0 is good.\n- Person 2 states that person 1 is bad.\nLet's take person 2 as the key.\n- Assuming that person 2 is a good person:\n    - Based on the statement made by person 2, person 1 is a bad person.\n    - Now we know for sure that person 1 is bad and person 2 is good.\n    - Based on the statement made by person 1, and since person 1 is bad, they could be:\n        - telling the truth. There will be a contradiction in this case and this assumption is invalid.\n        - lying. In this case, person 0 is also a bad person and lied in their statement.\n    - Following that person 2 is a good person, there will be only one good person in the group.\n- Assuming that person 2 is a bad person:\n    - Based on the statement made by person 2, and since person 2 is bad, they could be:\n        - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.\n            - Following that person 2 is bad but told the truth, there will be no good persons in the group.\n        - lying. In this case person 1 is a good person.\n            - Since person 1 is a good person, person 0 is also a good person.\n            - Following that person 2 is bad and lied, there will be two good persons in the group.\nWe can see that at most 2 persons are good in the best case, so we return 2.\nNote that there is more than one way to arrive at this conclusion.\nExample 2:\nInput: statements = [[2,0],[0,2]]\nOutput: 1\nExplanation: Each person makes a single statement.\n- Person 0 states that person 1 is bad.\n- Person 1 states that person 0 is bad.\nLet's take person 0 as the key.\n- Assuming that person 0 is a good person:\n    - Based on the statement made by person 0, person 1 is a bad person and was lying.\n    - Following that person 0 is a good person, there will be only one good person in the group.\n- Assuming that person 0 is a bad person:\n    - Based on the statement made by person 0, and since person 0 is bad, they could be:\n        - telling the truth. Following this scenario, person 0 and 1 are both bad.\n            - Following that person 0 is bad but told the truth, there will be no good persons in the group.\n        - lying. In this case person 1 is a good person.\n            - Following that person 0 is bad and lied, there will be only one good person in the group.\nWe can see that at most, one person is good in the best case, so we return 1.\nNote that there is more than one way to arrive at this conclusion.\n  Constraints:\nn == statements.length == statements[i].length\n2 <= n <= 15\nstatements[i][j] is either 0, 1, or 2.\nstatements[i][i] == 2"
    },
    {
      "post_href": "https://leetcode.com/problems/keep-multiplying-found-values-by-two/discuss/2531609/Python-solution-simple-faster-than-80-less-memory-than-99",
      "python_solutions": "class Solution:\n\n def findFinalValue(self, nums: List[int], original: int) -> int:\n\n    while original in nums:\n\t\n        original *= 2\n\t\t\n    return original",
      "slug": "keep-multiplying-found-values-by-two",
      "post_title": "Python solution simple faster than 80% less memory than 99%",
      "user": "Theo704",
      "upvotes": 2,
      "views": 62,
      "problem_title": "keep multiplying found values by two",
      "number": 2154,
      "acceptance": 0.731,
      "difficulty": "Easy",
      "__index_level_0__": 29886,
      "question": "You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums.\nYou then do the following steps:\nIf original is found in nums, multiply it by two (i.e., set original = 2 * original).\nOtherwise, stop the process.\nRepeat this process with the new number as long as you keep finding the number.\nReturn the final value of original.\n  Example 1:\nInput: nums = [5,3,6,1,12], original = 3\nOutput: 24\nExplanation: \n- 3 is found in nums. 3 is multiplied by 2 to obtain 6.\n- 6 is found in nums. 6 is multiplied by 2 to obtain 12.\n- 12 is found in nums. 12 is multiplied by 2 to obtain 24.\n- 24 is not found in nums. Thus, 24 is returned.\nExample 2:\nInput: nums = [2,7,9], original = 4\nOutput: 4\nExplanation:\n- 4 is not found in nums. Thus, 4 is returned.\n  Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i], original <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/all-divisions-with-the-highest-score-of-a-binary-array/discuss/1732887/Python3-scan",
      "python_solutions": "class Solution:\n    def maxScoreIndices(self, nums: List[int]) -> List[int]:\n        ans = [0]\n        cand = most = nums.count(1)\n        for i, x in enumerate(nums): \n            if x == 0: cand += 1\n            elif x == 1: cand -= 1\n            if cand > most: ans, most = [i+1], cand\n            elif cand == most: ans.append(i+1)\n        return ans",
      "slug": "all-divisions-with-the-highest-score-of-a-binary-array",
      "post_title": "[Python3] scan",
      "user": "ye15",
      "upvotes": 2,
      "views": 39,
      "problem_title": "all divisions with the highest score of a binary array",
      "number": 2155,
      "acceptance": 0.634,
      "difficulty": "Medium",
      "__index_level_0__": 29934,
      "question": "You are given a 0-indexed binary array nums of length n. nums can be divided at index i (where 0 <= i <= n) into two arrays (possibly empty) numsleft and numsright:\nnumsleft has all the elements of nums between index 0 and i - 1 (inclusive), while numsright has all the elements of nums between index i and n - 1 (inclusive).\nIf i == 0, numsleft is empty, while numsright has all the elements of nums.\nIf i == n, numsleft has all the elements of nums, while numsright is empty.\nThe division score of an index i is the sum of the number of 0's in numsleft and the number of 1's in numsright.\nReturn all distinct indices that have the highest possible division score. You may return the answer in any order.\n  Example 1:\nInput: nums = [0,0,1,0]\nOutput: [2,4]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [0,0,1,0]. The score is 0 + 1 = 1.\n- 1: numsleft is [0]. numsright is [0,1,0]. The score is 1 + 1 = 2.\n- 2: numsleft is [0,0]. numsright is [1,0]. The score is 2 + 1 = 3.\n- 3: numsleft is [0,0,1]. numsright is [0]. The score is 2 + 0 = 2.\n- 4: numsleft is [0,0,1,0]. numsright is []. The score is 3 + 0 = 3.\nIndices 2 and 4 both have the highest possible division score 3.\nNote the answer [4,2] would also be accepted.\nExample 2:\nInput: nums = [0,0,0]\nOutput: [3]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [0,0,0]. The score is 0 + 0 = 0.\n- 1: numsleft is [0]. numsright is [0,0]. The score is 1 + 0 = 1.\n- 2: numsleft is [0,0]. numsright is [0]. The score is 2 + 0 = 2.\n- 3: numsleft is [0,0,0]. numsright is []. The score is 3 + 0 = 3.\nOnly index 3 has the highest possible division score 3.\nExample 3:\nInput: nums = [1,1]\nOutput: [0]\nExplanation: Division at index\n- 0: numsleft is []. numsright is [1,1]. The score is 0 + 2 = 2.\n- 1: numsleft is [1]. numsright is [1]. The score is 0 + 1 = 1.\n- 2: numsleft is [1,1]. numsright is []. The score is 0 + 0 = 0.\nOnly index 0 has the highest possible division score 2.\n  Constraints:\nn == nums.length\n1 <= n <= 105\nnums[i] is either 0 or 1."
    },
    {
      "post_href": "https://leetcode.com/problems/find-substring-with-given-hash-value/discuss/1732936/Python3-rolling-hash",
      "python_solutions": "class Solution:\n    def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:\n        pp = pow(power, k-1, modulo)\n        hs = ii = 0 \n        for i, ch in enumerate(reversed(s)): \n            if i >= k: hs -= (ord(s[~(i-k)]) - 96)*pp\n            hs = (hs * power + (ord(ch) - 96)) % modulo\n            if i >= k-1 and hs == hashValue: ii = i \n        return s[~ii:~ii+k or None]",
      "slug": "find-substring-with-given-hash-value",
      "post_title": "[Python3] rolling hash",
      "user": "ye15",
      "upvotes": 2,
      "views": 79,
      "problem_title": "find substring with given hash value",
      "number": 2156,
      "acceptance": 0.221,
      "difficulty": "Hard",
      "__index_level_0__": 29954,
      "question": "The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:\nhash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.\nWhere val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.\nYou are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.\nThe test cases will be generated such that an answer always exists.\nA substring is a contiguous non-empty sequence of characters within a string.\n  Example 1:\nInput: s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0\nOutput: \"ee\"\nExplanation: The hash of \"ee\" can be computed to be hash(\"ee\", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. \n\"ee\" is the first substring of length 2 with hashValue 0. Hence, we return \"ee\".\nExample 2:\nInput: s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32\nOutput: \"fbx\"\nExplanation: The hash of \"fbx\" can be computed to be hash(\"fbx\", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. \nThe hash of \"bxz\" can be computed to be hash(\"bxz\", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. \n\"fbx\" is the first substring of length 3 with hashValue 32. Hence, we return \"fbx\".\nNote that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".\n  Constraints:\n1 <= k <= s.length <= 2 * 104\n1 <= power, modulo <= 109\n0 <= hashValue < modulo\ns consists of lowercase English letters only.\nThe test cases are generated such that an answer always exists."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-sum-of-four-digit-number-after-splitting-digits/discuss/1747018/Python-simple-and-fast-with-explanation-no-permutation",
      "python_solutions": "class Solution:\n    def minimumSum(self, num: int) -> int:\n        num = sorted(str(num),reverse=True)\n        n = len(num)    \n        res = 0\n        even_iteration = False\n        position = 0\n        for i in range(n):\n            res += int(num[i])*(10**position)\n            if even_iteration:\n                position += 1\n                even_iteration = False\n            else:\n                even_iteration = True\n        return res",
      "slug": "minimum-sum-of-four-digit-number-after-splitting-digits",
      "post_title": "Python - simple & fast with explanation - no permutation",
      "user": "fatamorgana",
      "upvotes": 43,
      "views": 4300,
      "problem_title": "minimum sum of four digit number after splitting digits",
      "number": 2160,
      "acceptance": 0.879,
      "difficulty": "Easy",
      "__index_level_0__": 29961,
      "question": "You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.\nFor example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].\nReturn the minimum possible sum of new1 and new2.\n  Example 1:\nInput: num = 2932\nOutput: 52\nExplanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\nThe minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.\nExample 2:\nInput: num = 4009\nOutput: 13\nExplanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \nThe minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.\n  Constraints:\n1000 <= num <= 9999"
    },
    {
      "post_href": "https://leetcode.com/problems/partition-array-according-to-given-pivot/discuss/1748566/Python-Simple-and-Clean-Python-Solution-by-Removing-and-Appending",
      "python_solutions": "class Solution:\n\tdef pivotArray(self, nums: List[int], pivot: int) -> List[int]:\n\n\t\tans=[]\n\n\t\tnums.remove(pivot)\n\n\t\ti=0\n\t\tans.append(pivot)\n\n\t\tfor j in nums:\n\t\t\tif j pivot and nums[j] > pivot, then pi < pj.\nReturn nums after the rearrangement.\n  Example 1:\nInput: nums = [9,12,5,10,14,3,10], pivot = 10\nOutput: [9,5,3,10,10,12,14]\nExplanation: \nThe elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\nThe elements 12 and 14 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.\nExample 2:\nInput: nums = [-3,4,3,2], pivot = 2\nOutput: [-3,2,4,3]\nExplanation: \nThe element -3 is less than the pivot so it is on the left side of the array.\nThe elements 4 and 3 are greater than the pivot so they are on the right side of the array.\nThe relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.\n  Constraints:\n1 <= nums.length <= 105\n-106 <= nums[i] <= 106\npivot equals to an element of nums."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-cost-to-set-cooking-time/discuss/1746996/Simple-Python-Solution",
      "python_solutions": "class Solution:\n    def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n        def count_cost(minutes, seconds): # Calculates cost for certain configuration of minutes and seconds\n            time = f'{minutes // 10}{minutes % 10}{seconds // 10}{seconds % 10}' # mm:ss\n            time = time.lstrip('0') # since 0's are prepended we remove the 0's to the left to minimize cost\n            t = [int(i) for i in time]\n            current = startAt\n            cost = 0\n            for i in t:\n                if i != current:\n                    current = i\n                    cost += moveCost\n                cost += pushCost\n            return cost\n        ans = float('inf')\n        for m in range(100): # Check which [mm:ss] configuration works out\n            for s in range(100):\n                if m * 60 + s == targetSeconds: \n                    ans = min(ans, count_cost(m, s))\n        return ans",
      "slug": "minimum-cost-to-set-cooking-time",
      "post_title": "Simple Python Solution",
      "user": "anCoderr",
      "upvotes": 10,
      "views": 513,
      "problem_title": "minimum cost to set cooking time",
      "number": 2162,
      "acceptance": 0.396,
      "difficulty": "Medium",
      "__index_level_0__": 30053,
      "question": "A generic microwave supports cooking times for:\nat least 1 second.\nat most 99 minutes and 99 seconds.\nTo set the cooking time, you push at most four digits. The microwave normalizes what you push as four digits by prepending zeroes. It interprets the first two digits as the minutes and the last two digits as the seconds. It then adds them up as the cooking time. For example,\nYou push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds.\nYou push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds.\nYou push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds.\nYou push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds.\nYou are given integers startAt, moveCost, pushCost, and targetSeconds. Initially, your finger is on the digit startAt. Moving the finger above any specific digit costs moveCost units of fatigue. Pushing the digit below the finger once costs pushCost units of fatigue.\nThere can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost.\nReturn the minimum cost to set targetSeconds seconds of cooking time.\nRemember that one minute consists of 60 seconds.\n  Example 1:\nInput: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600\nOutput: 6\nExplanation: The following are the possible ways to set the cooking time.\n- 1 0 0 0, interpreted as 10 minutes and 0 seconds.\n  The finger is already on digit 1, pushes 1 (with cost 1), moves to 0 (with cost 2), pushes 0 (with cost 1), pushes 0 (with cost 1), and pushes 0 (with cost 1).\n  The cost is: 1 + 2 + 1 + 1 + 1 = 6. This is the minimum cost.\n- 0 9 6 0, interpreted as 9 minutes and 60 seconds. That is also 600 seconds.\n  The finger moves to 0 (with cost 2), pushes 0 (with cost 1), moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n  The cost is: 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 = 12.\n- 9 6 0, normalized as 0960 and interpreted as 9 minutes and 60 seconds.\n  The finger moves to 9 (with cost 2), pushes 9 (with cost 1), moves to 6 (with cost 2), pushes 6 (with cost 1), moves to 0 (with cost 2), and pushes 0 (with cost 1).\n  The cost is: 2 + 1 + 2 + 1 + 2 + 1 = 9.\nExample 2:\nInput: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76\nOutput: 6\nExplanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds.\nThe finger moves to 7 (with cost 1), pushes 7 (with cost 2), moves to 6 (with cost 1), and pushes 6 (with cost 2). The total cost is: 1 + 2 + 1 + 2 = 6\nNote other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.\n  Constraints:\n0 <= startAt <= 9\n1 <= moveCost, pushCost <= 105\n1 <= targetSeconds <= 6039"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-difference-in-sums-after-removal-of-elements/discuss/2392142/Python-solution-or-O(nlogn)-or-explained-with-diagram-or-heap-and-dp-solution",
      "python_solutions": "class Solution:\n    def minimumDifference(self, nums: List[int]) -> int:\n        n = len(nums) // 3\n\n        # calculate max_sum using min_heap for second part\n        min_heap = nums[(2 * n) :]\n        heapq.heapify(min_heap)\n\n        max_sum = [0] * (n + 2)\n        max_sum[n + 1] = sum(min_heap)\n        for i in range((2 * n) - 1, n - 1, -1):\n            # push current\n            heapq.heappush(min_heap, nums[i])\n            # popout minimum from heap\n            val = heapq.heappop(min_heap)\n            # max_sum for this partition\n            max_sum[i - n + 1] = max_sum[i - n + 2] - val + nums[i]\n\n\n        # calculate min_sum using max_heap for first part\n        max_heap = [-x for x in nums[:n]]\n        heapq.heapify(max_heap)\n\n        min_sum = [0] * (n + 2)\n        min_sum[0] = -sum(max_heap)\n        for i in range(n, (2 * n)):\n            # push current\n            heapq.heappush(max_heap, -nums[i])\n            # popout maximum from heap\n            val = -heapq.heappop(max_heap)\n            # min_sum for this partition\n            min_sum[i - n + 1] = min_sum[i - n] - val + nums[i]\n\n\n        # find min difference bw second part (max_sum) and first part (min_sum)\n        ans = math.inf\n        for i in range(0, n + 1):\n            print(i, min_sum[i], max_sum[i])\n            ans = min((min_sum[i] - max_sum[i + 1]), ans)\n\n        return ans",
      "slug": "minimum-difference-in-sums-after-removal-of-elements",
      "post_title": "Python solution | O(nlogn) | explained with diagram | heap and dp solution",
      "user": "wilspi",
      "upvotes": 1,
      "views": 64,
      "problem_title": "minimum difference in sums after removal of elements",
      "number": 2163,
      "acceptance": 0.467,
      "difficulty": "Hard",
      "__index_level_0__": 30059,
      "question": "You are given a 0-indexed integer array nums consisting of 3 * n elements.\nYou are allowed to remove any subsequence of elements of size exactly n from nums. The remaining 2 * n elements will be divided into two equal parts:\nThe first n elements belonging to the first part and their sum is sumfirst.\nThe next n elements belonging to the second part and their sum is sumsecond.\nThe difference in sums of the two parts is denoted as sumfirst - sumsecond.\nFor example, if sumfirst = 3 and sumsecond = 2, their difference is 1.\nSimilarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.\nReturn the minimum difference possible between the sums of the two parts after the removal of n elements.\n  Example 1:\nInput: nums = [3,1,2]\nOutput: -1\nExplanation: Here, nums has 3 elements, so n = 1. \nThus we have to remove 1 element from nums and divide the array into two equal parts.\n- If we remove nums[0] = 3, the array will be [1,2]. The difference in sums of the two parts will be 1 - 2 = -1.\n- If we remove nums[1] = 1, the array will be [3,2]. The difference in sums of the two parts will be 3 - 2 = 1.\n- If we remove nums[2] = 2, the array will be [3,1]. The difference in sums of the two parts will be 3 - 1 = 2.\nThe minimum difference between sums of the two parts is min(-1,1,2) = -1. \nExample 2:\nInput: nums = [7,9,5,8,1,3]\nOutput: 1\nExplanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\nIf we remove nums[2] = 5 and nums[3] = 8, the resultant array will be [7,9,1,3]. The difference in sums will be (7+9) - (1+3) = 12.\nTo obtain the minimum difference, we should remove nums[1] = 9 and nums[4] = 1. The resultant array becomes [7,5,8,3]. The difference in sums of the two parts is (7+5) - (8+3) = 1.\nIt can be shown that it is not possible to obtain a difference smaller than 1.\n  Constraints:\nnums.length == 3 * n\n1 <= n <= 105\n1 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/sort-even-and-odd-indices-independently/discuss/2214566/Python-oror-In-Place-Sorting",
      "python_solutions": "class Solution:\n\tdef sortEvenOdd(self, nums: List[int]) -> List[int]:\n\t\tn = len(nums)\n\t\tfor i in range(0,n,2):\n\t\t\tfor j in range(i+2,n,2):\n\t\t\t\tif nums[i] > nums[j]:\n\t\t\t\t\tnums[i],nums[j] = nums[j], nums[i]\n\n\t\tfor i in range(1,n,2):\n\t\t\tfor j in range(i+2,n,2):\n\t\t\t\tif nums[i] < nums[j]:\n\t\t\t\t\tnums[i],nums[j] = nums[j], nums[i]\n\t\treturn nums",
      "slug": "sort-even-and-odd-indices-independently",
      "post_title": "Python || In Place Sorting",
      "user": "morpheusdurden",
      "upvotes": 1,
      "views": 186,
      "problem_title": "sort even and odd indices independently",
      "number": 2164,
      "acceptance": 0.664,
      "difficulty": "Easy",
      "__index_level_0__": 30062,
      "question": "You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:\nSort the values at odd indices of nums in non-increasing order.\nFor example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order.\nSort the values at even indices of nums in non-decreasing order.\nFor example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order.\nReturn the array formed after rearranging the values of nums.\n  Example 1:\nInput: nums = [4,1,2,3]\nOutput: [2,3,4,1]\nExplanation: \nFirst, we sort the values present at odd indices (1 and 3) in non-increasing order.\nSo, nums changes from [4,1,2,3] to [4,3,2,1].\nNext, we sort the values present at even indices (0 and 2) in non-decreasing order.\nSo, nums changes from [4,1,2,3] to [2,3,4,1].\nThus, the array formed after rearranging the values is [2,3,4,1].\nExample 2:\nInput: nums = [2,1]\nOutput: [2,1]\nExplanation: \nSince there is exactly one odd index and one even index, no rearrangement of values takes place.\nThe resultant array formed is [2,1], which is the same as the initial array. \n  Constraints:\n1 <= nums.length <= 100\n1 <= nums[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/smallest-value-of-the-rearranged-number/discuss/1755847/PYTHON3-or-EASY-SOLUTION-or",
      "python_solutions": "class Solution:\n    def smallestNumber(self, num: int) -> int:\n        \n        if num == 0 : return 0 \n        snum = sorted(str(num))\n        if snum[0] == '-' :\n            return -int(\"\".join(snum[:0:-1]))\n        elif snum[0] == '0' :\n            x = snum.count('0')\n            return \"\".join([snum[x]]+['0'*x]+snum[x+1:])\n        else :\n            return \"\".join(snum)",
      "slug": "smallest-value-of-the-rearranged-number",
      "post_title": "PYTHON3 | EASY  SOLUTION |",
      "user": "rohitkhairnar",
      "upvotes": 1,
      "views": 108,
      "problem_title": "smallest value of the rearranged number",
      "number": 2165,
      "acceptance": 0.513,
      "difficulty": "Medium",
      "__index_level_0__": 30084,
      "question": "You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.\nReturn the rearranged number with minimal value.\nNote that the sign of the number does not change after rearranging the digits.\n  Example 1:\nInput: num = 310\nOutput: 103\nExplanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \nThe arrangement with the smallest value that does not contain any leading zeros is 103.\nExample 2:\nInput: num = -7605\nOutput: -7650\nExplanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\nThe arrangement with the smallest value that does not contain any leading zeros is -7650.\n  Constraints:\n-1015 <= num <= 1015"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-time-to-remove-all-cars-containing-illegal-goods/discuss/2465604/Python3-dp",
      "python_solutions": "class Solution:\n    def minimumTime(self, s: str) -> int:\n        ans = inf \n        prefix = 0 \n        for i, ch in enumerate(s): \n            if ch == '1': prefix = min(2 + prefix, i+1)\n            ans = min(ans, prefix + len(s)-1-i)\n        return ans",
      "slug": "minimum-time-to-remove-all-cars-containing-illegal-goods",
      "post_title": "[Python3] dp",
      "user": "ye15",
      "upvotes": 0,
      "views": 24,
      "problem_title": "minimum time to remove all cars containing illegal goods",
      "number": 2167,
      "acceptance": 0.402,
      "difficulty": "Hard",
      "__index_level_0__": 30094,
      "question": "You are given a 0-indexed binary string s which represents a sequence of train cars. s[i] = '0' denotes that the ith car does not contain illegal goods and s[i] = '1' denotes that the ith car does contain illegal goods.\nAs the train conductor, you would like to get rid of all the cars containing illegal goods. You can do any of the following three operations any number of times:\nRemove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time.\nRemove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time.\nRemove a train car from anywhere in the sequence which takes 2 units of time.\nReturn the minimum time to remove all the cars containing illegal goods.\nNote that an empty sequence of cars is considered to have no cars containing illegal goods.\n  Example 1:\nInput: s = \"1100101\"\nOutput: 5\nExplanation: \nOne way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end. Time taken is 1.\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2 + 1 + 2 = 5. \n\nAn alternative way is to\n- remove a car from the left end 2 times. Time taken is 2 * 1 = 2.\n- remove a car from the right end 3 times. Time taken is 3 * 1 = 3.\nThis also obtains a total time of 2 + 3 = 5.\n\n5 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.\nExample 2:\nInput: s = \"0010\"\nOutput: 2\nExplanation:\nOne way to remove all the cars containing illegal goods from the sequence is to\n- remove a car from the left end 3 times. Time taken is 3 * 1 = 3.\nThis obtains a total time of 3.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to\n- remove the car containing illegal goods found in the middle. Time taken is 2.\nThis obtains a total time of 2.\n\nAnother way to remove all the cars containing illegal goods from the sequence is to \n- remove a car from the right end 2 times. Time taken is 2 * 1 = 2. \nThis obtains a total time of 2.\n\n2 is the minimum time taken to remove all the cars containing illegal goods. \nThere are no other ways to remove them with less time.\n  Constraints:\n1 <= s.length <= 2 * 105\ns[i] is either '0' or '1'."
    },
    {
      "post_href": "https://leetcode.com/problems/count-operations-to-obtain-zero/discuss/1766882/Python3-simulation",
      "python_solutions": "class Solution:\n    def countOperations(self, num1: int, num2: int) -> int:\n        ans = 0 \n        while num1 and num2: \n            ans += num1//num2\n            num1, num2 = num2, num1%num2\n        return ans",
      "slug": "count-operations-to-obtain-zero",
      "post_title": "[Python3] simulation",
      "user": "ye15",
      "upvotes": 4,
      "views": 385,
      "problem_title": "count operations to obtain zero",
      "number": 2169,
      "acceptance": 0.755,
      "difficulty": "Easy",
      "__index_level_0__": 30096,
      "question": "You are given two non-negative integers num1 and num2.\nIn one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.\nFor example, if num1 = 5 and num2 = 4, subtract num2 from num1, thus obtaining num1 = 1 and num2 = 4. However, if num1 = 4 and num2 = 5, after one operation, num1 = 4 and num2 = 1.\nReturn the number of operations required to make either num1 = 0 or num2 = 0.\n  Example 1:\nInput: num1 = 2, num2 = 3\nOutput: 3\nExplanation: \n- Operation 1: num1 = 2, num2 = 3. Since num1 < num2, we subtract num1 from num2 and get num1 = 2, num2 = 3 - 2 = 1.\n- Operation 2: num1 = 2, num2 = 1. Since num1 > num2, we subtract num2 from num1.\n- Operation 3: num1 = 1, num2 = 1. Since num1 == num2, we subtract num2 from num1.\nNow num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\nSo the total number of operations required is 3.\nExample 2:\nInput: num1 = 10, num2 = 10\nOutput: 1\nExplanation: \n- Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\nNow num1 = 0 and num2 = 10. Since num1 == 0, we are done.\nSo the total number of operations required is 1.\n  Constraints:\n0 <= num1, num2 <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-operations-to-make-the-array-alternating/discuss/1766909/Python3-4-line",
      "python_solutions": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        pad = lambda x: x + [(None, 0)]*(2-len(x))\n        even = pad(Counter(nums[::2]).most_common(2))\n        odd = pad(Counter(nums[1::2]).most_common(2))\n        return len(nums) - (max(even[0][1] + odd[1][1], even[1][1] + odd[0][1]) if even[0][0] == odd[0][0] else even[0][1] + odd[0][1])",
      "slug": "minimum-operations-to-make-the-array-alternating",
      "post_title": "[Python3] 4-line",
      "user": "ye15",
      "upvotes": 19,
      "views": 1600,
      "problem_title": "minimum operations to make the array alternating",
      "number": 2170,
      "acceptance": 0.332,
      "difficulty": "Medium",
      "__index_level_0__": 30123,
      "question": "You are given a 0-indexed array nums consisting of n positive integers.\nThe array nums is called alternating if:\nnums[i - 2] == nums[i], where 2 <= i <= n - 1.\nnums[i - 1] != nums[i], where 1 <= i <= n - 1.\nIn one operation, you can choose an index i and change nums[i] into any positive integer.\nReturn the minimum number of operations required to make the array alternating.\n  Example 1:\nInput: nums = [3,1,3,2,4,3]\nOutput: 3\nExplanation:\nOne way to make the array alternating is by converting it to [3,1,3,1,3,1].\nThe number of operations required in this case is 3.\nIt can be proven that it is not possible to make the array alternating in less than 3 operations. \nExample 2:\nInput: nums = [1,2,2,2,2]\nOutput: 2\nExplanation:\nOne way to make the array alternating is by converting it to [1,2,1,2,1].\nThe number of operations required in this case is 2.\nNote that the array cannot be converted to [2,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/removing-minimum-number-of-magic-beans/discuss/1766873/Python3-2-line",
      "python_solutions": "class Solution:\n    def minimumRemoval(self, beans: List[int]) -> int:\n        beans.sort()\n        return sum(beans) - max((len(beans)-i)*x for i, x in enumerate(beans))",
      "slug": "removing-minimum-number-of-magic-beans",
      "post_title": "[Python3] 2-line",
      "user": "ye15",
      "upvotes": 4,
      "views": 163,
      "problem_title": "removing minimum number of magic beans",
      "number": 2171,
      "acceptance": 0.42,
      "difficulty": "Medium",
      "__index_level_0__": 30138,
      "question": "You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.\nRemove any number of beans (possibly none) from each bag such that the number of beans in each remaining non-empty bag (still containing at least one bean) is equal. Once a bean has been removed from a bag, you are not allowed to return it to any of the bags.\nReturn the minimum number of magic beans that you have to remove.\n  Example 1:\nInput: beans = [4,1,6,5]\nOutput: 4\nExplanation: \n- We remove 1 bean from the bag with only 1 bean.\n  This results in the remaining bags: [4,0,6,5]\n- Then we remove 2 beans from the bag with 6 beans.\n  This results in the remaining bags: [4,0,4,5]\n- Then we remove 1 bean from the bag with 5 beans.\n  This results in the remaining bags: [4,0,4,4]\nWe removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that remove 4 beans or fewer.\nExample 2:\nInput: beans = [2,10,3,2]\nOutput: 7\nExplanation:\n- We remove 2 beans from one of the bags with 2 beans.\n  This results in the remaining bags: [0,10,3,2]\n- Then we remove 2 beans from the other bag with 2 beans.\n  This results in the remaining bags: [0,10,3,0]\n- Then we remove 3 beans from the bag with 3 beans. \n  This results in the remaining bags: [0,10,0,0]\nWe removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\nThere are no other solutions that removes 7 beans or fewer.\n  Constraints:\n1 <= beans.length <= 105\n1 <= beans[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-and-sum-of-array/discuss/1766984/Python3-dp-(top-down)",
      "python_solutions": "class Solution:\n    def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n        \n        @cache\n        def fn(k, m): \n            \"\"\"Return max AND sum.\"\"\"\n            if k == len(nums): return 0 \n            ans = 0 \n            for i in range(numSlots): \n                if m & 1<<2*i == 0 or m & 1<<2*i+1 == 0: \n                    if m & 1<<2*i == 0: mm = m ^ 1<<2*i\n                    else: mm = m ^ 1<<2*i+1\n                    ans = max(ans, (nums[k] & i+1) + fn(k+1, mm))\n            return ans \n        \n        return fn(0, 0)",
      "slug": "maximum-and-sum-of-array",
      "post_title": "[Python3] dp (top-down)",
      "user": "ye15",
      "upvotes": 13,
      "views": 591,
      "problem_title": "maximum and sum of array",
      "number": 2172,
      "acceptance": 0.475,
      "difficulty": "Hard",
      "__index_level_0__": 30149,
      "question": "You are given an integer array nums of length n and an integer numSlots such that 2 * numSlots >= n. There are numSlots slots numbered from 1 to numSlots.\nYou have to place all n integers into the slots such that each slot contains at most two numbers. The AND sum of a given placement is the sum of the bitwise AND of every number with its respective slot number.\nFor example, the AND sum of placing the numbers [1, 3] into slot 1 and [4, 6] into slot 2 is equal to (1 AND 1) + (3 AND 1) + (4 AND 2) + (6 AND 2) = 1 + 1 + 0 + 2 = 4.\nReturn the maximum possible AND sum of nums given numSlots slots.\n  Example 1:\nInput: nums = [1,2,3,4,5,6], numSlots = 3\nOutput: 9\nExplanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. \nThis gives the maximum AND sum of (1 AND 1) + (4 AND 1) + (2 AND 2) + (6 AND 2) + (3 AND 3) + (5 AND 3) = 1 + 0 + 2 + 2 + 3 + 1 = 9.\nExample 2:\nInput: nums = [1,3,10,4,7,1], numSlots = 9\nOutput: 24\nExplanation: One possible placement is [1, 1] into slot 1, [3] into slot 3, [4] into slot 4, [7] into slot 7, and [10] into slot 9.\nThis gives the maximum AND sum of (1 AND 1) + (1 AND 1) + (3 AND 3) + (4 AND 4) + (7 AND 7) + (10 AND 9) = 1 + 1 + 3 + 4 + 7 + 8 = 24.\nNote that slots 2, 5, 6, and 8 are empty which is permitted.\n  Constraints:\nn == nums.length\n1 <= numSlots <= 9\n1 <= n <= 2 * numSlots\n1 <= nums[i] <= 15"
    },
    {
      "post_href": "https://leetcode.com/problems/count-equal-and-divisible-pairs-in-an-array/discuss/1783447/Python3-Solution-fastest",
      "python_solutions": "class Solution:\n    def countPairs(self, nums: List[int], k: int) -> int:\n        n=len(nums)\n        c=0\n        for i in range(0,n):\n            for j in range(i+1,n):\n                if nums[i]==nums[j] and ((i*j)%k==0):\n                    c+=1\n        return c",
      "slug": "count-equal-and-divisible-pairs-in-an-array",
      "post_title": "Python3 Solution fastest",
      "user": "Anilchouhan181",
      "upvotes": 6,
      "views": 812,
      "problem_title": "count equal and divisible pairs in an array",
      "number": 2176,
      "acceptance": 0.8029999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 30151,
      "question": "Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) where 0 <= i < j < n, such that nums[i] == nums[j] and (i * j) is divisible by k.\n  Example 1:\nInput: nums = [3,1,2,2,2,1,3], k = 2\nOutput: 4\nExplanation:\nThere are 4 pairs that meet all the requirements:\n- nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.\n- nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.\n- nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.\n- nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.\nExample 2:\nInput: nums = [1,2,3,4], k = 1\nOutput: 0\nExplanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.\n  Constraints:\n1 <= nums.length <= 100\n1 <= nums[i], k <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/find-three-consecutive-integers-that-sum-to-a-given-number/discuss/1783425/Python3-1-line",
      "python_solutions": "class Solution:\n    def sumOfThree(self, num: int) -> List[int]:\n        return [] if num % 3 else [num//3-1, num//3, num//3+1]",
      "slug": "find-three-consecutive-integers-that-sum-to-a-given-number",
      "post_title": "[Python3] 1-line",
      "user": "ye15",
      "upvotes": 5,
      "views": 258,
      "problem_title": "find three consecutive integers that sum to a given number",
      "number": 2177,
      "acceptance": 0.637,
      "difficulty": "Medium",
      "__index_level_0__": 30184,
      "question": "Given an integer num, return three consecutive integers (as a sorted array) that sum to num. If num cannot be expressed as the sum of three consecutive integers, return an empty array.\n  Example 1:\nInput: num = 33\nOutput: [10,11,12]\nExplanation: 33 can be expressed as 10 + 11 + 12 = 33.\n10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].\nExample 2:\nInput: num = 4\nOutput: []\nExplanation: There is no way to express 4 as the sum of 3 consecutive integers.\n  Constraints:\n0 <= num <= 1015"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-split-of-positive-even-integers/discuss/1783966/Simple-Python-Solution-with-Explanation-oror-O(sqrt(n))-Time-Complexity-oror-O(1)-Space-Complexity",
      "python_solutions": "class Solution:\n    def maximumEvenSplit(self, finalSum: int) -> List[int]:\n        l=set()\n        if finalSum%2!=0:\n            return l\n        else:\n            s=0\n            i=2                       # even pointer 2, 4, 6, 8, 10, 12...........\n            while(s int:\n        n = len(nums1)\n        hashmap2 = {}\n        for i in range(n):\n            hashmap2[nums2[i]] = i\n        indices = []\n        for num in nums1:\n            indices.append(hashmap2[num])\n        from sortedcontainers import SortedList\n        left, right = SortedList(), SortedList()\n        leftCount, rightCount = [], []\n        for i in range(n):\n            leftCount.append(left.bisect_left(indices[i]))\n            left.add(indices[i])\n        for i in range(n - 1, -1, -1):\n            rightCount.append(len(right) - right.bisect_right(indices[i]))\n            right.add(indices[i])\n        count = 0\n        for i in range(n):\n            count += leftCount[i] * rightCount[n - 1 - i]\n        return count",
      "slug": "count-good-triplets-in-an-array",
      "post_title": "Python 3 SortedList solution, O(NlogN)",
      "user": "xil899",
      "upvotes": 13,
      "views": 554,
      "problem_title": "count good triplets in an array",
      "number": 2179,
      "acceptance": 0.371,
      "difficulty": "Hard",
      "__index_level_0__": 30226,
      "question": "You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].\nA good triplet is a set of 3 distinct values which are present in increasing order by position both in nums1 and nums2. In other words, if we consider pos1v as the index of the value v in nums1 and pos2v as the index of the value v in nums2, then a good triplet will be a set (x, y, z) where 0 <= x, y, z <= n - 1, such that pos1x < pos1y < pos1z and pos2x < pos2y < pos2z.\nReturn the total number of good triplets.\n  Example 1:\nInput: nums1 = [2,0,1,3], nums2 = [0,1,2,3]\nOutput: 1\nExplanation: \nThere are 4 triplets (x,y,z) such that pos1x < pos1y < pos1z. They are (2,0,1), (2,0,3), (2,1,3), and (0,1,3). \nOut of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet.\nExample 2:\nInput: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]\nOutput: 4\nExplanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).\n  Constraints:\nn == nums1.length == nums2.length\n3 <= n <= 105\n0 <= nums1[i], nums2[i] <= n - 1\nnums1 and nums2 are permutations of [0, 1, ..., n - 1]."
    },
    {
      "post_href": "https://leetcode.com/problems/count-integers-with-even-digit-sum/discuss/1785049/lessPython3greater-O(1)-Discrete-Formula-100-faster-1-LINE",
      "python_solutions": "class Solution:\n    def countEven(self, num: int) -> int:\n        return num // 2 if sum([int(k) for k in str(num)]) % 2 == 0 else (num - 1) // 2",
      "slug": "count-integers-with-even-digit-sum",
      "post_title": " O(1) - Discrete Formula - 100% faster - 1 LINE",
      "user": "drknzz",
      "upvotes": 9,
      "views": 845,
      "problem_title": "count integers with even digit sum",
      "number": 2180,
      "acceptance": 0.645,
      "difficulty": "Easy",
      "__index_level_0__": 30229,
      "question": "Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.\nThe digit sum of a positive integer is the sum of all its digits.\n  Example 1:\nInput: num = 4\nOutput: 2\nExplanation:\nThe only integers less than or equal to 4 whose digit sums are even are 2 and 4.    \nExample 2:\nInput: num = 30\nOutput: 14\nExplanation:\nThe 14 integers less than or equal to 30 whose digit sums are even are\n2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.\n  Constraints:\n1 <= num <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/merge-nodes-in-between-zeros/discuss/1784873/Python-3-or-Dummy-Node-O(N)-Time-Solution",
      "python_solutions": "class Solution:\n    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        d=ListNode(0)\n        t=0\n        r=ListNode(0,d)\n        while head:\n            if head.val!=0:\n                t+=head.val\n            else:\n                print(t)\n                if t!=0:\n                    d.next=ListNode(t)\n                    d=d.next\n                    t=0\n            head=head.next\n        return r.next.next",
      "slug": "merge-nodes-in-between-zeros",
      "post_title": "Python 3 | Dummy Node O(N) Time Solution",
      "user": "MrShobhit",
      "upvotes": 6,
      "views": 576,
      "problem_title": "merge nodes in between zeros",
      "number": 2181,
      "acceptance": 0.867,
      "difficulty": "Medium",
      "__index_level_0__": 30271,
      "question": "You are given the head of a linked list, which contains a series of integers separated by 0's. The beginning and end of the linked list will have Node.val == 0.\nFor every two consecutive 0's, merge all the nodes lying in between them into a single node whose value is the sum of all the merged nodes. The modified list should not contain any 0's.\nReturn the head of the modified linked list.\n  Example 1:\nInput: head = [0,3,1,0,4,5,2,0]\nOutput: [4,11]\nExplanation: \nThe above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 3 + 1 = 4.\n- The sum of the nodes marked in red: 4 + 5 + 2 = 11.\nExample 2:\nInput: head = [0,1,0,3,0,2,2,0]\nOutput: [1,3,4]\nExplanation: \nThe above figure represents the given linked list. The modified list contains\n- The sum of the nodes marked in green: 1 = 1.\n- The sum of the nodes marked in red: 3 = 3.\n- The sum of the nodes marked in yellow: 2 + 2 = 4.\n  Constraints:\nThe number of nodes in the list is in the range [3, 2 * 105].\n0 <= Node.val <= 1000\nThere are no two consecutive nodes with Node.val == 0.\nThe beginning and end of the linked list have Node.val == 0."
    },
    {
      "post_href": "https://leetcode.com/problems/construct-string-with-repeat-limit/discuss/1784789/Python3-priority-queue",
      "python_solutions": "class Solution:\n    def repeatLimitedString(self, s: str, repeatLimit: int) -> str:\n        pq = [(-ord(k), v) for k, v in Counter(s).items()] \n        heapify(pq)\n        ans = []\n        while pq: \n            k, v = heappop(pq)\n            if ans and ans[-1] == k: \n                if not pq: break \n                kk, vv = heappop(pq)\n                ans.append(kk)\n                if vv-1: heappush(pq, (kk, vv-1))\n                heappush(pq, (k, v))\n            else: \n                m = min(v, repeatLimit)\n                ans.extend([k]*m)\n                if v-m: heappush(pq, (k, v-m))\n        return \"\".join(chr(-x) for x in ans)",
      "slug": "construct-string-with-repeat-limit",
      "post_title": "[Python3] priority queue",
      "user": "ye15",
      "upvotes": 23,
      "views": 1100,
      "problem_title": "construct string with repeat limit",
      "number": 2182,
      "acceptance": 0.519,
      "difficulty": "Medium",
      "__index_level_0__": 30294,
      "question": "You are given a string s and an integer repeatLimit. Construct a new string repeatLimitedString using the characters of s such that no letter appears more than repeatLimit times in a row. You do not have to use all characters from s.\nReturn the lexicographically largest repeatLimitedString possible.\nA string a is lexicographically larger than a string b if in the first position where a and b differ, string a has a letter that appears later in the alphabet than the corresponding letter in b. If the first min(a.length, b.length) characters do not differ, then the longer string is the lexicographically larger one.\n  Example 1:\nInput: s = \"cczazcc\", repeatLimit = 3\nOutput: \"zzcccac\"\nExplanation: We use all of the characters from s to construct the repeatLimitedString \"zzcccac\".\nThe letter 'a' appears at most 1 time in a row.\nThe letter 'c' appears at most 3 times in a row.\nThe letter 'z' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"zzcccac\".\nNote that the string \"zzcccca\" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.\nExample 2:\nInput: s = \"aababab\", repeatLimit = 2\nOutput: \"bbabaa\"\nExplanation: We use only some of the characters from s to construct the repeatLimitedString \"bbabaa\". \nThe letter 'a' appears at most 2 times in a row.\nThe letter 'b' appears at most 2 times in a row.\nHence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\nThe string is the lexicographically largest repeatLimitedString possible so we return \"bbabaa\".\nNote that the string \"bbabaaa\" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.\n  Constraints:\n1 <= repeatLimit <= s.length <= 105\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/count-array-pairs-divisible-by-k/discuss/1784801/Python3-factors",
      "python_solutions": "class Solution:\n    def coutPairs(self, nums: List[int], k: int) -> int:\n        factors = []\n        for x in range(1, int(sqrt(k))+1):\n            if k % x == 0: factors.append(x)\n        ans = 0 \n        freq = Counter()\n        for x in nums: \n            x = gcd(x, k)\n            ans += freq[k//x]\n            for f in factors: \n                if x % f == 0 and f <= x//f: \n                    freq[f] += 1\n                    if f < x//f: freq[x//f] += 1\n        return ans",
      "slug": "count-array-pairs-divisible-by-k",
      "post_title": "[Python3] factors",
      "user": "ye15",
      "upvotes": 6,
      "views": 661,
      "problem_title": "count array pairs divisible by k",
      "number": 2183,
      "acceptance": 0.287,
      "difficulty": "Hard",
      "__index_level_0__": 30301,
      "question": "Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:\n0 <= i < j <= n - 1 and\nnums[i] * nums[j] is divisible by k.\n  Example 1:\nInput: nums = [1,2,3,4,5], k = 2\nOutput: 7\nExplanation: \nThe 7 pairs of indices whose corresponding products are divisible by 2 are\n(0, 1), (0, 3), (1, 2), (1, 3), (1, 4), (2, 3), and (3, 4).\nTheir products are 2, 4, 6, 8, 10, 12, and 20 respectively.\nOther pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.    \nExample 2:\nInput: nums = [1,2,3,4], k = 5\nOutput: 0\nExplanation: There does not exist any pair of indices whose corresponding product is divisible by 5.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i], k <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/counting-words-with-a-given-prefix/discuss/1803163/Python-1-Liner-Solution",
      "python_solutions": "class Solution:\n    def prefixCount(self, words: List[str], pref: str) -> int:\n        return sum(word.find(pref) == 0 for word in words)",
      "slug": "counting-words-with-a-given-prefix",
      "post_title": "Python 1 Liner Solution",
      "user": "anCoderr",
      "upvotes": 3,
      "views": 210,
      "problem_title": "counting words with a given prefix",
      "number": 2185,
      "acceptance": 0.7709999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 30305,
      "question": "You are given an array of strings words and a string pref.\nReturn the number of strings in words that contain pref as a prefix.\nA prefix of a string s is any leading contiguous substring of s.\n  Example 1:\nInput: words = [\"pay\",\"attention\",\"practice\",\"attend\"], pref = \"at\"\nOutput: 2\nExplanation: The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".\nExample 2:\nInput: words = [\"leetcode\",\"win\",\"loops\",\"success\"], pref = \"code\"\nOutput: 0\nExplanation: There are no strings that contain \"code\" as a prefix.\n  Constraints:\n1 <= words.length <= 100\n1 <= words[i].length, pref.length <= 100\nwords[i] and pref consist of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram-ii/discuss/1802652/Python3-freq-table",
      "python_solutions": "class Solution:\n    def minSteps(self, s: str, t: str) -> int:\n        fs, ft = Counter(s), Counter(t)\n        return sum((fs-ft).values()) + sum((ft-fs).values())",
      "slug": "minimum-number-of-steps-to-make-two-strings-anagram-ii",
      "post_title": "[Python3] freq table",
      "user": "ye15",
      "upvotes": 6,
      "views": 307,
      "problem_title": "minimum number of steps to make two strings anagram ii",
      "number": 2186,
      "acceptance": 0.7190000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 30354,
      "question": "You are given two strings s and t. In one step, you can append any character to either s or t.\nReturn the minimum number of steps to make s and t anagrams of each other.\nAn anagram of a string is a string that contains the same characters with a different (or the same) ordering.\n  Example 1:\nInput: s = \"leetcode\", t = \"coats\"\nOutput: 7\nExplanation: \n- In 2 steps, we can append the letters in \"as\" onto s = \"leetcode\", forming s = \"leetcodeas\".\n- In 5 steps, we can append the letters in \"leede\" onto t = \"coats\", forming t = \"coatsleede\".\n\"leetcodeas\" and \"coatsleede\" are now anagrams of each other.\nWe used a total of 2 + 5 = 7 steps.\nIt can be shown that there is no way to make them anagrams of each other with less than 7 steps.\nExample 2:\nInput: s = \"night\", t = \"thing\"\nOutput: 0\nExplanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.\n  Constraints:\n1 <= s.length, t.length <= 2 * 105\ns and t consist of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-time-to-complete-trips/discuss/1802433/Python-Solution-oror-Detailed-Article-on-Binary-Search-on-Answer",
      "python_solutions": "class Solution:\n    def minimumTime(self, time: List[int], totalTrips: int) -> int:\n        r = min(time) * totalTrips + 1 # This is the worst case answer possible for any case. Could use big values like 10^15 as well but they might slow the time down for smaller cases.\n        l = 0\n        ans = 0\n\n        def check_status(expected_time: int) -> int:\n            nonlocal ans\n            count = 0\n            for i in time:\n                count += expected_time // i # Total trips with time expected_time should be integer part of expected_time // i\n            if count < totalTrips:\n                return 1 # Since number of trips are less then required, left moves to mid\n            elif count >= totalTrips:\n                ans = expected_time # stores the latest result. This is guaranteed to be the minimum possible answer.\n                return -1 # Since number of trips are greater/equal to required, right moves to mid\n\n        while l < r-1: # Till Binary Search can continue. \n            mid = (l + r) // 2 # mid is the current expected time.\n            status = check_status(mid) # The return values 1/-1 in check_status function determines which pointer to move.\n            if status == 1:\n                l = mid\n            else:\n                r = mid\n                \n        return ans",
      "slug": "minimum-time-to-complete-trips",
      "post_title": "\u2705 Python Solution || Detailed Article on Binary Search on Answer",
      "user": "anCoderr",
      "upvotes": 12,
      "views": 694,
      "problem_title": "minimum time to complete trips",
      "number": 2187,
      "acceptance": 0.32,
      "difficulty": "Medium",
      "__index_level_0__": 30378,
      "question": "You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.\nEach bus can make multiple trips successively; that is, the next trip can start immediately after completing the current trip. Also, each bus operates independently; that is, the trips of one bus do not influence the trips of any other bus.\nYou are also given an integer totalTrips, which denotes the number of trips all buses should make in total. Return the minimum time required for all buses to complete at least totalTrips trips.\n  Example 1:\nInput: time = [1,2,3], totalTrips = 5\nOutput: 3\nExplanation:\n- At time t = 1, the number of trips completed by each bus are [1,0,0]. \n  The total number of trips completed is 1 + 0 + 0 = 1.\n- At time t = 2, the number of trips completed by each bus are [2,1,0]. \n  The total number of trips completed is 2 + 1 + 0 = 3.\n- At time t = 3, the number of trips completed by each bus are [3,1,1]. \n  The total number of trips completed is 3 + 1 + 1 = 5.\nSo the minimum time needed for all buses to complete at least 5 trips is 3.\nExample 2:\nInput: time = [2], totalTrips = 1\nOutput: 2\nExplanation:\nThere is only one bus, and it will complete its first trip at t = 2.\nSo the minimum time needed to complete 1 trip is 2.\n  Constraints:\n1 <= time.length <= 105\n1 <= time[i], totalTrips <= 107"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-time-to-finish-the-race/discuss/1803014/Python-DP-with-pre-treatment-to-reduce-time-complexity",
      "python_solutions": "class Solution:\n    def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n        tires.sort()\n        newTires = []\n        minTime = [changeTime*(i-1) + tires[0][0]*i for i in range(numLaps+1)]\n        minTime[0] = 0\n        maxi = 0\n        for f,r in tires:\n            if not newTires or f>newTires[-1][0] and rt:\n                        minTime[i]=t\n                        maxi = max(i,maxi)\n        for lap in range(numLaps+1):\n            for run in range(min(lap,maxi+1)):\n                minTime[lap] = min(minTime[lap],minTime[lap-run]+changeTime+minTime[run])\n        return minTime[numLaps]",
      "slug": "minimum-time-to-finish-the-race",
      "post_title": "[Python] DP with pre-treatment to reduce time complexity",
      "user": "wssx349",
      "upvotes": 3,
      "views": 226,
      "problem_title": "minimum time to finish the race",
      "number": 2188,
      "acceptance": 0.419,
      "difficulty": "Hard",
      "__index_level_0__": 30404,
      "question": "You are given a 0-indexed 2D integer array tires where tires[i] = [fi, ri] indicates that the ith tire can finish its xth successive lap in fi * ri(x-1) seconds.\nFor example, if fi = 3 and ri = 2, then the tire would finish its 1st lap in 3 seconds, its 2nd lap in 3 * 2 = 6 seconds, its 3rd lap in 3 * 22 = 12 seconds, etc.\nYou are also given an integer changeTime and an integer numLaps.\nThe race consists of numLaps laps and you may start the race with any tire. You have an unlimited supply of each tire and after every lap, you may change to any given tire (including the current tire type) if you wait changeTime seconds.\nReturn the minimum time to finish the race.\n  Example 1:\nInput: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4\nOutput: 21\nExplanation: \nLap 1: Start with tire 0 and finish the lap in 2 seconds.\nLap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nLap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\nTotal time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\nThe minimum time to complete the race is 21 seconds.\nExample 2:\nInput: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5\nOutput: 25\nExplanation: \nLap 1: Start with tire 1 and finish the lap in 2 seconds.\nLap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\nLap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\nLap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\nTotal time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\nThe minimum time to complete the race is 25 seconds. \n  Constraints:\n1 <= tires.length <= 105\ntires[i].length == 2\n1 <= fi, changeTime <= 105\n2 <= ri <= 105\n1 <= numLaps <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/most-frequent-number-following-key-in-an-array/discuss/1924231/Python-Multiple-Solutions-%2B-One-Liners-or-Clean-and-Simple",
      "python_solutions": "class Solution:\n    def mostFrequent(self, nums, key):\n        counts = {}\n        \n        for i in range(1,len(nums)):\n            if nums[i-1]==key:\n                if nums[i] not in counts: counts[nums[i]] = 1\n                else: counts[nums[i]] += 1\n        \n        return max(counts, key=counts.get)",
      "slug": "most-frequent-number-following-key-in-an-array",
      "post_title": "Python - Multiple Solutions + One-Liners | Clean and Simple",
      "user": "domthedeveloper",
      "upvotes": 4,
      "views": 214,
      "problem_title": "most frequent number following key in an array",
      "number": 2190,
      "acceptance": 0.605,
      "difficulty": "Easy",
      "__index_level_0__": 30408,
      "question": "You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.\nFor every unique integer target in nums, count the number of times target immediately follows an occurrence of key in nums. In other words, count the number of indices i such that:\n0 <= i <= nums.length - 2,\nnums[i] == key and,\nnums[i + 1] == target.\nReturn the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.\n  Example 1:\nInput: nums = [1,100,200,1,100], key = 1\nOutput: 100\nExplanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\nNo other integers follow an occurrence of key, so we return 100.\nExample 2:\nInput: nums = [2,2,2,2,3], key = 2\nOutput: 2\nExplanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\nFor target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\ntarget = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.\n  Constraints:\n2 <= nums.length <= 1000\n1 <= nums[i] <= 1000\nThe test cases will be generated such that the answer is unique."
    },
    {
      "post_href": "https://leetcode.com/problems/sort-the-jumbled-numbers/discuss/1822244/Sorted-Lambda",
      "python_solutions": "class Solution:\n    def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n        @cache\n        def convert(i: int):\n            res, pow10 = 0, 1\n            while i:\n                res += pow10 * mapping[i % 10]\n                i //= 10\n                pow10 *= 10\n            return res\n        return sorted(nums, key=lambda i: mapping[i] if i < 10 else convert(i))",
      "slug": "sort-the-jumbled-numbers",
      "post_title": "Sorted Lambda",
      "user": "votrubac",
      "upvotes": 8,
      "views": 869,
      "problem_title": "sort the jumbled numbers",
      "number": 2191,
      "acceptance": 0.4529999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 30436,
      "question": "You are given a 0-indexed integer array mapping which represents the mapping rule of a shuffled decimal system. mapping[i] = j means digit i should be mapped to digit j in this system.\nThe mapped value of an integer is the new integer obtained by replacing each occurrence of digit i in the integer with mapping[i] for all 0 <= i <= 9.\nYou are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements.\nNotes:\nElements with the same mapped values should appear in the same relative order as in the input.\nThe elements of nums should only be sorted based on their mapped values and not be replaced by them.\n  Example 1:\nInput: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]\nOutput: [338,38,991]\nExplanation: \nMap the number 991 as follows:\n1. mapping[9] = 6, so all occurrences of the digit 9 will become 6.\n2. mapping[1] = 9, so all occurrences of the digit 1 will become 9.\nTherefore, the mapped value of 991 is 669.\n338 maps to 007, or 7 after removing the leading zeros.\n38 maps to 07, which is also 7 after removing leading zeros.\nSince 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.\nThus, the sorted array is [338,38,991].\nExample 2:\nInput: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]\nOutput: [123,456,789]\nExplanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].\n  Constraints:\nmapping.length == 10\n0 <= mapping[i] <= 9\nAll the values of mapping[i] are unique.\n1 <= nums.length <= 3 * 104\n0 <= nums[i] < 109"
    },
    {
      "post_href": "https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/2333862/Python3-or-Solved-using-Topo-Sort(Kahn-Algo)-with-Queue(BFS)",
      "python_solutions": "class Solution:\n    def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n        #Use Kahn's algorithm of toposort using a queue and bfs!\n        graph = [[] for _ in range(n)]\n        indegrees = [0] * n\n        \n        #Time: O(n^2)\n        #Space: O(n^2 + n + n) -> O(n^2)\n        \n        #1st step: build adjacency list grpah and update the initial indegrees of every node!\n        for edge in edges:\n            src, dest = edge[0], edge[1]\n            graph[src].append(dest)\n            indegrees[dest] += 1\n        \n        \n        queue = deque()\n        ans = [set() for _ in range(n)]\n        #2nd step: go through the indegrees array and add to queue for any node that has no ancestor!\n        for i in range(len(indegrees)):\n            if(indegrees[i] == 0):\n                queue.append(i)\n        \n        #Kahn's algorithm initiation!\n        #while loop will run for each and every node in graph!\n        #in worst case, adjacency list for one particular node may contain all other vertices!\n        while queue:\n            cur = queue.pop()\n            \n            #for each neighbor\n            for neighbor in graph[cur]:\n                #current node is ancestor to each and every neighboring node!\n                ans[neighbor].add(cur)\n                #every ancestor of current node is also an ancestor to the neighboring node!\n                ans[neighbor].update(ans[cur])\n                indegrees[neighbor] -= 1\n                if(indegrees[neighbor] == 0):\n                    queue.append(neighbor)\n        \n        #at the end, we should have set of ancestors for each and every node!\n        #in worst case, set s for ith node could have all other vertices be ancestor to node i !\n        ans = [(sorted(list(s))) for s in ans]\n        return ans",
      "slug": "all-ancestors-of-a-node-in-a-directed-acyclic-graph",
      "post_title": "Python3 | Solved using Topo Sort(Kahn Algo) with Queue(BFS)",
      "user": "JOON1234",
      "upvotes": 4,
      "views": 169,
      "problem_title": "all ancestors of a node in a directed acyclic graph",
      "number": 2192,
      "acceptance": 0.503,
      "difficulty": "Medium",
      "__index_level_0__": 30448,
      "question": "You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).\nYou are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph.\nReturn a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order.\nA node u is an ancestor of another node v if u can reach v via a set of edges.\n  Example 1:\nInput: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]\nOutput: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]\nExplanation:\nThe above diagram represents the input graph.\n- Nodes 0, 1, and 2 do not have any ancestors.\n- Node 3 has two ancestors 0 and 1.\n- Node 4 has two ancestors 0 and 2.\n- Node 5 has three ancestors 0, 1, and 3.\n- Node 6 has five ancestors 0, 1, 2, 3, and 4.\n- Node 7 has four ancestors 0, 1, 2, and 3.\nExample 2:\nInput: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\nOutput: [[],[0],[0,1],[0,1,2],[0,1,2,3]]\nExplanation:\nThe above diagram represents the input graph.\n- Node 0 does not have any ancestor.\n- Node 1 has one ancestor 0.\n- Node 2 has two ancestors 0 and 1.\n- Node 3 has three ancestors 0, 1, and 2.\n- Node 4 has four ancestors 0, 1, 2, and 3.\n  Constraints:\n1 <= n <= 1000\n0 <= edges.length <= min(2000, n * (n - 1) / 2)\nedges[i].length == 2\n0 <= fromi, toi <= n - 1\nfromi != toi\nThere are no duplicate edges.\nThe graph is directed and acyclic."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-number-of-moves-to-make-palindrome/discuss/2152484/Python3-peel-the-string",
      "python_solutions": "class Solution:\n    def minMovesToMakePalindrome(self, s: str) -> int:\n        ans = 0 \n        while len(s) > 2: \n            lo = s.find(s[-1])\n            hi = s.rfind(s[0])\n            if lo < len(s)-hi-1: \n                ans += lo \n                s = s[:lo] + s[lo+1:-1]\n            else: \n                ans += len(s)-hi-1\n                s = s[1:hi] + s[hi+1:]\n        return ans",
      "slug": "minimum-number-of-moves-to-make-palindrome",
      "post_title": "[Python3] peel the string",
      "user": "ye15",
      "upvotes": 1,
      "views": 614,
      "problem_title": "minimum number of moves to make palindrome",
      "number": 2193,
      "acceptance": 0.514,
      "difficulty": "Hard",
      "__index_level_0__": 30460,
      "question": "You are given a string s consisting only of lowercase English letters.\nIn one move, you can select any two adjacent characters of s and swap them.\nReturn the minimum number of moves needed to make s a palindrome.\nNote that the input will be generated such that s can always be converted to a palindrome.\n  Example 1:\nInput: s = \"aabb\"\nOutput: 2\nExplanation:\nWe can obtain two palindromes from s, \"abba\" and \"baab\". \n- We can obtain \"abba\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"abba\".\n- We can obtain \"baab\" from s in 2 moves: \"aabb\" -> \"abab\" -> \"baab\".\nThus, the minimum number of moves needed to make s a palindrome is 2.\nExample 2:\nInput: s = \"letelt\"\nOutput: 2\nExplanation:\nOne of the palindromes we can obtain from s in 2 moves is \"lettel\".\nOne of the ways we can obtain it is \"letelt\" -> \"letetl\" -> \"lettel\".\nOther palindromes such as \"tleelt\" can also be obtained in 2 moves.\nIt can be shown that it is not possible to obtain a palindrome in less than 2 moves.\n  Constraints:\n1 <= s.length <= 2000\ns consists only of lowercase English letters.\ns can be converted to a palindrome using a finite number of moves."
    },
    {
      "post_href": "https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet/discuss/1823607/Python3-1-line",
      "python_solutions": "class Solution:\n    def cellsInRange(self, s: str) -> List[str]:\n        return [chr(c)+str(r) for c in range(ord(s[0]), ord(s[3])+1) for r in range(int(s[1]), int(s[4])+1)]",
      "slug": "cells-in-a-range-on-an-excel-sheet",
      "post_title": "[Python3] 1-line",
      "user": "ye15",
      "upvotes": 7,
      "views": 368,
      "problem_title": "cells in a range on an excel sheet",
      "number": 2194,
      "acceptance": 0.856,
      "difficulty": "Easy",
      "__index_level_0__": 30466,
      "question": "A cell (r, c) of an excel sheet is represented as a string \"\" where:\n denotes the column number c of the cell. It is represented by alphabetical letters.\nFor example, the 1st column is denoted by 'A', the 2nd by 'B', the 3rd by 'C', and so on.\n is the row number r of the cell. The rth row is represented by the integer r.\nYou are given a string s in the format \":\", where  represents the column c1,  represents the row r1,  represents the column c2, and  represents the row r2, such that r1 <= r2 and c1 <= c2.\nReturn the list of cells (x, y) such that r1 <= x <= r2 and c1 <= y <= c2. The cells should be represented as strings in the format mentioned above and be sorted in non-decreasing order first by columns and then by rows.\n  Example 1:\nInput: s = \"K1:L2\"\nOutput: [\"K1\",\"K2\",\"L1\",\"L2\"]\nExplanation:\nThe above diagram shows the cells which should be present in the list.\nThe red arrows denote the order in which the cells should be presented.\nExample 2:\nInput: s = \"A1:F1\"\nOutput: [\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]\nExplanation:\nThe above diagram shows the cells which should be present in the list.\nThe red arrow denotes the order in which the cells should be presented.\n  Constraints:\ns.length == 5\n'A' <= s[0] <= s[3] <= 'Z'\n'1' <= s[1] <= s[4] <= '9'\ns consists of uppercase English letters, digits and ':'."
    },
    {
      "post_href": "https://leetcode.com/problems/append-k-integers-with-minimal-sum/discuss/1823628/Python3-swap",
      "python_solutions": "class Solution:\n    def minimalKSum(self, nums: List[int], k: int) -> int:\n        ans = k*(k+1)//2\n        prev = -inf \n        for x in sorted(nums): \n            if prev < x: \n                if x <= k: \n                    k += 1\n                    ans += k - x\n                else: break\n                prev = x\n        return ans",
      "slug": "append-k-integers-with-minimal-sum",
      "post_title": "[Python3] swap",
      "user": "ye15",
      "upvotes": 10,
      "views": 495,
      "problem_title": "append k integers with minimal sum",
      "number": 2195,
      "acceptance": 0.25,
      "difficulty": "Medium",
      "__index_level_0__": 30497,
      "question": "You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum.\nReturn the sum of the k integers appended to nums.\n  Example 1:\nInput: nums = [1,4,25,10,25], k = 2\nOutput: 5\nExplanation: The two unique positive integers that do not appear in nums which we append are 2 and 3.\nThe resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\nThe sum of the two integers appended is 2 + 3 = 5, so we return 5.\nExample 2:\nInput: nums = [5,6], k = 6\nOutput: 25\nExplanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\nThe resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \nThe sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109\n1 <= k <= 108"
    },
    {
      "post_href": "https://leetcode.com/problems/create-binary-tree-from-descriptions/discuss/1823644/Python3-simulation",
      "python_solutions": "class Solution:\n    def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n        mp = {}\n        seen = set()\n        for p, c, left in descriptions: \n            if p not in mp: mp[p] = TreeNode(p)\n            if c not in mp: mp[c] = TreeNode(c)\n            if left: mp[p].left = mp[c]\n            else: mp[p].right = mp[c]\n            seen.add(c)\n        for p, _, _ in descriptions: \n            if p not in seen: return mp[p]",
      "slug": "create-binary-tree-from-descriptions",
      "post_title": "[Python3] simulation",
      "user": "ye15",
      "upvotes": 8,
      "views": 191,
      "problem_title": "create binary tree from descriptions",
      "number": 2196,
      "acceptance": 0.722,
      "difficulty": "Medium",
      "__index_level_0__": 30515,
      "question": "You are given a 2D integer array descriptions where descriptions[i] = [parenti, childi, isLefti] indicates that parenti is the parent of childi in a binary tree of unique values. Furthermore,\nIf isLefti == 1, then childi is the left child of parenti.\nIf isLefti == 0, then childi is the right child of parenti.\nConstruct the binary tree described by descriptions and return its root.\nThe test cases will be generated such that the binary tree is valid.\n  Example 1:\nInput: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\nOutput: [50,20,80,15,17,19]\nExplanation: The root node is the node with value 50 since it has no parent.\nThe resulting binary tree is shown in the diagram.\nExample 2:\nInput: descriptions = [[1,2,1],[2,3,0],[3,4,1]]\nOutput: [1,2,null,null,3,4]\nExplanation: The root node is the node with value 1 since it has no parent.\nThe resulting binary tree is shown in the diagram.\n  Constraints:\n1 <= descriptions.length <= 104\ndescriptions[i].length == 3\n1 <= parenti, childi <= 105\n0 <= isLefti <= 1\nThe binary tree described by descriptions is valid."
    },
    {
      "post_href": "https://leetcode.com/problems/replace-non-coprime-numbers-in-array/discuss/1825538/Python-3-Stack-solution",
      "python_solutions": "class Solution:\n    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:       \n\n        stack = nums[:1]\n        \n        for j in range(1, len(nums)):\n            cur = nums[j]\n            while stack and math.gcd(stack[-1], cur) > 1:\n                prev = stack.pop()\n                cur = math.lcm(prev, cur)\n            stack.append(cur)            \n               \n        return stack",
      "slug": "replace-non-coprime-numbers-in-array",
      "post_title": "[Python 3] Stack solution",
      "user": "chestnut890123",
      "upvotes": 2,
      "views": 125,
      "problem_title": "replace non coprime numbers in array",
      "number": 2197,
      "acceptance": 0.387,
      "difficulty": "Hard",
      "__index_level_0__": 30531,
      "question": "You are given an array of integers nums. Perform the following steps:\nFind any two adjacent numbers in nums that are non-coprime.\nIf no such numbers are found, stop the process.\nOtherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).\nRepeat this process as long as you keep finding two adjacent non-coprime numbers.\nReturn the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.\nThe test cases are generated such that the values in the final array are less than or equal to 108.\nTwo values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.\n  Example 1:\nInput: nums = [6,4,3,2,7,6,2]\nOutput: [12,7,6]\nExplanation: \n- (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].\n- (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].\n- (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].\n- (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [12,7,6].\nNote that there are other ways to obtain the same resultant array.\nExample 2:\nInput: nums = [2,2,1,1,3,3,3]\nOutput: [2,1,1,3]\nExplanation: \n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].\n- (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].\n- (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].\nThere are no more adjacent non-coprime numbers in nums.\nThus, the final modified array is [2,1,1,3].\nNote that there are other ways to obtain the same resultant array.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 105\nThe test cases are generated such that the values in the final array are less than or equal to 108."
    },
    {
      "post_href": "https://leetcode.com/problems/find-all-k-distant-indices-in-an-array/discuss/2171271/Python-easy-to-understand-oror-Beginner-friendly",
      "python_solutions": "class Solution:\n    def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n        ind_j = []\n        for ind, elem in enumerate(nums):\n            if elem == key:\n                ind_j.append(ind)\n        res = []\n        for i in range(len(nums)):\n            for j in ind_j:\n                if abs(i - j) <= k:\n                    res.append(i)\n                    break\n        return sorted(res)",
      "slug": "find-all-k-distant-indices-in-an-array",
      "post_title": "\u2705Python easy to understand || Beginner friendly",
      "user": "Shivam_Raj_Sharma",
      "upvotes": 4,
      "views": 147,
      "problem_title": "find all k distant indices in an array",
      "number": 2200,
      "acceptance": 0.6459999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 30538,
      "question": "You are given a 0-indexed integer array nums and two integers key and k. A k-distant index is an index i of nums for which there exists at least one index j such that |i - j| <= k and nums[j] == key.\nReturn a list of all k-distant indices sorted in increasing order.\n  Example 1:\nInput: nums = [3,4,9,1,3,9,5], key = 9, k = 1\nOutput: [1,2,3,4,5,6]\nExplanation: Here, nums[2] == key and nums[5] == key.\n- For index 0, |0 - 2| > k and |0 - 5| > k, so there is no j where |0 - j| <= k and nums[j] == key. Thus, 0 is not a k-distant index.\n- For index 1, |1 - 2| <= k and nums[2] == key, so 1 is a k-distant index.\n- For index 2, |2 - 2| <= k and nums[2] == key, so 2 is a k-distant index.\n- For index 3, |3 - 2| <= k and nums[2] == key, so 3 is a k-distant index.\n- For index 4, |4 - 5| <= k and nums[5] == key, so 4 is a k-distant index.\n- For index 5, |5 - 5| <= k and nums[5] == key, so 5 is a k-distant index.\n- For index 6, |6 - 5| <= k and nums[5] == key, so 6 is a k-distant index.\nThus, we return [1,2,3,4,5,6] which is sorted in increasing order. \nExample 2:\nInput: nums = [2,2,2,2,2], key = 2, k = 2\nOutput: [0,1,2,3,4]\nExplanation: For all indices i in nums, there exists some index j such that |i - j| <= k and nums[j] == key, so every index is a k-distant index. \nHence, we return [0,1,2,3,4].\n  Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 1000\nkey is an integer from the array nums.\n1 <= k <= nums.length"
    },
    {
      "post_href": "https://leetcode.com/problems/count-artifacts-that-can-be-extracted/discuss/1844361/Python-elegant-short-and-simple-to-understand-with-explanations",
      "python_solutions": "class Solution:\n    def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:\n\t    # Time: O(max(artifacts, dig)) which is O(N^2) as every position in the grid can be in dig\n\t\t# Space: O(dig) which is O(N^2)\n        result, dig_pos = 0, set(tuple(pos) for pos in dig)\n        for pos in artifacts:\n            if all((x, y) in dig_pos for x in range(pos[0], pos[2] + 1) for y in range(pos[1], pos[3] + 1)):     \n                result += 1\n        return result",
      "slug": "count-artifacts-that-can-be-extracted",
      "post_title": "\ud83d\udcaf Python elegant, short and simple to understand with explanations",
      "user": "yangshun",
      "upvotes": 6,
      "views": 352,
      "problem_title": "count artifacts that can be extracted",
      "number": 2201,
      "acceptance": 0.551,
      "difficulty": "Medium",
      "__index_level_0__": 30559,
      "question": "There is an n x n 0-indexed grid with some artifacts buried in it. You are given the integer n and a 0-indexed 2D integer array artifacts describing the positions of the rectangular artifacts where artifacts[i] = [r1i, c1i, r2i, c2i] denotes that the ith artifact is buried in the subgrid where:\n(r1i, c1i) is the coordinate of the top-left cell of the ith artifact and\n(r2i, c2i) is the coordinate of the bottom-right cell of the ith artifact.\nYou will excavate some cells of the grid and remove all the mud from them. If the cell has a part of an artifact buried underneath, it will be uncovered. If all the parts of an artifact are uncovered, you can extract it.\nGiven a 0-indexed 2D integer array dig where dig[i] = [ri, ci] indicates that you will excavate the cell (ri, ci), return the number of artifacts that you can extract.\nThe test cases are generated such that:\nNo two artifacts overlap.\nEach artifact only covers at most 4 cells.\nThe entries of dig are unique.\n  Example 1:\nInput: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]]\nOutput: 1\nExplanation: \nThe different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.\nThere is 1 artifact that can be extracted, namely the red artifact.\nThe blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.\nThus, we return 1.\nExample 2:\nInput: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]]\nOutput: 2\nExplanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2. \n  Constraints:\n1 <= n <= 1000\n1 <= artifacts.length, dig.length <= min(n2, 105)\nartifacts[i].length == 4\ndig[i].length == 2\n0 <= r1i, c1i, r2i, c2i, ri, ci <= n - 1\nr1i <= r2i\nc1i <= c2i\nNo two artifacts will overlap.\nThe number of cells covered by an artifact is at most 4.\nThe entries of dig are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/maximize-the-topmost-element-after-k-moves/discuss/1844186/Python-3-Find-Maximum-of-first-k-1-elements-or-(k%2B1)th-element-or-Beats-100",
      "python_solutions": "class Solution:\n    def maximumTop(self, nums: List[int], k: int) -> int:\n        if len(nums) == 1:\n            if k%2 != 0:\n                return -1\n            return nums[0]\n        \n        if k == 0:\n            return nums[0]\n        if k == len(nums):\n            return max(nums[:-1])\n        if k > len(nums):\n            return max(nums)\n        if k == 1:\n            return nums[1]\n        m = max(nums[:k-1])\n        m = max(m, nums[k])\n        return m",
      "slug": "maximize-the-topmost-element-after-k-moves",
      "post_title": "[Python 3] Find Maximum of first k-1 elements or (k+1)th element | Beats 100%",
      "user": "hari19041",
      "upvotes": 9,
      "views": 369,
      "problem_title": "maximize the topmost element after k moves",
      "number": 2202,
      "acceptance": 0.228,
      "difficulty": "Medium",
      "__index_level_0__": 30568,
      "question": "You are given a 0-indexed integer array nums representing the contents of a pile, where nums[0] is the topmost element of the pile.\nIn one move, you can perform either of the following:\nIf the pile is not empty, remove the topmost element of the pile.\nIf there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.\nYou are also given an integer k, which denotes the total number of moves to be made.\nReturn the maximum value of the topmost element of the pile possible after exactly k moves. In case it is not possible to obtain a non-empty pile after k moves, return -1.\n  Example 1:\nInput: nums = [5,2,2,4,0,6], k = 4\nOutput: 5\nExplanation:\nOne of the ways we can end with 5 at the top of the pile after 4 moves is as follows:\n- Step 1: Remove the topmost element = 5. The pile becomes [2,2,4,0,6].\n- Step 2: Remove the topmost element = 2. The pile becomes [2,4,0,6].\n- Step 3: Remove the topmost element = 2. The pile becomes [4,0,6].\n- Step 4: Add 5 back onto the pile. The pile becomes [5,4,0,6].\nNote that this is not the only way to end with 5 at the top of the pile. It can be shown that 5 is the largest answer possible after 4 moves.\nExample 2:\nInput: nums = [2], k = 1\nOutput: -1\nExplanation: \nIn the first move, our only option is to pop the topmost element of the pile.\nSince it is not possible to obtain a non-empty pile after one move, we return -1.\n  Constraints:\n1 <= nums.length <= 105\n0 <= nums[i], k <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-weighted-subgraph-with-the-required-paths/discuss/1867689/Three-min-costs-to-every-node-97-speed",
      "python_solutions": "class Solution:\n    def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:\n        forward, backward = dict(), dict()\n        for start, end, weight in edges:\n            if start in forward:\n                if end in forward[start]:\n                    forward[start][end] = min(weight, forward[start][end])\n                else:\n                    forward[start][end] = weight\n            else:\n                forward[start] = {end: weight}\n            if end in backward:\n                if start in backward[end]:\n                    backward[end][start] = min(weight, backward[end][start])\n                else:\n                    backward[end][start] = weight\n            else:\n                backward[end] = {start: weight}\n\n        def travel(origin: int, relations: dict, costs: list) -> None:\n            level = {origin}\n            costs[origin] = 0\n            while level:\n                new_level = set()\n                for node in level:\n                    if node in relations:\n                        for next_node, w in relations[node].items():\n                            if w + costs[node] < costs[next_node]:\n                                new_level.add(next_node)\n                                costs[next_node] = w + costs[node]\n                level = new_level\n\n        from_src1 = [inf] * n\n        from_src2 = [inf] * n\n        from_dest = [inf] * n\n\n        travel(src1, forward, from_src1)\n        travel(src2, forward, from_src2)\n        travel(dest, backward, from_dest)\n\n        combined_cost = min(sum(tpl)\n                            for tpl in zip(from_src1, from_src2, from_dest))\n\n        return combined_cost if combined_cost < inf else -1",
      "slug": "minimum-weighted-subgraph-with-the-required-paths",
      "post_title": "Three min costs to every node, 97% speed",
      "user": "EvgenySH",
      "upvotes": 1,
      "views": 144,
      "problem_title": "minimum weighted subgraph with the required paths",
      "number": 2203,
      "acceptance": 0.357,
      "difficulty": "Hard",
      "__index_level_0__": 30577,
      "question": "You are given an integer n denoting the number of nodes of a weighted directed graph. The nodes are numbered from 0 to n - 1.\nYou are also given a 2D integer array edges where edges[i] = [fromi, toi, weighti] denotes that there exists a directed edge from fromi to toi with weight weighti.\nLastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph.\nReturn the minimum weight of a subgraph of the graph such that it is possible to reach dest from both src1 and src2 via a set of edges of this subgraph. In case such a subgraph does not exist, return -1.\nA subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.\n  Example 1:\nInput: n = 6, edges = [[0,2,2],[0,5,6],[1,0,3],[1,4,5],[2,1,1],[2,3,3],[2,3,4],[3,4,2],[4,5,1]], src1 = 0, src2 = 1, dest = 5\nOutput: 9\nExplanation:\nThe above figure represents the input graph.\nThe blue edges represent one of the subgraphs that yield the optimal answer.\nNote that the subgraph [[1,0,3],[0,5,6]] also yields the optimal answer. It is not possible to get a subgraph with less weight satisfying all the constraints.\nExample 2:\nInput: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2\nOutput: -1\nExplanation:\nThe above figure represents the input graph.\nIt can be seen that there does not exist any path from node 1 to node 2, hence there are no subgraphs satisfying all the constraints.\n  Constraints:\n3 <= n <= 105\n0 <= edges.length <= 105\nedges[i].length == 3\n0 <= fromi, toi, src1, src2, dest <= n - 1\nfromi != toi\nsrc1, src2, and dest are pairwise distinct.\n1 <= weight[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/divide-array-into-equal-pairs/discuss/1864079/Python-Solution-Using-Counter-oror-Beats-99-oror-O(n)",
      "python_solutions": "class Solution:\n\n    def divideArray(self, nums: List[int]) -> bool:\n        lena = len(nums)\n        count = sum(num//2 for num in Counter(nums).values())\n        return (lena/2 == count)",
      "slug": "divide-array-into-equal-pairs",
      "post_title": "Python Solution Using Counter || Beats 99% || O(n)",
      "user": "IvanTsukei",
      "upvotes": 6,
      "views": 698,
      "problem_title": "divide array into equal pairs",
      "number": 2206,
      "acceptance": 0.746,
      "difficulty": "Easy",
      "__index_level_0__": 30581,
      "question": "You are given an integer array nums consisting of 2 * n integers.\nYou need to divide nums into n pairs such that:\nEach element belongs to exactly one pair.\nThe elements present in a pair are equal.\nReturn true if nums can be divided into n pairs, otherwise return false.\n  Example 1:\nInput: nums = [3,2,3,2,2,2]\nOutput: true\nExplanation: \nThere are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\nIf nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: false\nExplanation: \nThere is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.\n  Constraints:\nnums.length == 2 * n\n1 <= n <= 500\n1 <= nums[i] <= 500"
    },
    {
      "post_href": "https://leetcode.com/problems/maximize-number-of-subsequences-in-a-string/discuss/2501496/Python-Easy-Solution",
      "python_solutions": "class Solution:\n    def maximumSubsequenceCount(self, string: str, pattern: str) -> int:\n\n        text = pattern[0]+string\n        text1 = string + pattern[1]\n        cnt,cnt1 = 0,0\n        ans,ans1 = 0,0\n        \n        for i in range(len(text)):\n            if text[i] == pattern[0]:\n                cnt+=1\n            elif text[i] == pattern[1]:\n                ans+= cnt\n        if pattern[0] == pattern[1]:\n            ans = ((cnt)*(cnt-1))//2\n        # appending at the last \n        for i in range(len(text1)):\n            if text1[i] == pattern[0]:\n                cnt1+=1\n            elif text1[i] == pattern[1]:\n                ans1+= cnt1\n        if pattern[0] == pattern[1]:\n            ans1 = ((cnt1)*(cnt1-1))//2\n        return max(ans1,ans)",
      "slug": "maximize-number-of-subsequences-in-a-string",
      "post_title": "Python Easy Solution",
      "user": "Abhi_009",
      "upvotes": 0,
      "views": 26,
      "problem_title": "maximize number of subsequences in a string",
      "number": 2207,
      "acceptance": 0.3279999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 30624,
      "question": "You are given a 0-indexed string text and another 0-indexed string pattern of length 2, both of which consist of only lowercase English letters.\nYou can add either pattern[0] or pattern[1] anywhere in text exactly once. Note that the character can be added even at the beginning or at the end of text.\nReturn the maximum number of times pattern can occur as a subsequence of the modified text.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n  Example 1:\nInput: text = \"abdcdbc\", pattern = \"ac\"\nOutput: 4\nExplanation:\nIf we add pattern[0] = 'a' in between text[1] and text[2], we get \"abadcdbc\". Now, the number of times \"ac\" occurs as a subsequence is 4.\nSome other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\nHowever, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\nIt can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.\nExample 2:\nInput: text = \"aabb\", pattern = \"ab\"\nOutput: 6\nExplanation:\nSome of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".\n  Constraints:\n1 <= text.length <= 105\npattern.length == 2\ntext and pattern consist only of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-operations-to-halve-array-sum/discuss/1984994/python-3-oror-priority-queue",
      "python_solutions": "class Solution:\n    def halveArray(self, nums: List[int]) -> int:\n        s = sum(nums)\n        goal = s / 2\n        res = 0\n        \n        for i, num in enumerate(nums):\n            nums[i] = -num\n        heapq.heapify(nums)\n        \n        while s > goal:\n            halfLargest = -heapq.heappop(nums) / 2\n            s -= halfLargest\n            heapq.heappush(nums, -halfLargest)\n            res += 1\n        \n        return res",
      "slug": "minimum-operations-to-halve-array-sum",
      "post_title": "python 3 || priority queue",
      "user": "dereky4",
      "upvotes": 2,
      "views": 79,
      "problem_title": "minimum operations to halve array sum",
      "number": 2208,
      "acceptance": 0.452,
      "difficulty": "Medium",
      "__index_level_0__": 30630,
      "question": "You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number. (Note that you may choose this reduced number in future operations.)\nReturn the minimum number of operations to reduce the sum of nums by at least half.\n  Example 1:\nInput: nums = [5,19,8,1]\nOutput: 3\nExplanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 19 and reduce it to 9.5.\nPick the number 9.5 and reduce it to 4.75.\nPick the number 8 and reduce it to 4.\nThe final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \nThe sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 >= 33/2 = 16.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\nExample 2:\nInput: nums = [3,8,20]\nOutput: 3\nExplanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.\nThe following is one of the ways to reduce the sum by at least half:\nPick the number 20 and reduce it to 10.\nPick the number 10 and reduce it to 5.\nPick the number 3 and reduce it to 1.5.\nThe final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \nThe sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 >= 31/2 = 15.5.\nOverall, 3 operations were used so we return 3.\nIt can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 107"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-white-tiles-after-covering-with-carpets/discuss/1874969/Python3-dp",
      "python_solutions": "class Solution:\n    def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n        \n        @cache\n        def fn(i, n):\n            \"\"\"Return min while tiles at k with n carpets left.\"\"\"\n            if n < 0: return inf \n            if i >= len(floor): return 0 \n            if floor[i] == '1': return min(fn(i+carpetLen, n-1), 1 + fn(i+1, n))\n            return fn(i+1, n)\n        \n        return fn(0, numCarpets)",
      "slug": "minimum-white-tiles-after-covering-with-carpets",
      "post_title": "[Python3] dp",
      "user": "ye15",
      "upvotes": 2,
      "views": 51,
      "problem_title": "minimum white tiles after covering with carpets",
      "number": 2209,
      "acceptance": 0.3379999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 30637,
      "question": "You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:\nfloor[i] = '0' denotes that the ith tile of the floor is colored black.\nOn the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.\nYou are also given numCarpets and carpetLen. You have numCarpets black carpets, each of length carpetLen tiles. Cover the tiles with the given carpets such that the number of white tiles still visible is minimum. Carpets may overlap one another.\nReturn the minimum number of white tiles still visible.\n  Example 1:\nInput: floor = \"10110101\", numCarpets = 2, carpetLen = 2\nOutput: 2\nExplanation: \nThe figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\nNo other way of covering the tiles with the carpets can leave less than 2 white tiles visible.\nExample 2:\nInput: floor = \"11111\", numCarpets = 2, carpetLen = 3\nOutput: 0\nExplanation: \nThe figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\nNote that the carpets are able to overlap one another.\n  Constraints:\n1 <= carpetLen <= floor.length <= 1000\nfloor[i] is either '0' or '1'.\n1 <= numCarpets <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/count-hills-and-valleys-in-an-array/discuss/1866869/Python3-One-pass-oror-O(1)-space",
      "python_solutions": "class Solution:\n    def countHillValley(self, nums: List[int]) -> int:\n        \n        #cnt: An integer to store total hills and valleys\n        #left: Highest point of hill or lowest point of valley left of the current index\n        cnt, left = 0, nums[0]\n        \n        for i in range(1, len(nums)-1):\n            if (leftnums[i+1]) or (left>nums[i] and nums[i] 2 and 4 > 1, index 1 is a hill. \nAt index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\nAt index 3: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 3 is a valley, but note that it is part of the same valley as index 2.\nAt index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\nAt index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \nThere are 3 hills and valleys so we return 3.\nExample 2:\nInput: nums = [6,6,5,5,4,1]\nOutput: 0\nExplanation:\nAt index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\nAt index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\nAt index 2: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 2 is neither a hill nor a valley.\nAt index 3: The closest non-equal neighbors of 5 are 6 and 4. Since 5 < 6 and 5 > 4, index 3 is neither a hill nor a valley.\nAt index 4: The closest non-equal neighbors of 4 are 5 and 1. Since 4 < 5 and 4 > 1, index 4 is neither a hill nor a valley.\nAt index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\nThere are 0 hills and valleys so we return 0.\n  Constraints:\n3 <= nums.length <= 100\n1 <= nums[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/count-collisions-on-a-road/discuss/1865694/One-liner-in-Python",
      "python_solutions": "class Solution:\n    def countCollisions(self, directions: str) -> int:\n        return sum(d!='S' for d in directions.lstrip('L').rstrip('R'))",
      "slug": "count-collisions-on-a-road",
      "post_title": "One-liner in Python",
      "user": "LuckyBoy88",
      "upvotes": 65,
      "views": 1200,
      "problem_title": "count collisions on a road",
      "number": 2211,
      "acceptance": 0.419,
      "difficulty": "Medium",
      "__index_level_0__": 30666,
      "question": "There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point.\nYou are given a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.\nThe number of collisions can be calculated as follows:\nWhen two cars moving in opposite directions collide with each other, the number of collisions increases by 2.\nWhen a moving car collides with a stationary car, the number of collisions increases by 1.\nAfter a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.\nReturn the total number of collisions that will happen on the road.\n  Example 1:\nInput: directions = \"RLRSLL\"\nOutput: 5\nExplanation:\nThe collisions that will happen on the road are:\n- Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the number of collisions becomes 0 + 2 = 2.\n- Cars 2 and 3 will collide with each other. Since car 3 is stationary, the number of collisions becomes 2 + 1 = 3.\n- Cars 3 and 4 will collide with each other. Since car 3 is stationary, the number of collisions becomes 3 + 1 = 4.\n- Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The number of collisions becomes 4 + 1 = 5.\nThus, the total number of collisions that will happen on the road is 5. \nExample 2:\nInput: directions = \"LLRR\"\nOutput: 0\nExplanation:\nNo cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.\n  Constraints:\n1 <= directions.length <= 105\ndirections[i] is either 'L', 'R', or 'S'."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-points-in-an-archery-competition/discuss/1866042/Python3-DP-100-with-Detailed-Explanation",
      "python_solutions": "class Solution:\n    def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n        \n        # Initialization with round 1 (round 0 is skipped)\n        dp = {(0, 0): (0, numArrows), (0, aliceArrows[1] + 1): (1, numArrows - (aliceArrows[1] + 1))}\n        \n        # Loop from round 2\n        for i in range(2, 12):\n            prev = dp\n            dp = {}\n            \n            # Consider two possible strategies for each state from last round: to bid and not to bid\n            for key in prev:\n                \n                # Base case: not to bid in this round. Score and arrows left do not change.\n                # Simply append 0 at the end to the key.\n                newkey1 = list(key)\n                newkey1.append(0)\n                score, arrowleft = prev[key]\n                \n                newval1 = (score, arrowleft)\n                dp[tuple(newkey1)] = newval1\n                \n                # If we still have enough arrows, we can bid in this round\n                if arrowleft >= aliceArrows[i] + 1:\n                    newkey2 = list(key)\n                    newkey2.append(aliceArrows[i] + 1)\n                    newval2 = (score + i, arrowleft - (aliceArrows[i] + 1))\n                    dp[tuple(newkey2)] = newval2\n        \n        # Select the bidding history with max score\n        maxscore, res = 0, None\n        for key in dp:\n            score, _ = dp[key]\n            if score > maxscore:\n                maxscore = score\n                res = list(key)\n        \n        # Taking care of the corner case, where too many arrows are given\n        if sum(res) < numArrows:\n            res[0] = numArrows - sum(res)\n        \n        return res",
      "slug": "maximum-points-in-an-archery-competition",
      "post_title": "[Python3] DP 100% with Detailed Explanation",
      "user": "hsjiang",
      "upvotes": 1,
      "views": 68,
      "problem_title": "maximum points in an archery competition",
      "number": 2212,
      "acceptance": 0.489,
      "difficulty": "Medium",
      "__index_level_0__": 30682,
      "question": "Alice and Bob are opponents in an archery competition. The competition has set the following rules:\nAlice first shoots numArrows arrows and then Bob shoots numArrows arrows.\nThe points are then calculated as follows:\nThe target has integer scoring sections ranging from 0 to 11 inclusive.\nFor each section of the target with score k (in between 0 to 11), say Alice and Bob have shot ak and bk arrows on that section respectively. If ak >= bk, then Alice takes k points. If ak < bk, then Bob takes k points.\nHowever, if ak == bk == 0, then nobody takes k points.\nFor example, if Alice and Bob both shot 2 arrows on the section with score 11, then Alice takes 11 points. On the other hand, if Alice shot 0 arrows on the section with score 11 and Bob shot 2 arrows on that same section, then Bob takes 11 points.\nYou are given the integer numArrows and an integer array aliceArrows of size 12, which represents the number of arrows Alice shot on each scoring section from 0 to 11. Now, Bob wants to maximize the total number of points he can obtain.\nReturn the array bobArrows which represents the number of arrows Bob shot on each scoring section from 0 to 11. The sum of the values in bobArrows should equal numArrows.\nIf there are multiple ways for Bob to earn the maximum total points, return any one of them.\n  Example 1:\nInput: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]\nOutput: [0,0,0,0,1,1,0,0,1,2,3,1]\nExplanation: The table above shows how the competition is scored. \nBob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\nIt can be shown that Bob cannot obtain a score higher than 47 points.\nExample 2:\nInput: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]\nOutput: [0,0,0,0,0,0,0,0,1,1,1,0]\nExplanation: The table above shows how the competition is scored.\nBob earns a total point of 8 + 9 + 10 = 27.\nIt can be shown that Bob cannot obtain a score higher than 27 points.\n  Constraints:\n1 <= numArrows <= 105\naliceArrows.length == bobArrows.length == 12\n0 <= aliceArrows[i], bobArrows[i] <= numArrows\nsum(aliceArrows[i]) == numArrows"
    },
    {
      "post_href": "https://leetcode.com/problems/find-the-difference-of-two-arrays/discuss/2668224/Python-solution.-Clean-code-with-full-comments.-95.96-speed.",
      "python_solutions": "class Solution:\n    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n        \n        set_1 = list_to_set(nums1)\n        set_2 = list_to_set(nums2)\n        \n        return remove_same_elements(set_1, set_2)\n                \n# Convert the lists into sets via helper method.      \ndef list_to_set(arr: List[int]):\n    \n    s = set()\n    \n    for i in arr:\n        s.add(i)\n        \n    return s   \n\n# Now when the two lists are sets, use the difference attribute to filter common elements of the two sets.\ndef remove_same_elements(x, y):\n    \n    x, y = list(x - y), list(y - x)\n        \n    return [x, y]\n\n\n# Runtime: 185 ms, faster than 95.96% of Python3 online submissions for Find the Difference of Two Arrays.\n# Memory Usage: 14.3 MB, less than 51.66% of Python3 online submissions for Find the Difference of Two Arrays.\n\n# If you like my work, then I'll appreciate a like. Thanks!",
      "slug": "find-the-difference-of-two-arrays",
      "post_title": "Python solution. Clean code with full comments. 95.96% speed.",
      "user": "375d",
      "upvotes": 3,
      "views": 159,
      "problem_title": "find the difference of two arrays",
      "number": 2215,
      "acceptance": 0.693,
      "difficulty": "Easy",
      "__index_level_0__": 30692,
      "question": "Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:\nanswer[0] is a list of all distinct integers in nums1 which are not present in nums2.\nanswer[1] is a list of all distinct integers in nums2 which are not present in nums1.\nNote that the integers in the lists may be returned in any order.\n  Example 1:\nInput: nums1 = [1,2,3], nums2 = [2,4,6]\nOutput: [[1,3],[4,6]]\nExplanation:\nFor nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].\nFor nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].\nExample 2:\nInput: nums1 = [1,2,3,3], nums2 = [1,1,2,2]\nOutput: [[3],[]]\nExplanation:\nFor nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].\nEvery integer in nums2 is present in nums1. Therefore, answer[1] = [].\n  Constraints:\n1 <= nums1.length, nums2.length <= 1000\n-1000 <= nums1[i], nums2[i] <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/discuss/1886918/Python-or-Greedy",
      "python_solutions": "class Solution:\n    def minDeletion(self, nums: List[int]) -> int:\n        # Greedy !\n        # we first only consider requirement 2: nums[i] != nums[i + 1] for all i % 2 == 0\n        # at the begining, we consider the num on the even index\n        # when we delete a num, we need consider the num on the odd index\n        # then repeat this process\n        # at the end we check the requirement 1: nums.length is even or not\n        \n        n = len(nums)\n        count = 0\n        # flag is true then check the even index\n        # flag is false then check the odd index\n        flag = True\n        \n        for i in range(n):\n            # check the even index\n            if flag:\n                if i % 2 == 0 and i != n -1 and nums[i] == nums[i + 1]:\n                    count += 1\n                    flag = False\n            # check the odd index\n            elif not flag:\n                if i % 2 == 1 and i != n -1 and nums[i] == nums[i + 1]:\n                    count += 1\n                    flag = True\n        \n        curLength = n - count\n        \n        return count if curLength % 2 == 0 else count + 1",
      "slug": "minimum-deletions-to-make-array-beautiful",
      "post_title": "Python | Greedy",
      "user": "Mikey98",
      "upvotes": 10,
      "views": 397,
      "problem_title": "minimum deletions to make array beautiful",
      "number": 2216,
      "acceptance": 0.4629999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 30733,
      "question": "You are given a 0-indexed integer array nums. The array nums is beautiful if:\nnums.length is even.\nnums[i] != nums[i + 1] for all i % 2 == 0.\nNote that an empty array is considered beautiful.\nYou can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.\nReturn the minimum number of elements to delete from nums to make it beautiful.\n  Example 1:\nInput: nums = [1,1,2,3,5]\nOutput: 1\nExplanation: You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful.\nExample 2:\nInput: nums = [1,1,2,2,3,3]\nOutput: 2\nExplanation: You can delete nums[0] and nums[5] to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.\n  Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/find-palindrome-with-fixed-length/discuss/1886956/Python-or-simple-and-straightforward",
      "python_solutions": "class Solution:\n    def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n        # think the palindromes in half\n        # e.g. len  = 4 we only consider the first 2 digits\n        # half: 10, 11, 12, 13, 14, ..., 19, 20, \n        # full: 1001, 1111, 1221, 1331, ...\n        # e.g. len = 5 we consider the first 3 digits\n        # half: 100, 101, 102, ...\n        # full: 10001, 10101, 10201, ...\n        \n        result = []\n        \n        for i in queries:\n            result.append(self.generatePalindrome(intLength, i))\n        \n        return result\n    \n    def generatePalindrome(self, length, num):\n        # index start from 0\n\t\t# e.g. num =1 means we want to find the most smallest palindrome, then its index is 0\n\t\t# e.g. num =2 means we want to find the second most smallest palindrome, then its index is 1\n        index = num -1\n        \n\t\t# if the length is even\n\t\t# we only think about the fisrt half of digits\n        if length % 2 == 0:\n            cur = int('1' + '0' * (length // 2 -1))\n            maxLength = len(str(cur))\n            cur += index\n            \n            if len(str(cur)) > maxLength:\n                return -1\n            \n            else:\n                cur = str(cur)\n                cur = cur + cur[::-1]\n                cur = int(cur)\n                return cur\n\t\t\t\t\n        # if the length is odd\n\t\t# we consider first (length // 2 + 1) digits\n        else:\n            cur = int('1' + '0' * (length // 2))\n            maxLength = len(str(cur))\n            cur += index\n            \n            if len(str(cur)) > maxLength:\n                return -1\n            \n            else:\n                cur = str(cur)\n                temp = str(cur)[:-1]\n                cur = cur + temp[::-1]\n                cur = int(cur)\n                return cur",
      "slug": "find-palindrome-with-fixed-length",
      "post_title": "Python | simple and straightforward",
      "user": "Mikey98",
      "upvotes": 6,
      "views": 474,
      "problem_title": "find palindrome with fixed length",
      "number": 2217,
      "acceptance": 0.3429999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 30750,
      "question": "Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists.\nA palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.\n  Example 1:\nInput: queries = [1,2,3,4,5,90], intLength = 3\nOutput: [101,111,121,131,141,999]\nExplanation:\nThe first few palindromes of length 3 are:\n101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\nThe 90th palindrome of length 3 is 999.\nExample 2:\nInput: queries = [2,4,6], intLength = 4\nOutput: [1111,1331,1551]\nExplanation:\nThe first six palindromes of length 4 are:\n1001, 1111, 1221, 1331, 1441, and 1551.\n  Constraints:\n1 <= queries.length <= 5 * 104\n1 <= queries[i] <= 109\n1 <= intLength <= 15"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-value-of-k-coins-from-piles/discuss/1889647/Python-Bottom-up-DP-solution",
      "python_solutions": "class Solution:\n    def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n        n, m = len(piles), 0\n        prefixSum = []\n        for i in range(n):\n            temp = [0]\n            for j in range(len(piles[i])):\n                temp.append(temp[-1] + piles[i][j])\n                m += 1\n            prefixSum.append(temp)\n        if m == k:\n            return sum(temp[-1] for temp in prefixSum)\n            \n        dp = [[0] * (k + 1) for _ in range(n)]\n        for j in range(1, k + 1):\n            if j < len(prefixSum[0]):\n                dp[0][j] = prefixSum[0][j]\n        \n        for i in range(1, n):\n            for j in range(1, k + 1):\n                for l in range(len(prefixSum[i])):\n                    if l > j:\n                        break\n                    dp[i][j] = max(dp[i][j], prefixSum[i][l] + dp[i - 1][j - l])\n        return dp[n - 1][k]",
      "slug": "maximum-value-of-k-coins-from-piles",
      "post_title": "[Python] Bottom-up DP solution",
      "user": "xil899",
      "upvotes": 9,
      "views": 407,
      "problem_title": "maximum value of k coins from piles",
      "number": 2218,
      "acceptance": 0.48,
      "difficulty": "Hard",
      "__index_level_0__": 30764,
      "question": "There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.\nIn one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.\nGiven a list piles, where piles[i] is a list of integers denoting the composition of the ith pile from top to bottom, and a positive integer k, return the maximum total value of coins you can have in your wallet if you choose exactly k coins optimally.\n  Example 1:\nInput: piles = [[1,100,3],[7,8,9]], k = 2\nOutput: 101\nExplanation:\nThe above diagram shows the different ways we can choose k coins.\nThe maximum total we can obtain is 101.\nExample 2:\nInput: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\nOutput: 706\nExplanation:\nThe maximum total can be obtained if we choose all coins from the last pile.\n  Constraints:\nn == piles.length\n1 <= n <= 1000\n1 <= piles[i][j] <= 105\n1 <= k <= sum(piles[i].length) <= 2000"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-bit-flips-to-convert-number/discuss/2775126/Python-Solution-without-XOR",
      "python_solutions": "class Solution:\n    def minBitFlips(self, s: int, g: int) -> int:\n        count = 0\n        while s or g:\n            if s%2 != g%2: count+=1\n            s, g = s//2, g//2\n        return count",
      "slug": "minimum-bit-flips-to-convert-number",
      "post_title": "Python Solution without XOR",
      "user": "keioon",
      "upvotes": 4,
      "views": 134,
      "problem_title": "minimum bit flips to convert number",
      "number": 2220,
      "acceptance": 0.821,
      "difficulty": "Easy",
      "__index_level_0__": 30769,
      "question": "A bit flip of a number x is choosing a bit in the binary representation of x and flipping it from either 0 to 1 or 1 to 0.\nFor example, for x = 7, the binary representation is 111 and we may choose any bit (including any leading zeros not shown) and flip it. We can flip the first bit from the right to get 110, flip the second bit from the right to get 101, flip the fifth bit from the right (a leading zero) to get 10111, etc.\nGiven two integers start and goal, return the minimum number of bit flips to convert start to goal.\n  Example 1:\nInput: start = 10, goal = 7\nOutput: 3\nExplanation: The binary representation of 10 and 7 are 1010 and 0111 respectively. We can convert 10 to 7 in 3 steps:\n- Flip the first bit from the right: 1010 -> 1011.\n- Flip the third bit from the right: 1011 -> 1111.\n- Flip the fourth bit from the right: 1111 -> 0111.\nIt can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.\nExample 2:\nInput: start = 3, goal = 4\nOutput: 3\nExplanation: The binary representation of 3 and 4 are 011 and 100 respectively. We can convert 3 to 4 in 3 steps:\n- Flip the first bit from the right: 011 -> 010.\n- Flip the second bit from the right: 010 -> 000.\n- Flip the third bit from the right: 000 -> 100.\nIt can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.\n  Constraints:\n0 <= start, goal <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/find-triangular-sum-of-an-array/discuss/1909302/Pascal-Triangle",
      "python_solutions": "class Solution:\n    def triangularSum(self, nums: List[int]) -> int:\n        return sum(n * comb(len(nums) - 1, i) for i, n in enumerate(nums)) % 10",
      "slug": "find-triangular-sum-of-an-array",
      "post_title": "Pascal Triangle",
      "user": "votrubac",
      "upvotes": 28,
      "views": 3800,
      "problem_title": "find triangular sum of an array",
      "number": 2221,
      "acceptance": 0.79,
      "difficulty": "Medium",
      "__index_level_0__": 30798,
      "question": "You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).\nThe triangular sum of nums is the value of the only element present in nums after the following process terminates:\nLet nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.\nFor each index i, where 0 <= i < n - 1, assign the value of newNums[i] as (nums[i] + nums[i+1]) % 10, where % denotes modulo operator.\nReplace the array nums with newNums.\nRepeat the entire process starting from step 1.\nReturn the triangular sum of nums.\n  Example 1:\nInput: nums = [1,2,3,4,5]\nOutput: 8\nExplanation:\nThe above diagram depicts the process from which we obtain the triangular sum of the array.\nExample 2:\nInput: nums = [5]\nOutput: 5\nExplanation:\nSince there is only one element in nums, the triangular sum is the value of that element itself.\n  Constraints:\n1 <= nums.length <= 1000\n0 <= nums[i] <= 9"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-ways-to-select-buildings/discuss/1979756/python-3-oror-short-and-simple-oror-O(n)O(1)",
      "python_solutions": "class Solution:\n    def numberOfWays(self, s: str) -> int:\n        zeros = s.count('0')\n        ones = len(s) - zeros\n        zeroPrefix = onePrefix = res = 0\n        for c in s:\n            if c == '0':\n                res += onePrefix * (ones - onePrefix)\n                zeroPrefix += 1\n            else:\n                res += zeroPrefix * (zeros - zeroPrefix)\n                onePrefix += 1\n        \n        return res",
      "slug": "number-of-ways-to-select-buildings",
      "post_title": "python 3 || short and simple || O(n)/O(1)",
      "user": "dereky4",
      "upvotes": 5,
      "views": 304,
      "problem_title": "number of ways to select buildings",
      "number": 2222,
      "acceptance": 0.512,
      "difficulty": "Medium",
      "__index_level_0__": 30844,
      "question": "You are given a 0-indexed binary string s which represents the types of buildings along a street where:\ns[i] = '0' denotes that the ith building is an office and\ns[i] = '1' denotes that the ith building is a restaurant.\nAs a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.\nFor example, given s = \"001101\", we cannot select the 1st, 3rd, and 5th buildings as that would form \"011\" which is not allowed due to having two consecutive buildings of the same type.\nReturn the number of valid ways to select 3 buildings.\n  Example 1:\nInput: s = \"001101\"\nOutput: 6\nExplanation: \nThe following sets of indices selected are valid:\n- [0,2,4] from \"001101\" forms \"010\"\n- [0,3,4] from \"001101\" forms \"010\"\n- [1,2,4] from \"001101\" forms \"010\"\n- [1,3,4] from \"001101\" forms \"010\"\n- [2,4,5] from \"001101\" forms \"101\"\n- [3,4,5] from \"001101\" forms \"101\"\nNo other selection is valid. Thus, there are 6 total ways.\nExample 2:\nInput: s = \"11100\"\nOutput: 0\nExplanation: It can be shown that there are no valid selections.\n  Constraints:\n3 <= s.length <= 105\ns[i] is either '0' or '1'."
    },
    {
      "post_href": "https://leetcode.com/problems/sum-of-scores-of-built-strings/discuss/2256814/Python3-rolling-hash-and-z-algorithm",
      "python_solutions": "class Solution:\n    def sumScores(self, s: str) -> int:\n        mod = 119_218_851_371\n        hs = 0 \n        vals = [0]\n        for i, ch in enumerate(s): \n            hs = (hs * 26 + ord(ch) - 97) % mod\n            vals.append(hs)\n        \n        p26 = [1]\n        for _ in range(len(s)): p26.append(p26[-1] * 26 % mod)\n        \n        ans = 0 \n        for i in range(len(s)): \n            if s[0] == s[i]: \n                lo, hi = i, len(s)\n                while lo < hi: \n                    mid = lo + hi + 1 >> 1\n                    hs = (vals[mid] - vals[i]*p26[mid-i]) % mod\n                    if hs == vals[mid-i]: lo = mid\n                    else: hi = mid - 1\n                ans += lo - i \n        return ans",
      "slug": "sum-of-scores-of-built-strings",
      "post_title": "[Python3] rolling hash & z-algorithm",
      "user": "ye15",
      "upvotes": 1,
      "views": 82,
      "problem_title": "sum of scores of built strings",
      "number": 2223,
      "acceptance": 0.37,
      "difficulty": "Hard",
      "__index_level_0__": 30852,
      "question": "You are building a string s of length n one character at a time, prepending each new character to the front of the string. The strings are labeled from 1 to n, where the string with length i is labeled si.\nFor example, for s = \"abaca\", s1 == \"a\", s2 == \"ca\", s3 == \"aca\", etc.\nThe score of si is the length of the longest common prefix between si and sn (Note that s == sn).\nGiven the final string s, return the sum of the score of every si.\n  Example 1:\nInput: s = \"babab\"\nOutput: 9\nExplanation:\nFor s1 == \"b\", the longest common prefix is \"b\" which has a score of 1.\nFor s2 == \"ab\", there is no common prefix so the score is 0.\nFor s3 == \"bab\", the longest common prefix is \"bab\" which has a score of 3.\nFor s4 == \"abab\", there is no common prefix so the score is 0.\nFor s5 == \"babab\", the longest common prefix is \"babab\" which has a score of 5.\nThe sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.\nExample 2:\nInput: s = \"azbazbzaz\"\nOutput: 14\nExplanation: \nFor s2 == \"az\", the longest common prefix is \"az\" which has a score of 2.\nFor s6 == \"azbzaz\", the longest common prefix is \"azb\" which has a score of 3.\nFor s9 == \"azbazbzaz\", the longest common prefix is \"azbazbzaz\" which has a score of 9.\nFor all other si, the score is 0.\nThe sum of the scores is 2 + 3 + 9 = 14, so we return 14.\n  Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-convert-time/discuss/1908786/Easy-Python-Solution-or-Convert-time-to-minutes",
      "python_solutions": "class Solution:\n    def convertTime(self, current: str, correct: str) -> int:\n        current_time = 60 * int(current[0:2]) + int(current[3:5]) # Current time in minutes\n        target_time = 60 * int(correct[0:2]) + int(correct[3:5]) # Target time in minutes\n        diff = target_time - current_time # Difference b/w current and target times in minutes\n        count = 0 # Required number of operations\n\t\t# Use GREEDY APPROACH to calculate number of operations\n        for i in [60, 15, 5, 1]:\n            count += diff // i # add number of operations needed with i to count\n            diff %= i # Diff becomes modulo of diff with i\n        return count",
      "slug": "minimum-number-of-operations-to-convert-time",
      "post_title": "\u2b50Easy Python Solution | Convert time to minutes",
      "user": "anCoderr",
      "upvotes": 30,
      "views": 1200,
      "problem_title": "minimum number of operations to convert time",
      "number": 2224,
      "acceptance": 0.655,
      "difficulty": "Easy",
      "__index_level_0__": 30856,
      "question": "You are given two strings current and correct representing two 24-hour times.\n24-hour times are formatted as \"HH:MM\", where HH is between 00 and 23, and MM is between 00 and 59. The earliest 24-hour time is 00:00, and the latest is 23:59.\nIn one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.\nReturn the minimum number of operations needed to convert current to correct.\n  Example 1:\nInput: current = \"02:30\", correct = \"04:35\"\nOutput: 3\nExplanation:\nWe can convert current to correct in 3 operations as follows:\n- Add 60 minutes to current. current becomes \"03:30\".\n- Add 60 minutes to current. current becomes \"04:30\".\n- Add 5 minutes to current. current becomes \"04:35\".\nIt can be proven that it is not possible to convert current to correct in fewer than 3 operations.\nExample 2:\nInput: current = \"11:00\", correct = \"11:01\"\nOutput: 1\nExplanation: We only have to add one minute to current, so the minimum number of operations needed is 1.\n  Constraints:\ncurrent and correct are in the format \"HH:MM\"\ncurrent <= correct"
    },
    {
      "post_href": "https://leetcode.com/problems/find-players-with-zero-or-one-losses/discuss/1908760/Python-Solution-with-Hashmap",
      "python_solutions": "class Solution:\n    def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n        winners, losers, table = [], [], {}\n        for winner, loser in matches:\n            # map[key] = map.get(key, 0) + change . This format ensures that KEY NOT FOUND error is always prevented.\n            # map.get(key, 0) returns map[key] if key exists and 0 if it does not.\n            table[winner] = table.get(winner, 0)  # Winner\n            table[loser] = table.get(loser, 0) + 1\n        for k, v in table.items(): # Player k with losses v\n            if v == 0:\n                winners.append(k) # If player k has no loss ie v == 0\n            if v == 1:\n                losers.append(k) # If player k has one loss ie v == 1\n        return [sorted(winners), sorted(losers)] # Problem asked to return sorted arrays.",
      "slug": "find-players-with-zero-or-one-losses",
      "post_title": "\u2b50Python Solution with Hashmap",
      "user": "anCoderr",
      "upvotes": 22,
      "views": 1200,
      "problem_title": "find players with zero or one losses",
      "number": 2225,
      "acceptance": 0.6859999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 30877,
      "question": "You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.\nReturn a list answer of size 2 where:\nanswer[0] is a list of all players that have not lost any matches.\nanswer[1] is a list of all players that have lost exactly one match.\nThe values in the two lists should be returned in increasing order.\nNote:\nYou should only consider the players that have played at least one match.\nThe testcases will be generated such that no two matches will have the same outcome.\n  Example 1:\nInput: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\nOutput: [[1,2,10],[4,5,7,8]]\nExplanation:\nPlayers 1, 2, and 10 have not lost any matches.\nPlayers 4, 5, 7, and 8 each have lost one match.\nPlayers 3, 6, and 9 each have lost two matches.\nThus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].\nExample 2:\nInput: matches = [[2,3],[1,3],[5,4],[6,4]]\nOutput: [[1,2,5,6],[]]\nExplanation:\nPlayers 1, 2, 5, and 6 have not lost any matches.\nPlayers 3 and 4 each have lost two matches.\nThus, answer[0] = [1,2,5,6] and answer[1] = [].\n  Constraints:\n1 <= matches.length <= 105\nmatches[i].length == 2\n1 <= winneri, loseri <= 105\nwinneri != loseri\nAll matches[i] are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-candies-allocated-to-k-children/discuss/1912213/Easy-To-Understand-Python-Solution-(Binary-Search)",
      "python_solutions": "class Solution:\n    def maximumCandies(self, candies, k):\n        n = len(candies)\n        left = 1  # the least number of candy in each stack we can give to each student is one\n        right = max(candies)  # the max number of candy in each stack that we can give to each student is the maximum number in the candies array\n        ans = 0 # ans here is used to store the maximum amount in each stack that we can give to each children. \n               # If we don't have enough to distribute, we will return 0 at the end so we initialize it to be 0 now.\n\n        while left <= right:  # binary search\n            numberOfPiles = 0\n            mid = (left) + (right - left) // 2  # the number of candies we require to form a stack\n\n            for i in range(n):   # loop through the array to find the numbers of stack we can form\n                numberOfPiles += candies[i] // mid   # we add to the numberOfPiles whenever we find that this current stack (candies[i]) can be split into mid (the number of candies we require to form a stack)\n\n            if numberOfPiles >= k: # if our number of piles is greater or equal than the students we have, so we have enough to distribute\n                ans = max(ans, mid)   # we first store the max no. of candies in each stack that we can give to each student \n                left = mid + 1      # we will try to increase the number of candies in each stack that we can give to each student\n            else: \n                right = mid - 1   # we will try to reduce the number of candies in each stack that we can give to each student\n        return ans",
      "slug": "maximum-candies-allocated-to-k-children",
      "post_title": "Easy To Understand Python Solution (Binary Search)",
      "user": "danielkua",
      "upvotes": 2,
      "views": 87,
      "problem_title": "maximum candies allocated to k children",
      "number": 2226,
      "acceptance": 0.361,
      "difficulty": "Medium",
      "__index_level_0__": 30899,
      "question": "You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.\nYou are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.\nReturn the maximum number of candies each child can get.\n  Example 1:\nInput: candies = [5,8,6], k = 3\nOutput: 5\nExplanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.\nExample 2:\nInput: candies = [2,5], k = 11\nOutput: 0\nExplanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.\n  Constraints:\n1 <= candies.length <= 105\n1 <= candies[i] <= 107\n1 <= k <= 1012"
    },
    {
      "post_href": "https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/discuss/1931017/Python-Solution-using-Sorting",
      "python_solutions": "class Solution:\n    def largestInteger(self, num: int):\n        n = len(str(num))\n        arr = [int(i) for i in str(num)]\n        odd, even = [], []\n        for i in arr:\n            if i % 2 == 0:\n                even.append(i)\n            else:\n                odd.append(i)\n        odd.sort()\n        even.sort()\n        res = 0\n        for i in range(n):\n            if arr[i] % 2 == 0:\n                res = res*10 + even.pop()\n            else:\n                res = res*10 + odd.pop()\n        return res",
      "slug": "largest-number-after-digit-swaps-by-parity",
      "post_title": "Python Solution using Sorting",
      "user": "anCoderr",
      "upvotes": 17,
      "views": 1500,
      "problem_title": "largest number after digit swaps by parity",
      "number": 2231,
      "acceptance": 0.605,
      "difficulty": "Easy",
      "__index_level_0__": 30913,
      "question": "You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).\nReturn the largest possible value of num after any number of swaps.\n  Example 1:\nInput: num = 1234\nOutput: 3412\nExplanation: Swap the digit 3 with the digit 1, this results in the number 3214.\nSwap the digit 2 with the digit 4, this results in the number 3412.\nNote that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\nAlso note that we may not swap the digit 4 with the digit 1 since they are of different parities.\nExample 2:\nInput: num = 65875\nOutput: 87655\nExplanation: Swap the digit 8 with the digit 6, this results in the number 85675.\nSwap the first digit 5 with the digit 7, this results in the number 87655.\nNote that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.\n  Constraints:\n1 <= num <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimize-result-by-adding-parentheses-to-expression/discuss/1931004/Python-Solution-using-2-Pointers-Brute-Force",
      "python_solutions": "class Solution:\n    def minimizeResult(self, expression: str) -> str:\n        plus_index, n, ans = expression.find('+'), len(expression), [float(inf),expression] \n        def evaluate(exps: str):\n            return eval(exps.replace('(','*(').replace(')', ')*').lstrip('*').rstrip('*'))\n        for l in range(plus_index):\n            for r in range(plus_index+1, n):\n                exps = f'{expression[:l]}({expression[l:plus_index]}+{expression[plus_index+1:r+1]}){expression[r+1:n]}'\n                res = evaluate(exps)\n                if ans[0] > res:\n                    ans[0], ans[1] = res, exps\n        return ans[1]",
      "slug": "minimize-result-by-adding-parentheses-to-expression",
      "post_title": "Python Solution using 2 Pointers Brute Force",
      "user": "anCoderr",
      "upvotes": 12,
      "views": 1500,
      "problem_title": "minimize result by adding parentheses to expression",
      "number": 2232,
      "acceptance": 0.6509999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 30930,
      "question": "You are given a 0-indexed string expression of the form \"+\" where  and  represent positive integers.\nAdd a pair of parentheses to expression such that after the addition of parentheses, expression is a valid mathematical expression and evaluates to the smallest possible value. The left parenthesis must be added to the left of '+' and the right parenthesis must be added to the right of '+'.\nReturn expression after adding a pair of parentheses such that expression evaluates to the smallest possible value. If there are multiple answers that yield the same result, return any of them.\nThe input has been generated such that the original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.\n  Example 1:\nInput: expression = \"247+38\"\nOutput: \"2(47+38)\"\nExplanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.\nNote that \"2(4)7+38\" is invalid because the right parenthesis must be to the right of the '+'.\nIt can be shown that 170 is the smallest possible value.\nExample 2:\nInput: expression = \"12+34\"\nOutput: \"1(2+3)4\"\nExplanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.\nExample 3:\nInput: expression = \"999+999\"\nOutput: \"(999+999)\"\nExplanation: The expression evaluates to 999 + 999 = 1998.\n  Constraints:\n3 <= expression.length <= 10\nexpression consists of digits from '1' to '9' and '+'.\nexpression starts and ends with digits.\nexpression contains exactly one '+'.\nThe original value of expression, and the value of expression after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-product-after-k-increments/discuss/1930986/Python-Solution-using-Min-Heap",
      "python_solutions": "class Solution:\n    def maximumProduct(self, nums: List[int], k: int) -> int:\n        heap = nums.copy()\n        heapify(heap)\n        for i in range(k):\n            t = heappop(heap)\n            heappush(heap, t + 1)\n        ans = 1\n        mod = 1000000007\n        for i in heap:\n            ans = (ans*i) % mod\n        return ans",
      "slug": "maximum-product-after-k-increments",
      "post_title": "\u27a1\ufe0fPython Solution using Min Heap",
      "user": "anCoderr",
      "upvotes": 2,
      "views": 150,
      "problem_title": "maximum product after k increments",
      "number": 2233,
      "acceptance": 0.413,
      "difficulty": "Medium",
      "__index_level_0__": 30947,
      "question": "You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.\nReturn the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7. Note that you should maximize the product before taking the modulo. \n  Example 1:\nInput: nums = [0,4], k = 5\nOutput: 20\nExplanation: Increment the first number 5 times.\nNow nums = [5, 4], with a product of 5 * 4 = 20.\nIt can be shown that 20 is maximum product possible, so we return 20.\nNote that there may be other ways to increment nums to have the maximum product.\nExample 2:\nInput: nums = [6,3,3,2], k = 2\nOutput: 216\nExplanation: Increment the second number 1 time and increment the fourth number 1 time.\nNow nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\nIt can be shown that 216 is maximum product possible, so we return 216.\nNote that there may be other ways to increment nums to have the maximum product.\n  Constraints:\n1 <= nums.length, k <= 105\n0 <= nums[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-total-beauty-of-the-gardens/discuss/2313576/Python3-2-pointer",
      "python_solutions": "class Solution:\n    def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n        flowers = sorted(min(target, x) for x in flowers)\n        prefix = [0]\n        ii = -1 \n        for i in range(len(flowers)): \n            if flowers[i] < target: ii = i \n            if i: prefix.append(prefix[-1] + (flowers[i]-flowers[i-1])*i)\n        ans = 0 \n        for k in range(len(flowers)+1): \n            if k: newFlowers -= target - flowers[-k]\n            if newFlowers >= 0: \n                while 0 <= ii and (ii+k >= len(flowers) or prefix[ii] > newFlowers): ii -= 1\n                if 0 <= ii: kk = min(target-1, flowers[ii] + (newFlowers - prefix[ii])//(ii+1))\n                else: kk = 0 \n                ans = max(ans, k*full + kk*partial)\n        return ans",
      "slug": "maximum-total-beauty-of-the-gardens",
      "post_title": "[Python3] 2-pointer",
      "user": "ye15",
      "upvotes": 1,
      "views": 61,
      "problem_title": "maximum total beauty of the gardens",
      "number": 2234,
      "acceptance": 0.283,
      "difficulty": "Hard",
      "__index_level_0__": 30958,
      "question": "Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens.\nYou are given a 0-indexed integer array flowers of size n, where flowers[i] is the number of flowers already planted in the ith garden. Flowers that are already planted cannot be removed. You are then given another integer newFlowers, which is the maximum number of flowers that Alice can additionally plant. You are also given the integers target, full, and partial.\nA garden is considered complete if it has at least target flowers. The total beauty of the gardens is then determined as the sum of the following:\nThe number of complete gardens multiplied by full.\nThe minimum number of flowers in any of the incomplete gardens multiplied by partial. If there are no incomplete gardens, then this value will be 0.\nReturn the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.\n  Example 1:\nInput: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1\nOutput: 14\nExplanation: Alice can plant\n- 2 flowers in the 0th garden\n- 3 flowers in the 1st garden\n- 1 flower in the 2nd garden\n- 1 flower in the 3rd garden\nThe gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\nThere is 1 garden that is complete.\nThe minimum number of flowers in the incomplete gardens is 2.\nThus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\nNo other way of planting flowers can obtain a total beauty higher than 14.\nExample 2:\nInput: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6\nOutput: 30\nExplanation: Alice can plant\n- 3 flowers in the 0th garden\n- 0 flowers in the 1st garden\n- 0 flowers in the 2nd garden\n- 2 flowers in the 3rd garden\nThe gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\nThere are 3 gardens that are complete.\nThe minimum number of flowers in the incomplete gardens is 4.\nThus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\nNo other way of planting flowers can obtain a total beauty higher than 30.\nNote that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.\n  Constraints:\n1 <= flowers.length <= 105\n1 <= flowers[i], target <= 105\n1 <= newFlowers <= 1010\n1 <= full, partial <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/add-two-integers/discuss/2670517/Solutions-in-Every-Language-*on-leetcode*-or-One-Liner",
      "python_solutions": "class Solution:\n    def sum(self, num1: int, num2: int) -> int:\n        return num1 + num2",
      "slug": "add-two-integers",
      "post_title": "Solutions in Every Language *on leetcode* | One-Liner \u2705",
      "user": "qing306037",
      "upvotes": 5,
      "views": 465,
      "problem_title": "add two integers",
      "number": 2235,
      "acceptance": 0.894,
      "difficulty": "Easy",
      "__index_level_0__": 30961,
      "question": "Given two integers num1 and num2, return the sum of the two integers.\n  Example 1:\nInput: num1 = 12, num2 = 5\nOutput: 17\nExplanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.\nExample 2:\nInput: num1 = -10, num2 = 4\nOutput: -6\nExplanation: num1 + num2 = -6, so -6 is returned.\n  Constraints:\n-100 <= num1, num2 <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/root-equals-sum-of-children/discuss/2178260/Python-oneliner",
      "python_solutions": "class Solution:\n    def checkTree(self, root: Optional[TreeNode]) -> bool:\n        return root.left.val+root.right.val == root.val",
      "slug": "root-equals-sum-of-children",
      "post_title": "Python oneliner",
      "user": "StikS32",
      "upvotes": 5,
      "views": 322,
      "problem_title": "root equals sum of children",
      "number": 2236,
      "acceptance": 0.8690000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 30983,
      "question": "You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.\nReturn true if the value of the root is equal to the sum of the values of its two children, or false otherwise.\n  Example 1:\nInput: root = [10,4,6]\nOutput: true\nExplanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n10 is equal to 4 + 6, so we return true.\nExample 2:\nInput: root = [5,3,1]\nOutput: false\nExplanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n5 is not equal to 3 + 1, so we return false.\n  Constraints:\nThe tree consists only of the root, its left child, and its right child.\n-100 <= Node.val <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/find-closest-number-to-zero/discuss/1959624/Python-dollarolution",
      "python_solutions": "class Solution:\n    def findClosestNumber(self, nums: List[int]) -> int:\n        m = 10 ** 6\n        for i in nums:\n            x = abs(i-0)\n            if x < m:\n                m = x\n                val = i\n            elif x == m and val < i:\n                val = i\n        return val",
      "slug": "find-closest-number-to-zero",
      "post_title": "Python $olution",
      "user": "AakRay",
      "upvotes": 2,
      "views": 180,
      "problem_title": "find closest number to zero",
      "number": 2239,
      "acceptance": 0.4579999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 30998,
      "question": "Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.\n  Example 1:\nInput: nums = [-4,-2,1,4,8]\nOutput: 1\nExplanation:\nThe distance from -4 to 0 is |-4| = 4.\nThe distance from -2 to 0 is |-2| = 2.\nThe distance from 1 to 0 is |1| = 1.\nThe distance from 4 to 0 is |4| = 4.\nThe distance from 8 to 0 is |8| = 8.\nThus, the closest number to 0 in the array is 1.\nExample 2:\nInput: nums = [2,-1,1]\nOutput: 1\nExplanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.\n  Constraints:\n1 <= n <= 1000\n-105 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/1962778/Python-easy-solution-faster-than-90",
      "python_solutions": "class Solution:\n    def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:\n        if total < cost1 and total < cost2:\n            return 1\n        ways = 0\n        if cost1 > cost2:\n            for i in range(0, (total // cost1)+1):\n                rem = total - (i * cost1)\n                ways += (rem // cost2) + 1\n            return ways\n        for i in range(0, (total // cost2)+1):\n            rem = total - (i * cost2)\n            ways += (rem // cost1) + 1\n        return ways",
      "slug": "number-of-ways-to-buy-pens-and-pencils",
      "post_title": "Python easy solution faster than 90%",
      "user": "alishak1999",
      "upvotes": 2,
      "views": 84,
      "problem_title": "number of ways to buy pens and pencils",
      "number": 2240,
      "acceptance": 0.57,
      "difficulty": "Medium",
      "__index_level_0__": 31026,
      "question": "You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil.\nReturn the number of distinct ways you can buy some number of pens and pencils.\n  Example 1:\nInput: total = 20, cost1 = 10, cost2 = 5\nOutput: 9\nExplanation: The price of a pen is 10 and the price of a pencil is 5.\n- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.\n- If you buy 1 pen, you can buy 0, 1, or 2 pencils.\n- If you buy 2 pens, you cannot buy any pencils.\nThe total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.\nExample 2:\nInput: total = 5, cost1 = 10, cost2 = 10\nOutput: 1\nExplanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.\n  Constraints:\n1 <= total, cost1, cost2 <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-score-of-a-node-sequence/discuss/1984916/Python3-O(orEor)-solution",
      "python_solutions": "class Solution:\n    def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n      \n      connection = {}\n      \n      for source, target in edges:\n        if source not in connection: connection[source] = [target]\n        else: connection[source].append(target)\n          \n        if target not in connection: connection[target] = [source]\n        else: connection[target].append(source)\n          \n      res = -1\n      \n      max_dict = {}\n      for key, value in connection.items():\n        max1, max2, max3 = -sys.maxsize, -sys.maxsize, -sys.maxsize\n        n1, n2, n3 = None, None, None\n        for element in value:\n          if scores[element] > max1:\n            max1, max2, max3 = scores[element], max1, max2\n            n1, n2, n3 = element, n1, n2\n          elif scores[element] > max2:\n            max2, max3 = scores[element], max2\n            n2, n3 = element, n2\n          elif scores[element] > max3:\n            max3 = scores[element]\n            n3 = element\n        max_dict[key] = []\n        if n1 != None: max_dict[key].append(n1)\n        if n2 != None: max_dict[key].append(n2)\n        if n3 != None: max_dict[key].append(n3)\n             \n      for source, target in edges:\n        base = scores[source] + scores[target]\n        \n        n_s = max_dict[source]\n        n_t = max_dict[target]\n        if len(n_s) == 1 or len(n_t) == 1:\n          pass\n        else:\n          new_n_s = [x for x in n_s if x != target]\n          new_n_t = [x for x in n_t if x != source]\n          if new_n_s[0] != new_n_t[0]:\n            res = max(res, base + scores[new_n_s[0]] + scores[new_n_t[0]])\n          else:\n            if len(new_n_s) > 1:\n              res = max(res, base + scores[new_n_s[1]] + scores[new_n_t[0]])\n            if len(new_n_t) > 1:\n              res = max(res, base + scores[new_n_s[0]] + scores[new_n_t[1]])      \n    \n      return res",
      "slug": "maximum-score-of-a-node-sequence",
      "post_title": "Python3 O(|E|) solution",
      "user": "xxHRxx",
      "upvotes": 2,
      "views": 239,
      "problem_title": "maximum score of a node sequence",
      "number": 2242,
      "acceptance": 0.375,
      "difficulty": "Hard",
      "__index_level_0__": 31037,
      "question": "There is an undirected graph with n nodes, numbered from 0 to n - 1.\nYou are given a 0-indexed integer array scores of length n where scores[i] denotes the score of node i. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.\nA node sequence is valid if it meets the following conditions:\nThere is an edge connecting every pair of adjacent nodes in the sequence.\nNo node appears more than once in the sequence.\nThe score of a node sequence is defined as the sum of the scores of the nodes in the sequence.\nReturn the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1.\n  Example 1:\nInput: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput: 24\nExplanation: The figure above shows the graph and the chosen node sequence [0,1,2,3].\nThe score of the node sequence is 5 + 2 + 9 + 8 = 24.\nIt can be shown that no other node sequence has a score of more than 24.\nNote that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\nThe sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.\nExample 2:\nInput: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]\nOutput: -1\nExplanation: The figure above shows the graph.\nThere are no valid node sequences of length 4, so we return -1.\n  Constraints:\nn == scores.length\n4 <= n <= 5 * 104\n1 <= scores[i] <= 108\n0 <= edges.length <= 5 * 104\nedges[i].length == 2\n0 <= ai, bi <= n - 1\nai != bi\nThere are no duplicate edges."
    },
    {
      "post_href": "https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1955460/Python3-elegant-pythonic-clean-and-easy-to-understand",
      "python_solutions": "class Solution:\n    def digitSum(self, s: str, k: int) -> str:\n        while len(s) > k:\n            set_3 = [s[i:i+k] for i in range(0, len(s), k)]\n            s = ''\n            for e in set_3:\n                val = 0\n                for n in e:\n                    val += int(n)\n                s += str(val)\n        return s",
      "slug": "calculate-digit-sum-of-a-string",
      "post_title": "Python3 elegant pythonic clean and easy to understand",
      "user": "Tallicia",
      "upvotes": 10,
      "views": 881,
      "problem_title": "calculate digit sum of a string",
      "number": 2243,
      "acceptance": 0.6679999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 31038,
      "question": "You are given a string s consisting of digits and an integer k.\nA round can be completed if the length of s is greater than k. In one round, do the following:\nDivide s into consecutive groups of size k such that the first k characters are in the first group, the next k characters are in the second group, and so on. Note that the size of the last group can be smaller than k.\nReplace each group of s with a string representing the sum of all its digits. For example, \"346\" is replaced with \"13\" because 3 + 4 + 6 = 13.\nMerge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.\nReturn s after all rounds have been completed.\n  Example 1:\nInput: s = \"11111222223\", k = 3\nOutput: \"135\"\nExplanation: \n- For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n  Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5. \n  So, s becomes \"3\" + \"4\" + \"6\" + \"5\" = \"3465\" after the first round.\n- For the second round, we divide s into \"346\" and \"5\".\n  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5. \n  So, s becomes \"13\" + \"5\" = \"135\" after second round. \nNow, s.length <= k, so we return \"135\" as the answer.\nExample 2:\nInput: s = \"00000000\", k = 3\nOutput: \"000\"\nExplanation: \nWe divide s into \"000\", \"000\", and \"00\".\nThen we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \ns becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".\n  Constraints:\n1 <= s.length <= 100\n2 <= k <= 100\ns consists of digits only."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-rounds-to-complete-all-tasks/discuss/1955367/Well-Explained-Python-Solution",
      "python_solutions": "class Solution:\n    def minimumRounds(self, tasks: List[int]) -> int:\n        table, res = Counter(tasks), 0 # Counter to hold frequency of ith task and res stores the result.\n        for count in table.values():\n            if count <= 1: return -1 # If count <= 1 then it cannot follow the condition hence return -1.\n            res += ceil(count / 3) # Total number of groups increments after 3 values. \n        return res",
      "slug": "minimum-rounds-to-complete-all-tasks",
      "post_title": "\u2b50 Well Explained Python Solution",
      "user": "anCoderr",
      "upvotes": 4,
      "views": 184,
      "problem_title": "minimum rounds to complete all tasks",
      "number": 2244,
      "acceptance": 0.575,
      "difficulty": "Medium",
      "__index_level_0__": 31071,
      "question": "You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the same difficulty level.\nReturn the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.\n  Example 1:\nInput: tasks = [2,2,3,3,2,4,4,4,4,4]\nOutput: 4\nExplanation: To complete all the tasks, a possible plan is:\n- In the first round, you complete 3 tasks of difficulty level 2. \n- In the second round, you complete 2 tasks of difficulty level 3. \n- In the third round, you complete 3 tasks of difficulty level 4. \n- In the fourth round, you complete 2 tasks of difficulty level 4.  \nIt can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.\nExample 2:\nInput: tasks = [2,3,3]\nOutput: -1\nExplanation: There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.\n  Constraints:\n1 <= tasks.length <= 105\n1 <= tasks[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-trailing-zeros-in-a-cornered-path/discuss/1955502/Python-Prefix-Sum-O(m-*-n)",
      "python_solutions": "class Solution:\n    def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n        ans = 0\n        m, n = len(grid), len(grid[0])\n        prefixH = [[[0] * 2 for _ in range(n + 1)] for __ in range(m)]\n        prefixV = [[[0] * 2 for _ in range(n)] for __ in range(m + 1)]\n        for i in range(m):\n            for j in range(n):\n                temp= grid[i][j]\n                while temp % 2 == 0:\n                    prefixH[i][j + 1][0] += 1\n                    prefixV[i + 1][j][0] += 1\n                    temp //= 2\n                while temp % 5 == 0:\n                    prefixH[i][j + 1][1] += 1\n                    prefixV[i + 1][j][1] += 1\n                    temp //= 5\n                for k in range(2):\n                    prefixH[i][j + 1][k] += prefixH[i][j][k]\n                    prefixV[i + 1][j][k] += prefixV[i][j][k]\n        for i in range(m):\n            for j in range(n):\n                left = prefixH[i][j]\n                up = prefixV[i][j]\n                right, down, center = [0] * 2, [0] * 2, [0] * 2\n                for k in range(2):\n                    right[k] = prefixH[i][n][k] - prefixH[i][j + 1][k]\n                    down[k] = prefixV[m][j][k] - prefixV[i + 1][j][k]\n                    center[k] = prefixH[i][j + 1][k] - prefixH[i][j][k]\n                LU, LD, RU, RD = [0] * 2, [0] * 2, [0] * 2, [0] * 2\n                for k in range(2):\n                    LU[k] += left[k] + up[k] + center[k]\n                    LD[k] += left[k] + down[k] + center[k]\n                    RU[k] += right[k] + up[k] + center[k]\n                    RD[k] += right[k] + down[k] + center[k]\n                ans = max(ans,\n                          min(LU[0], LU[1]),\n                          min(LD[0], LD[1]),\n                          min(RU[0], RU[1]),\n                          min(RD[0], RD[1]))\n        return ans",
      "slug": "maximum-trailing-zeros-in-a-cornered-path",
      "post_title": "[Python] Prefix Sum, O(m * n)",
      "user": "xil899",
      "upvotes": 7,
      "views": 574,
      "problem_title": "maximum trailing zeros in a cornered path",
      "number": 2245,
      "acceptance": 0.35,
      "difficulty": "Medium",
      "__index_level_0__": 31090,
      "question": "You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.\nA cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.\nThe product of a path is defined as the product of all the values in the path.\nReturn the maximum number of trailing zeros in the product of a cornered path found in grid.\nNote:\nHorizontal movement means moving in either the left or right direction.\nVertical movement means moving in either the up or down direction.\n  Example 1:\nInput: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]\nOutput: 3\nExplanation: The grid on the left shows a valid cornered path.\nIt has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\nIt can be shown that this is the maximum trailing zeros in the product of a cornered path.\n\nThe grid in the middle is not a cornered path as it has more than one turn.\nThe grid on the right is not a cornered path as it requires a return to a previously visited cell.\nExample 2:\nInput: grid = [[4,3,2],[7,6,1],[8,8,8]]\nOutput: 0\nExplanation: The grid is shown in the figure above.\nThere are no cornered paths in the grid that result in a product with a trailing zero.\n  Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 105\n1 <= m * n <= 105\n1 <= grid[i][j] <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-path-with-different-adjacent-characters/discuss/2494179/Python-oror-Faster-than-100-oror-Simple-DFS-oror-Easy-Explanation",
      "python_solutions": "class Solution:\n    def longestPath(self, par: List[int], s: str) -> int:\n        dit = {}\n        # store tree in dictionary\n        for i in range(len(par)):\n            if par[i] in dit:\n                dit[par[i]].append(i)\n            else:\n                dit[par[i]] = [i]\n                \n        ans = 1        \n        def dfs(n):\n            nonlocal ans\n            if n not in dit:\n                return 1\n            \n            largest=0 # largest path lenght among all children\n            second_largest=0 # second largest path lenght among all children\n            for u in dit[n]:\n                curr = dfs(u)\n                if s[u]!=s[n]: # pick child path if child and parent both have different value\n                    if curr>largest:\n                        second_largest = largest\n                        largest = curr\n                    elif curr>second_largest:\n                        second_largest = curr\n                        \n            ans = max(ans,largest+second_largest+1) # largest path including parent with at most two children \n            \n            return largest+1  # return largest path end at parent\n        \n        dfs(0)\n        return ans\n        ```",
      "slug": "longest-path-with-different-adjacent-characters",
      "post_title": "Python || Faster than 100% || Simple DFS || Easy Explanation",
      "user": "Laxman_Singh_Saini",
      "upvotes": 10,
      "views": 359,
      "problem_title": "longest path with different adjacent characters",
      "number": 2246,
      "acceptance": 0.4529999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 31094,
      "question": "You are given a tree (i.e. a connected, undirected graph that has no cycles) rooted at node 0 consisting of n nodes numbered from 0 to n - 1. The tree is represented by a 0-indexed array parent of size n, where parent[i] is the parent of node i. Since node 0 is the root, parent[0] == -1.\nYou are also given a string s of length n, where s[i] is the character assigned to node i.\nReturn the length of the longest path in the tree such that no pair of adjacent nodes on the path have the same character assigned to them.\n  Example 1:\nInput: parent = [-1,0,0,1,1,2], s = \"abacbe\"\nOutput: 3\nExplanation: The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.\nIt can be proven that there is no longer path that satisfies the conditions. \nExample 2:\nInput: parent = [-1,0,0,0], s = \"aabc\"\nOutput: 3\nExplanation: The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.\n  Constraints:\nn == parent.length == s.length\n1 <= n <= 105\n0 <= parent[i] <= n - 1 for all i >= 1\nparent[0] == -1\nparent represents a valid tree.\ns consists of only lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/intersection-of-multiple-arrays/discuss/2428232/94.58-faster-using-set-and-and-operator-in-Python",
      "python_solutions": "class Solution:\n    def intersection(self, nums: List[List[int]]) -> List[int]:\n        res = set(nums[0])\n        for i in range(1, len(nums)):\n            res &= set(nums[i])\n        res = list(res)\n        res.sort()\n        return res",
      "slug": "intersection-of-multiple-arrays",
      "post_title": "94.58% faster using set and & operator in Python",
      "user": "ankurbhambri",
      "upvotes": 6,
      "views": 172,
      "problem_title": "intersection of multiple arrays",
      "number": 2248,
      "acceptance": 0.695,
      "difficulty": "Easy",
      "__index_level_0__": 31101,
      "question": "Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.\n  Example 1:\nInput: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]\nOutput: [3,4]\nExplanation: \nThe only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].\nExample 2:\nInput: nums = [[1,2,3],[4,5,6]]\nOutput: []\nExplanation: \nThere does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].\n  Constraints:\n1 <= nums.length <= 1000\n1 <= sum(nums[i].length) <= 1000\n1 <= nums[i][j] <= 1000\nAll the values of nums[i] are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/count-lattice-points-inside-a-circle/discuss/1977094/Python-Math-(Geometry)-and-Set-Solution-No-Brute-Force",
      "python_solutions": "class Solution:\n    def countLatticePoints(self, circles: List[List[int]]) -> int:\n        points = set()\n        for x, y, r in circles:\n            for dx in range(-r, r + 1, 1):\n                temp = math.floor(math.sqrt(r ** 2 - dx ** 2))\n                for dy in range(-temp, temp + 1):\n                    points.add((x + dx, y + dy))\n        return len(points)",
      "slug": "count-lattice-points-inside-a-circle",
      "post_title": "[Python] Math (Geometry) and Set Solution, No Brute Force",
      "user": "xil899",
      "upvotes": 1,
      "views": 60,
      "problem_title": "count lattice points inside a circle",
      "number": 2249,
      "acceptance": 0.503,
      "difficulty": "Medium",
      "__index_level_0__": 31147,
      "question": "Given a 2D integer array circles where circles[i] = [xi, yi, ri] represents the center (xi, yi) and radius ri of the ith circle drawn on a grid, return the number of lattice points that are present inside at least one circle.\nNote:\nA lattice point is a point with integer coordinates.\nPoints that lie on the circumference of a circle are also considered to be inside it.\n  Example 1:\nInput: circles = [[2,2,1]]\nOutput: 5\nExplanation:\nThe figure above shows the given circle.\nThe lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\nOther points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\nHence, the number of lattice points present inside at least one circle is 5.\nExample 2:\nInput: circles = [[2,2,2],[3,4,1]]\nOutput: 16\nExplanation:\nThe figure above shows the given circles.\nThere are exactly 16 lattice points which are present inside at least one circle. \nSome of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).\n  Constraints:\n1 <= circles.length <= 200\ncircles[i].length == 3\n1 <= xi, yi <= 100\n1 <= ri <= min(xi, yi)"
    },
    {
      "post_href": "https://leetcode.com/problems/count-number-of-rectangles-containing-each-point/discuss/1980349/Python3-binary-search",
      "python_solutions": "class Solution:\n    def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n        mp = defaultdict(list)\n        for l, h in rectangles: mp[h].append(l)\n        for v in mp.values(): v.sort()\n        ans = []\n        for x, y in points: \n            cnt = 0 \n            for yy in range(y, 101): \n                if yy in mp: cnt += len(mp[yy]) - bisect_left(mp[yy], x)\n            ans.append(cnt)\n        return ans",
      "slug": "count-number-of-rectangles-containing-each-point",
      "post_title": "[Python3] binary search",
      "user": "ye15",
      "upvotes": 3,
      "views": 55,
      "problem_title": "count number of rectangles containing each point",
      "number": 2250,
      "acceptance": 0.341,
      "difficulty": "Medium",
      "__index_level_0__": 31154,
      "question": "You are given a 2D integer array rectangles where rectangles[i] = [li, hi] indicates that ith rectangle has a length of li and a height of hi. You are also given a 2D integer array points where points[j] = [xj, yj] is a point with coordinates (xj, yj).\nThe ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi).\nReturn an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point.\nThe ith rectangle contains the jth point if 0 <= xj <= li and 0 <= yj <= hi. Note that points that lie on the edges of a rectangle are also considered to be contained by that rectangle.\n  Example 1:\nInput: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]\nOutput: [2,1]\nExplanation: \nThe first rectangle contains no points.\nThe second rectangle contains only the point (2, 1).\nThe third rectangle contains the points (2, 1) and (1, 4).\nThe number of rectangles that contain the point (2, 1) is 2.\nThe number of rectangles that contain the point (1, 4) is 1.\nTherefore, we return [2, 1].\nExample 2:\nInput: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]\nOutput: [1,3]\nExplanation:\nThe first rectangle contains only the point (1, 1).\nThe second rectangle contains only the point (1, 1).\nThe third rectangle contains the points (1, 3) and (1, 1).\nThe number of rectangles that contain the point (1, 3) is 1.\nThe number of rectangles that contain the point (1, 1) is 3.\nTherefore, we return [1, 3].\n  Constraints:\n1 <= rectangles.length, points.length <= 5 * 104\nrectangles[i].length == points[j].length == 2\n1 <= li, xj <= 109\n1 <= hi, yj <= 100\nAll the rectangles are unique.\nAll the points are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-flowers-in-full-bloom/discuss/2757459/Binary-Search-with-Explanation-Fast-and-Easy-Solution",
      "python_solutions": "class Solution:\n    def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:\n        start, end, res = [], [], []\n        for i in flowers:\n            start.append(i[0])\n            end.append(i[1])\n        start.sort() #bisect only works with sorted data\n        end.sort()\n\n        for p in persons:\n            num = bisect_right(start, p) - bisect_left(end, p)\n            res.append(num)\n        return res\n#bisect_right(start, p) gives you the number of flowers that are in full bloom at person p.\n#bisect_left(end, p) gives you number of flowers that are not in full bloom at person p.\n#we have to tighten our bound to get exact number of flowers that are in bloom or not, thats why we are using right and left of bisect module.",
      "slug": "number-of-flowers-in-full-bloom",
      "post_title": "Binary Search with Explanation - Fast and Easy Solution",
      "user": "user6770yv",
      "upvotes": 0,
      "views": 2,
      "problem_title": "number of flowers in full bloom",
      "number": 2251,
      "acceptance": 0.519,
      "difficulty": "Hard",
      "__index_level_0__": 31158,
      "question": "You are given a 0-indexed 2D integer array flowers, where flowers[i] = [starti, endi] means the ith flower will be in full bloom from starti to endi (inclusive). You are also given a 0-indexed integer array people of size n, where people[i] is the time that the ith person will arrive to see the flowers.\nReturn an integer array answer of size n, where answer[i] is the number of flowers that are in full bloom when the ith person arrives.\n  Example 1:\nInput: flowers = [[1,6],[3,7],[9,12],[4,13]], people = [2,3,7,11]\nOutput: [1,2,2,2]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\nExample 2:\nInput: flowers = [[1,10],[3,3]], people = [3,3,2]\nOutput: [2,2,1]\nExplanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\nFor each person, we return the number of flowers in full bloom during their arrival.\n  Constraints:\n1 <= flowers.length <= 5 * 104\nflowers[i].length == 2\n1 <= starti <= endi <= 109\n1 <= people.length <= 5 * 104\n1 <= people[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/count-prefixes-of-a-given-string/discuss/2076295/Easy-python-solution",
      "python_solutions": "class Solution:\n    def countPrefixes(self, words: List[str], s: str) -> int:\n        count=0\n        for i in words:\n            if (s[:len(i)]==i):\n                count+=1\n        return count",
      "slug": "count-prefixes-of-a-given-string",
      "post_title": "Easy python solution",
      "user": "tusharkhanna575",
      "upvotes": 9,
      "views": 336,
      "problem_title": "count prefixes of a given string",
      "number": 2255,
      "acceptance": 0.7340000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 31166,
      "question": "You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.\nReturn the number of strings in words that are a prefix of s.\nA prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.\n  Example 1:\nInput: words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"\nOutput: 3\nExplanation:\nThe strings in words which are a prefix of s = \"abc\" are:\n\"a\", \"ab\", and \"abc\".\nThus the number of strings in words which are a prefix of s is 3.\nExample 2:\nInput: words = [\"a\",\"a\"], s = \"aa\"\nOutput: 2\nExplanation:\nBoth of the strings are a prefix of s. \nNote that the same string can occur multiple times in words, and it should be counted each time.\n  Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length, s.length <= 10\nwords[i] and s consist of lowercase English letters only."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-average-difference/discuss/2098497/PYTHON-oror-EASY-oror-BEGINER-FRIENDLY",
      "python_solutions": "class Solution:\n    def minimumAverageDifference(self, a: List[int]) -> int:\n        l=0\n        r=sum(a)\n        z=100001\n        y=0\n        n=len(a)\n        \n        for i in range(n-1):\n            l+=a[i]\n            r-=a[i]\n        \n            d=abs((l//(i+1))-(r//(n-i-1)))\n            if d int:\n        vis = [[0]*n for _ in range(m)]\n        # i - rows, j - colums\n        # sum(row.count('hit') for row in grid)\n        for i,j in walls:\n            vis[i][j] = 2\n        for i,j in guards:\n            vis[i][j] = 2\n        for i,j in guards:\n            for l in range(j-1,-1,-1):\n                if self.checkWall(i,l,vis):\n                    break    \n                vis[i][l] = 1\n            for r in range(j+1,n):\n                if self.checkWall(i,r,vis):\n                    break\n                vis[i][r] = 1\n            for u in range(i-1,-1,-1):\n                if self.checkWall(u,j,vis):\n                    break\n                vis[u][j] = 1\n            for d in range(i+1,m):\n                if self.checkWall(d,j, vis):\n                    break\n                vis[d][j] = 1\n        return sum(row.count(0) for row in vis)\n        \n    def checkWall(self, i, j, vis):\n        if vis[i][j] ==2:\n            return True",
      "slug": "count-unguarded-cells-in-the-grid",
      "post_title": "Simple python code",
      "user": "beast316",
      "upvotes": 1,
      "views": 37,
      "problem_title": "count unguarded cells in the grid",
      "number": 2257,
      "acceptance": 0.522,
      "difficulty": "Medium",
      "__index_level_0__": 31211,
      "question": "You are given two integers m and n representing a 0-indexed m x n grid. You are also given two 2D integer arrays guards and walls where guards[i] = [rowi, coli] and walls[j] = [rowj, colj] represent the positions of the ith guard and jth wall respectively.\nA guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it.\nReturn the number of unoccupied cells that are not guarded.\n  Example 1:\nInput: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]\nOutput: 7\nExplanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.\nThere are a total of 7 unguarded cells, so we return 7.\nExample 2:\nInput: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]\nOutput: 4\nExplanation: The unguarded cells are shown in green in the above diagram.\nThere are a total of 4 unguarded cells, so we return 4.\n  Constraints:\n1 <= m, n <= 105\n2 <= m * n <= 105\n1 <= guards.length, walls.length <= 5 * 104\n2 <= guards.length + walls.length <= m * n\nguards[i].length == walls[j].length == 2\n0 <= rowi, rowj < m\n0 <= coli, colj < n\nAll the positions in guards and walls are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/escape-the-spreading-fire/discuss/2005513/Python3-BFS-%2B-DFS-%2B-Binary-Search-Solution",
      "python_solutions": "class Solution:\n    def maximumMinutes(self, grid: List[List[int]]) -> int:\n      \n      #region growing to assign each grass with the time that it will catch fire\n      \n      m, n = len(grid), len(grid[0])\n      \n      start = []\n      \n      for i in range(m):\n        for j in range(n):\n          if grid[i][j] == 1:\n            start.append([i,j])\n            grid[i][j] = 'F'\n          elif grid[i][j] == 2:\n            grid[i][j] = 'W'\n            \n      visited = set()\n      for element in start: visited.add(tuple(element))\n        \n      time = 1\n      \n      while start:\n        new_start = []\n        for x, y in start:\n          if x >= 1:\n            if grid[x-1][y] == 0 and (x-1, y) not in visited:\n              new_start.append([x-1, y])\n              visited.add((x-1, y))\n              grid[x-1][y] = time\n          if x < m-1:\n            if grid[x+1][y] == 0 and (x+1, y) not in visited:\n              new_start.append([x+1, y])\n              visited.add((x+1, y))\n              grid[x+1][y] = time\n          if y >= 1:\n            if grid[x][y-1] == 0 and (x, y-1) not in visited:\n              new_start.append([x, y-1])\n              visited.add((x, y-1))\n              grid[x][y-1] = time\n          if y < n-1:\n            if grid[x][y+1] == 0 and (x, y+1) not in visited:\n              new_start.append([x, y+1])\n              visited.add((x, y+1))\n              grid[x][y+1] = time\n        time += 1\n        start = new_start\n        \n        \n      #memo variable will save time from search path that is already proved to be impossible\n      memo = {}\n      def search(x, y, time, visited):\n        if (x,y) in memo and time >= memo[(x,y)]: return False\n        if time > grid[-1][-1]: return False\n        if x == m-1 and y == n-1:\n          if grid[x][y] == 0:\n            return True\n          else: \n            if grid[x][y] >= time:\n              return True\n        else:\n          if grid[x][y] == time: return False\n          visited.add((x,y))\n          if x >= 1:\n            if grid[x-1][y] != 'W' and grid[x-1][y] != 'F' and grid[x-1][y] > time  and (x-1, y) not in visited:\n              res = search(x-1, y, time+1, visited)\n              if res: return True\n          if x < m-1:\n            if grid[x+1][y] != 'W' and grid[x+1][y] != 'F' and grid[x+1][y] > time  and (x+1, y) not in visited:\n              res = search(x+1, y, time+1, visited)\n              if res: return True\n          if y >= 1:\n            if grid[x][y-1] != 'W' and grid[x][y-1] != 'F' and grid[x][y-1] > time  and (x, y-1) not in visited:\n              res = search(x, y-1, time+1, visited)\n              if res: return True\n          if y < n-1:\n            if grid[x][y+1] != 'W' and grid[x][y+1] != 'F' and grid[x][y+1] > time  and (x, y+1) not in visited:\n              res = search(x, y+1, time+1, visited)\n              if res: return True\n          visited.remove((x,y))\n          if (x,y) not in memo: memo[(x,y)] = time\n          else: memo[(x,y)] = min(time, memo[(x,y)])\n          return False\n        \n      if grid[0][0] == 0:\n        if search(0, 0, -sys.maxsize, set()): return 10**9\n        else: return -1\n      else:\n        start, end = 0, grid[0][0]-1\n        \n        #binary search\n \n        while start < end:\n          mid = ceil((start + end)/2)\n          if search(0, 0, mid, set()):\n            start = mid\n          else:\n            end = mid - 1\n        if start != 0: return start\n        else:\n          if search(0, 0, 0, set()): return 0\n          else: return -1",
      "slug": "escape-the-spreading-fire",
      "post_title": "Python3 BFS + DFS + Binary Search Solution",
      "user": "xxHRxx",
      "upvotes": 0,
      "views": 44,
      "problem_title": "escape the spreading fire",
      "number": 2258,
      "acceptance": 0.347,
      "difficulty": "Hard",
      "__index_level_0__": 31221,
      "question": "You are given a 0-indexed 2D integer array grid of size m x n which represents a field. Each cell has one of three values:\n0 represents grass,\n1 represents fire,\n2 represents a wall that you and fire cannot pass through.\nYou are situated in the top-left cell, (0, 0), and you want to travel to the safehouse at the bottom-right cell, (m - 1, n - 1). Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls.\nReturn the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return -1. If you can always reach the safehouse regardless of the minutes stayed, return 109.\nNote that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.\nA cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n  Example 1:\nInput: grid = [[0,2,0,0,0,0,0],[0,0,0,2,2,1,0],[0,2,0,0,1,2,0],[0,0,2,2,2,0,2],[0,0,0,0,0,0,0]]\nOutput: 3\nExplanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.\nYou will still be able to safely reach the safehouse.\nStaying for more than 3 minutes will not allow you to safely reach the safehouse.\nExample 2:\nInput: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\nOutput: -1\nExplanation: The figure above shows the scenario where you immediately move towards the safehouse.\nFire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\nThus, -1 is returned.\nExample 3:\nInput: grid = [[0,0,0],[2,2,0],[1,2,0]]\nOutput: 1000000000\nExplanation: The figure above shows the initial grid.\nNotice that the fire is contained by walls and you will always be able to safely reach the safehouse.\nThus, 109 is returned.\n  Constraints:\nm == grid.length\nn == grid[i].length\n2 <= m, n <= 300\n4 <= m * n <= 2 * 104\ngrid[i][j] is either 0, 1, or 2.\ngrid[0][0] == grid[m - 1][n - 1] == 0"
    },
    {
      "post_href": "https://leetcode.com/problems/remove-digit-from-number-to-maximize-result/discuss/2074599/Python-O(N)-solution-oror-Faster-than-99-submissions-oror-Detailed-explanation.",
      "python_solutions": "class Solution:\n    def removeDigit(self, number: str, digit: str) -> str:\n        \n        # Initializing the last index as zero\n        last_index = 0\n        \n        #iterating each number to find the occurences, \\\n        # and to find if the number is greater than the next element \\ \n\n        for num in range(1, len(number)):\n            \n            # Handling [case 1] and [case 2]\n            if number[num-1] == digit:\n                if int(number[num]) > int(number[num-1]):\n                    return number[:num-1] + number[num:]\n                else:\n                    last_index = num - 1\n        \n        # If digit is the last number (last occurence) in the string [case 3]\n        if number[-1] == digit:\n            last_index = len(number) - 1\n\n        return number[:last_index] + number[last_index + 1:]",
      "slug": "remove-digit-from-number-to-maximize-result",
      "post_title": "\ud83d\udd25\ud83d\udd25\ud83d\udd25Python O(N) solution || Faster than 99% submissions || Detailed explanation.",
      "user": "litdatascience",
      "upvotes": 16,
      "views": 1400,
      "problem_title": "remove digit from number to maximize result",
      "number": 2259,
      "acceptance": 0.47,
      "difficulty": "Easy",
      "__index_level_0__": 31224,
      "question": "You are given a string number representing a positive integer and a character digit.\nReturn the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.\n  Example 1:\nInput: number = \"123\", digit = \"3\"\nOutput: \"12\"\nExplanation: There is only one '3' in \"123\". After removing '3', the result is \"12\".\nExample 2:\nInput: number = \"1231\", digit = \"1\"\nOutput: \"231\"\nExplanation: We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\nSince 231 > 123, we return \"231\".\nExample 3:\nInput: number = \"551\", digit = \"5\"\nOutput: \"51\"\nExplanation: We can remove either the first or second '5' from \"551\".\nBoth result in the string \"51\".\n  Constraints:\n2 <= number.length <= 100\nnumber consists of digits from '1' to '9'.\ndigit is a digit from '1' to '9'.\ndigit occurs at least once in number."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-consecutive-cards-to-pick-up/discuss/1996393/Python3-or-Beginner-friendly-explained-or",
      "python_solutions": "class Solution:\n    def minimumCardPickup(self, cards: List[int]) -> int:\n        minPick = float('inf')\n        seen = {}\n        for i, n in enumerate(cards):\n            if n in seen:\n                if i - seen[n] + 1 < minPick:\n                    minPick = i - seen[n] + 1\n            seen[n] = i\n        if minPick == float('inf'):\n            return -1\n        return minPick",
      "slug": "minimum-consecutive-cards-to-pick-up",
      "post_title": "Python3 | Beginner-friendly explained |",
      "user": "hanjo108",
      "upvotes": 22,
      "views": 919,
      "problem_title": "minimum consecutive cards to pick up",
      "number": 2260,
      "acceptance": 0.517,
      "difficulty": "Medium",
      "__index_level_0__": 31251,
      "question": "You are given an integer array cards where cards[i] represents the value of the ith card. A pair of cards are matching if the cards have the same value.\nReturn the minimum number of consecutive cards you have to pick up to have a pair of matching cards among the picked cards. If it is impossible to have matching cards, return -1.\n  Example 1:\nInput: cards = [3,4,2,3,4,7]\nOutput: 4\nExplanation: We can pick up the cards [3,4,2,3] which contain a matching pair of cards with value 3. Note that picking up the cards [4,2,3,4] is also optimal.\nExample 2:\nInput: cards = [1,0,5,3]\nOutput: -1\nExplanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.\n  Constraints:\n1 <= cards.length <= 105\n0 <= cards[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/k-divisible-elements-subarrays/discuss/1996643/Python-Simple-Count-all-combinations",
      "python_solutions": "class Solution:\n    def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n        n = len(nums)                        \n        sub_arrays = set()\n        \n\t\t# generate all combinations of subarray\n        for start in range(n):\n            cnt = 0\n            temp = ''\n            for i in range(start, n):\n                if nums[i]%p == 0:\n                    cnt+=1                 \n                temp+=str(nums[i]) + ',' # build the sequence subarray in CSV format          \n                if cnt>k: # check for termination \n                    break\n                sub_arrays.add(temp)                                    \n                \n        return len(sub_arrays)",
      "slug": "k-divisible-elements-subarrays",
      "post_title": "\u2705 Python - Simple Count all combinations",
      "user": "constantine786",
      "upvotes": 20,
      "views": 885,
      "problem_title": "k divisible elements subarrays",
      "number": 2261,
      "acceptance": 0.476,
      "difficulty": "Medium",
      "__index_level_0__": 31275,
      "question": "Given an integer array nums and two integers k and p, return the number of distinct subarrays, which have at most k elements that are divisible by p.\nTwo arrays nums1 and nums2 are said to be distinct if:\nThey are of different lengths, or\nThere exists at least one index i where nums1[i] != nums2[i].\nA subarray is defined as a non-empty contiguous sequence of elements in an array.\n  Example 1:\nInput: nums = [2,3,3,2,2], k = 2, p = 2\nOutput: 11\nExplanation:\nThe elements at indices 0, 3, and 4 are divisible by p = 2.\nThe 11 distinct subarrays which have at most k = 2 elements divisible by 2 are:\n[2], [2,3], [2,3,3], [2,3,3,2], [3], [3,3], [3,3,2], [3,3,2,2], [3,2], [3,2,2], and [2,2].\nNote that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\nThe subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.\nExample 2:\nInput: nums = [1,2,3,4], k = 4, p = 1\nOutput: 10\nExplanation:\nAll element of nums are divisible by p = 1.\nAlso, every subarray of nums will have at most 4 elements that are divisible by 1.\nSince all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.\n  Constraints:\n1 <= nums.length <= 200\n1 <= nums[i], p <= 200\n1 <= k <= nums.length\n  Follow up:\nCan you solve this problem in O(n2) time complexity?"
    },
    {
      "post_href": "https://leetcode.com/problems/total-appeal-of-a-string/discuss/1996203/DP",
      "python_solutions": "class Solution:\n    def appealSum(self, s: str) -> int:\n        res, cur, prev = 0, 0, defaultdict(lambda: -1)\n        for i, ch in enumerate(s):\n            cur += i - prev[ch]\n            prev[ch] = i\n            res += cur\n        return res",
      "slug": "total-appeal-of-a-string",
      "post_title": "DP",
      "user": "votrubac",
      "upvotes": 245,
      "views": 10100,
      "problem_title": "total appeal of a string",
      "number": 2262,
      "acceptance": 0.583,
      "difficulty": "Hard",
      "__index_level_0__": 31287,
      "question": "The appeal of a string is the number of distinct characters found in the string.\nFor example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.\nGiven a string s, return the total appeal of all of its substrings.\nA substring is a contiguous sequence of characters within a string.\n  Example 1:\nInput: s = \"abbca\"\nOutput: 28\nExplanation: The following are the substrings of \"abbca\":\n- Substrings of length 1: \"a\", \"b\", \"b\", \"c\", \"a\" have an appeal of 1, 1, 1, 1, and 1 respectively. The sum is 5.\n- Substrings of length 2: \"ab\", \"bb\", \"bc\", \"ca\" have an appeal of 2, 1, 2, and 2 respectively. The sum is 7.\n- Substrings of length 3: \"abb\", \"bbc\", \"bca\" have an appeal of 2, 2, and 3 respectively. The sum is 7.\n- Substrings of length 4: \"abbc\", \"bbca\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 5: \"abbca\" has an appeal of 3. The sum is 3.\nThe total sum is 5 + 7 + 7 + 6 + 3 = 28.\nExample 2:\nInput: s = \"code\"\nOutput: 20\nExplanation: The following are the substrings of \"code\":\n- Substrings of length 1: \"c\", \"o\", \"d\", \"e\" have an appeal of 1, 1, 1, and 1 respectively. The sum is 4.\n- Substrings of length 2: \"co\", \"od\", \"de\" have an appeal of 2, 2, and 2 respectively. The sum is 6.\n- Substrings of length 3: \"cod\", \"ode\" have an appeal of 3 and 3 respectively. The sum is 6.\n- Substrings of length 4: \"code\" has an appeal of 4. The sum is 4.\nThe total sum is 4 + 6 + 6 + 4 = 20.\n  Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/largest-3-same-digit-number-in-string/discuss/2017786/Compare-with-2-previous",
      "python_solutions": "class Solution:\n    def largestGoodInteger(self, n: str) -> str:\n        return max(n[i-2:i+1] if n[i] == n[i - 1] == n[i - 2] else \"\" for i in range(2, len(n)))",
      "slug": "largest-3-same-digit-number-in-string",
      "post_title": "Compare with 2 previous",
      "user": "votrubac",
      "upvotes": 51,
      "views": 2300,
      "problem_title": "largest 3 same digit number in string",
      "number": 2264,
      "acceptance": 0.59,
      "difficulty": "Easy",
      "__index_level_0__": 31303,
      "question": "You are given a string num representing a large integer. An integer is good if it meets the following conditions:\nIt is a substring of num with length 3.\nIt consists of only one unique digit.\nReturn the maximum good integer as a string or an empty string \"\" if no such integer exists.\nNote:\nA substring is a contiguous sequence of characters within a string.\nThere may be leading zeroes in num or a good integer.\n  Example 1:\nInput: num = \"6777133339\"\nOutput: \"777\"\nExplanation: There are two distinct good integers: \"777\" and \"333\".\n\"777\" is the largest, so we return \"777\".\nExample 2:\nInput: num = \"2300019\"\nOutput: \"000\"\nExplanation: \"000\" is the only good integer.\nExample 3:\nInput: num = \"42352338\"\nOutput: \"\"\nExplanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.\n  Constraints:\n3 <= num.length <= 1000\nnum only consists of digits."
    },
    {
      "post_href": "https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/discuss/2017794/Python3-post-order-dfs",
      "python_solutions": "class Solution:\n    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n        \n        def fn(node): \n            nonlocal ans\n            if not node: return 0, 0 \n            ls, ln = fn(node.left)\n            rs, rn = fn(node.right)\n            s = node.val + ls + rs\n            n = 1 + ln + rn\n            if s//n == node.val: ans += 1\n            return s, n\n        \n        ans = 0 \n        fn(root)\n        return ans",
      "slug": "count-nodes-equal-to-average-of-subtree",
      "post_title": "[Python3] post-order dfs",
      "user": "ye15",
      "upvotes": 6,
      "views": 266,
      "problem_title": "count nodes equal to average of subtree",
      "number": 2265,
      "acceptance": 0.856,
      "difficulty": "Medium",
      "__index_level_0__": 31327,
      "question": "Given the root of a binary tree, return the number of nodes where the value of the node is equal to the average of the values in its subtree.\nNote:\nThe average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.\nA subtree of root is a tree consisting of root and all of its descendants.\n  Example 1:\nInput: root = [4,8,5,0,1,null,6]\nOutput: 5\nExplanation: \nFor the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\nFor the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\nFor the node with value 0: The average of its subtree is 0 / 1 = 0.\nFor the node with value 1: The average of its subtree is 1 / 1 = 1.\nFor the node with value 6: The average of its subtree is 6 / 1 = 6.\nExample 2:\nInput: root = [1]\nOutput: 1\nExplanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.\n  Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\n0 <= Node.val <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/count-number-of-texts/discuss/2017834/Python3-group-by-group",
      "python_solutions": "class Solution:\n    def countTexts(self, pressedKeys: str) -> int:\n        MOD = 1_000_000_007 \n        \n        @cache \n        def fn(n, k): \n            \"\"\"Return number of possible text of n repeated k times.\"\"\"\n            if n < 0: return 0\n            if n == 0: return 1\n            ans = 0\n            for x in range(1, k+1): ans = (ans + fn(n-x, k)) % MOD\n            return ans \n        \n        ans = 1\n        for key, grp in groupby(pressedKeys): \n            if key in \"79\": k = 4\n            else: k = 3\n            ans = (ans * fn(len(list(grp)), k)) % MOD \n        return ans",
      "slug": "count-number-of-texts",
      "post_title": "[Python3] group-by-group",
      "user": "ye15",
      "upvotes": 8,
      "views": 371,
      "problem_title": "count number of texts",
      "number": 2266,
      "acceptance": 0.473,
      "difficulty": "Medium",
      "__index_level_0__": 31339,
      "question": "Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.\nIn order to add a letter, Alice has to press the key of the corresponding digit i times, where i is the position of the letter in the key.\nFor example, to add the letter 's', Alice has to press '7' four times. Similarly, to add the letter 'k', Alice has to press '5' twice.\nNote that the digits '0' and '1' do not map to any letters, so Alice does not use them.\nHowever, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.\nFor example, when Alice sent the message \"bob\", Bob received the string \"2266622\".\nGiven a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.\nSince the answer may be very large, return it modulo 109 + 7.\n  Example 1:\nInput: pressedKeys = \"22233\"\nOutput: 8\nExplanation:\nThe possible text messages Alice could have sent are:\n\"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\nSince there are 8 possible messages, we return 8.\nExample 2:\nInput: pressedKeys = \"222222222222222222222222222222222222\"\nOutput: 82876089\nExplanation:\nThere are 2082876103 possible text messages Alice could have sent.\nSince we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.\n  Constraints:\n1 <= pressedKeys.length <= 105\npressedKeys only consists of digits from '2' - '9'."
    },
    {
      "post_href": "https://leetcode.com/problems/check-if-there-is-a-valid-parentheses-string-path/discuss/2018005/Python-Simple-MemoisationCaching",
      "python_solutions": "class Solution:\n    def hasValidPath(self, grid: List[List[str]]) -> bool:  \n        m = len(grid)\n        n = len(grid[0])\n        @lru_cache(maxsize=None)\n        def hasValidPathInner(x, y, cnt):\n            # cnt variable would act as a counter to track \n            # the balance of parantheses sequence\n            if x == m or y == n or cnt < 0:\n                return False\n            \n            # logic to check the balance of sequence\n            cnt += 1 if grid[x][y] == '(' else -1\n            \n            # if balanced and end of grid, return True\n            if x == m - 1 and y == n - 1 and not cnt:\n                return True\n            \n            return hasValidPathInner(x + 1, y, cnt) or hasValidPathInner(x, y + 1, cnt)\n\n        return hasValidPathInner(0, 0, 0)",
      "slug": "check-if-there-is-a-valid-parentheses-string-path",
      "post_title": "\u2705 Python Simple Memoisation/Caching",
      "user": "constantine786",
      "upvotes": 13,
      "views": 405,
      "problem_title": "check if there is a valid parentheses string path",
      "number": 2267,
      "acceptance": 0.38,
      "difficulty": "Hard",
      "__index_level_0__": 31346,
      "question": "A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:\nIt is ().\nIt can be written as AB (A concatenated with B), where A and B are valid parentheses strings.\nIt can be written as (A), where A is a valid parentheses string.\nYou are given an m x n matrix of parentheses grid. A valid parentheses string path in the grid is a path satisfying all of the following conditions:\nThe path starts from the upper left cell (0, 0).\nThe path ends at the bottom-right cell (m - 1, n - 1).\nThe path only ever moves down or right.\nThe resulting parentheses string formed by the path is valid.\nReturn true if there exists a valid parentheses string path in the grid. Otherwise, return false.\n  Example 1:\nInput: grid = [[\"(\",\"(\",\"(\"],[\")\",\"(\",\")\"],[\"(\",\"(\",\")\"],[\"(\",\"(\",\")\"]]\nOutput: true\nExplanation: The above diagram shows two possible paths that form valid parentheses strings.\nThe first path shown results in the valid parentheses string \"()(())\".\nThe second path shown results in the valid parentheses string \"((()))\".\nNote that there may be other valid parentheses string paths.\nExample 2:\nInput: grid = [[\")\",\")\"],[\"(\",\"(\"]]\nOutput: false\nExplanation: The two possible paths form the parentheses strings \"))(\" and \")((\". Since neither of them are valid parentheses strings, we return false.\n  Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 100\ngrid[i][j] is either '(' or ')'."
    },
    {
      "post_href": "https://leetcode.com/problems/find-the-k-beauty-of-a-number/discuss/2611592/Python-Elegant-and-Short-or-Sliding-window-or-O(log10(n))-time-or-O(1)-memory",
      "python_solutions": "class Solution:\n    \"\"\"\n    Time:   O(log10(n)*k)\n    Memory: O(log10(n))\n    \"\"\"\n\n    def divisorSubstrings(self, num: int, k: int) -> int:\n        str_num = str(num)\n        return sum(\n            num % int(str_num[i - k:i]) == 0\n            for i in range(k, len(str_num) + 1)\n            if int(str_num[i - k:i]) != 0\n        )",
      "slug": "find-the-k-beauty-of-a-number",
      "post_title": "Python Elegant & Short | Sliding window | O(log10(n)) time | O(1) memory",
      "user": "Kyrylo-Ktl",
      "upvotes": 3,
      "views": 211,
      "problem_title": "find the k beauty of a number",
      "number": 2269,
      "acceptance": 0.5670000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 31355,
      "question": "The k-beauty of an integer num is defined as the number of substrings of num when it is read as a string that meet the following conditions:\nIt has a length of k.\nIt is a divisor of num.\nGiven integers num and k, return the k-beauty of num.\nNote:\nLeading zeros are allowed.\n0 is not a divisor of any value.\nA substring is a contiguous sequence of characters in a string.\n  Example 1:\nInput: num = 240, k = 2\nOutput: 2\nExplanation: The following are the substrings of num of length k:\n- \"24\" from \"240\": 24 is a divisor of 240.\n- \"40\" from \"240\": 40 is a divisor of 240.\nTherefore, the k-beauty is 2.\nExample 2:\nInput: num = 430043, k = 2\nOutput: 2\nExplanation: The following are the substrings of num of length k:\n- \"43\" from \"430043\": 43 is a divisor of 430043.\n- \"30\" from \"430043\": 30 is not a divisor of 430043.\n- \"00\" from \"430043\": 0 is not a divisor of 430043.\n- \"04\" from \"430043\": 4 is not a divisor of 430043.\n- \"43\" from \"430043\": 43 is a divisor of 430043.\nTherefore, the k-beauty is 2.\n  Constraints:\n1 <= num <= 109\n1 <= k <= num.length (taking num as a string)"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-ways-to-split-array/discuss/2038567/Prefix-Sum",
      "python_solutions": "class Solution:\n    def waysToSplitArray(self, n: List[int]) -> int:\n        n = list(accumulate(n))\n        return sum(n[i] >= n[-1] - n[i] for i in range(len(n) - 1))",
      "slug": "number-of-ways-to-split-array",
      "post_title": "Prefix Sum",
      "user": "votrubac",
      "upvotes": 14,
      "views": 1100,
      "problem_title": "number of ways to split array",
      "number": 2270,
      "acceptance": 0.446,
      "difficulty": "Medium",
      "__index_level_0__": 31385,
      "question": "You are given a 0-indexed integer array nums of length n.\nnums contains a valid split at index i if the following are true:\nThe sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.\nThere is at least one element to the right of i. That is, 0 <= i < n - 1.\nReturn the number of valid splits in nums.\n  Example 1:\nInput: nums = [10,4,-8,7]\nOutput: 2\nExplanation: \nThere are three ways of splitting nums into two non-empty parts:\n- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 >= 3, i = 0 is a valid split.\n- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 >= -1, i = 1 is a valid split.\n- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 < 7, i = 2 is not a valid split.\nThus, the number of valid splits in nums is 2.\nExample 2:\nInput: nums = [2,3,1,0]\nOutput: 2\nExplanation: \nThere are two valid splits in nums:\n- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 >= 1, i = 1 is a valid split. \n- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 >= 0, i = 2 is a valid split.\n  Constraints:\n2 <= nums.length <= 105\n-105 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-white-tiles-covered-by-a-carpet/discuss/2148636/Python3-greedy",
      "python_solutions": "class Solution:\n    def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:\n        tiles.sort()\n        ans = ii = val = 0 \n        for i in range(len(tiles)): \n            hi = tiles[i][0] + carpetLen - 1\n            while ii < len(tiles) and tiles[ii][1] <= hi:\n                val += tiles[ii][1] - tiles[ii][0] + 1\n                ii += 1\n            partial = 0 \n            if ii < len(tiles): partial = max(0, hi - tiles[ii][0] + 1)\n            ans = max(ans, val + partial)\n            val -= tiles[i][1] - tiles[i][0] + 1\n        return ans",
      "slug": "maximum-white-tiles-covered-by-a-carpet",
      "post_title": "[Python3] greedy",
      "user": "ye15",
      "upvotes": 1,
      "views": 105,
      "problem_title": "maximum white tiles covered by a carpet",
      "number": 2271,
      "acceptance": 0.327,
      "difficulty": "Medium",
      "__index_level_0__": 31402,
      "question": "You are given a 2D integer array tiles where tiles[i] = [li, ri] represents that every tile j in the range li <= j <= ri is colored white.\nYou are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.\nReturn the maximum number of white tiles that can be covered by the carpet.\n  Example 1:\nInput: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10\nOutput: 9\nExplanation: Place the carpet starting on tile 10. \nIt covers 9 white tiles, so we return 9.\nNote that there may be other places where the carpet covers 9 white tiles.\nIt can be shown that the carpet cannot cover more than 9 white tiles.\nExample 2:\nInput: tiles = [[10,11],[1,1]], carpetLen = 2\nOutput: 2\nExplanation: Place the carpet starting on tile 10. \nIt covers 2 white tiles, so we return 2.\n  Constraints:\n1 <= tiles.length <= 5 * 104\ntiles[i].length == 2\n1 <= li <= ri <= 109\n1 <= carpetLen <= 109\nThe tiles are non-overlapping."
    },
    {
      "post_href": "https://leetcode.com/problems/substring-with-largest-variance/discuss/2148640/Python3-pairwise-prefix-sum",
      "python_solutions": "class Solution:\n    def largestVariance(self, s: str) -> int:\n        ans = 0 \n        seen = set(s)\n        for x in ascii_lowercase: \n            for y in ascii_lowercase: \n                if x != y and x in seen and y in seen: \n                    vals = []\n                    for ch in s: \n                        if ch == x: vals.append(1)\n                        elif ch == y: vals.append(-1)\n                    cand = prefix = least = 0 \n                    ii = -1 \n                    for i, v in enumerate(vals): \n                        prefix += v\n                        if prefix < least: \n                            least = prefix \n                            ii = i \n                        ans = max(ans, min(prefix-least, i-ii-1))\n        return ans",
      "slug": "substring-with-largest-variance",
      "post_title": "[Python3] pairwise prefix sum",
      "user": "ye15",
      "upvotes": 3,
      "views": 620,
      "problem_title": "substring with largest variance",
      "number": 2272,
      "acceptance": 0.374,
      "difficulty": "Hard",
      "__index_level_0__": 31410,
      "question": "The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same.\nGiven a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.\nA substring is a contiguous sequence of characters within a string.\n  Example 1:\nInput: s = \"aababbb\"\nOutput: 3\nExplanation:\nAll possible variances along with their respective substrings are listed below:\n- Variance 0 for substrings \"a\", \"aa\", \"ab\", \"abab\", \"aababb\", \"ba\", \"b\", \"bb\", and \"bbb\".\n- Variance 1 for substrings \"aab\", \"aba\", \"abb\", \"aabab\", \"ababb\", \"aababbb\", and \"bab\".\n- Variance 2 for substrings \"aaba\", \"ababbb\", \"abbb\", and \"babb\".\n- Variance 3 for substring \"babbb\".\nSince the largest possible variance is 3, we return it.\nExample 2:\nInput: s = \"abcde\"\nOutput: 0\nExplanation:\nNo letter occurs more than once in s, so the variance of every substring is 0.\n  Constraints:\n1 <= s.length <= 104\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/find-resultant-array-after-removing-anagrams/discuss/2039752/Weird-Description",
      "python_solutions": "class Solution:\n    def removeAnagrams(self, w: List[str]) -> List[str]:\n        return [next(g) for _, g in groupby(w, sorted)]",
      "slug": "find-resultant-array-after-removing-anagrams",
      "post_title": "Weird Description",
      "user": "votrubac",
      "upvotes": 39,
      "views": 2900,
      "problem_title": "find resultant array after removing anagrams",
      "number": 2273,
      "acceptance": 0.583,
      "difficulty": "Easy",
      "__index_level_0__": 31414,
      "question": "You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.\nIn one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.\nReturn words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, \"dacb\" is an anagram of \"abdc\".\n  Example 1:\nInput: words = [\"abba\",\"baba\",\"bbaa\",\"cd\",\"cd\"]\nOutput: [\"abba\",\"cd\"]\nExplanation:\nOne of the ways we can obtain the resultant array is by using the following operations:\n- Since words[2] = \"bbaa\" and words[1] = \"baba\" are anagrams, we choose index 2 and delete words[2].\n  Now words = [\"abba\",\"baba\",\"cd\",\"cd\"].\n- Since words[1] = \"baba\" and words[0] = \"abba\" are anagrams, we choose index 1 and delete words[1].\n  Now words = [\"abba\",\"cd\",\"cd\"].\n- Since words[2] = \"cd\" and words[1] = \"cd\" are anagrams, we choose index 2 and delete words[2].\n  Now words = [\"abba\",\"cd\"].\nWe can no longer perform any operations, so [\"abba\",\"cd\"] is the final answer.\nExample 2:\nInput: words = [\"a\",\"b\",\"c\",\"d\",\"e\"]\nOutput: [\"a\",\"b\",\"c\",\"d\",\"e\"]\nExplanation:\nNo two adjacent strings in words are anagrams of each other, so no operations are performed.\n  Constraints:\n1 <= words.length <= 100\n1 <= words[i].length <= 10\nwords[i] consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-consecutive-floors-without-special-floors/discuss/2039754/Python-Simulation-Just-sort-the-array-special",
      "python_solutions": "class Solution:\n    def maxConsecutive(self, bottom: int, top: int, special: list[int]) -> int:\n        special.sort()\n        res = special[0] - bottom\n        \n        for i in range(1, len(special)):\n            res = max(res, special[i] - special[i - 1] - 1)\n            \n        return max(res, top - special[-1])",
      "slug": "maximum-consecutive-floors-without-special-floors",
      "post_title": "Python Simulation - Just sort the array special",
      "user": "GigaMoksh",
      "upvotes": 7,
      "views": 326,
      "problem_title": "maximum consecutive floors without special floors",
      "number": 2274,
      "acceptance": 0.521,
      "difficulty": "Medium",
      "__index_level_0__": 31445,
      "question": "Alice manages a company and has rented some floors of a building as office space. Alice has decided some of these floors should be special floors, used for relaxation only.\nYou are given two integers bottom and top, which denote that Alice has rented all the floors from bottom to top (inclusive). You are also given the integer array special, where special[i] denotes a special floor that Alice has designated for relaxation.\nReturn the maximum number of consecutive floors without a special floor.\n  Example 1:\nInput: bottom = 2, top = 9, special = [4,6]\nOutput: 3\nExplanation: The following are the ranges (inclusive) of consecutive floors without a special floor:\n- (2, 3) with a total amount of 2 floors.\n- (5, 5) with a total amount of 1 floor.\n- (7, 9) with a total amount of 3 floors.\nTherefore, we return the maximum number which is 3 floors.\nExample 2:\nInput: bottom = 6, top = 8, special = [7,6,8]\nOutput: 0\nExplanation: Every floor rented is a special floor, so we return 0.\n  Constraints:\n1 <= special.length <= 105\n1 <= bottom <= special[i] <= top <= 109\nAll the values of special are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/largest-combination-with-bitwise-and-greater-than-zero/discuss/2039717/Check-Each-Bit",
      "python_solutions": "class Solution:\n    def largestCombination(self, candidates: List[int]) -> int:\n        return max(sum(n & (1 << i) > 0 for n in candidates) for i in range(0, 24))",
      "slug": "largest-combination-with-bitwise-and-greater-than-zero",
      "post_title": "Check Each Bit",
      "user": "votrubac",
      "upvotes": 55,
      "views": 3600,
      "problem_title": "largest combination with bitwise and greater than zero",
      "number": 2275,
      "acceptance": 0.7240000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 31457,
      "question": "The bitwise AND of an array nums is the bitwise AND of all integers in nums.\nFor example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.\nAlso, for nums = [7], the bitwise AND is 7.\nYou are given an array of positive integers candidates. Evaluate the bitwise AND of every combination of numbers of candidates. Each number in candidates may only be used once in each combination.\nReturn the size of the largest combination of candidates with a bitwise AND greater than 0.\n  Example 1:\nInput: candidates = [16,17,71,62,12,24,14]\nOutput: 4\nExplanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\nThe size of the combination is 4.\nIt can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\nNote that more than one combination may have the largest size.\nFor example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.\nExample 2:\nInput: candidates = [8,8]\nOutput: 2\nExplanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\nThe size of the combination is 2, so we return 2.\n  Constraints:\n1 <= candidates.length <= 105\n1 <= candidates[i] <= 107"
    },
    {
      "post_href": "https://leetcode.com/problems/percentage-of-letter-in-string/discuss/2061930/Simple-Python-Solution-or-Easy-to-Understand-or-Two-Liner-Solution-or-O(N)-Solution",
      "python_solutions": "class Solution:\n    def percentageLetter(self, s: str, letter: str) -> int:\n        a = s.count(letter)\n        return (a*100)//len(s)",
      "slug": "percentage-of-letter-in-string",
      "post_title": "Simple Python Solution | Easy to Understand | Two Liner Solution | O(N) Solution",
      "user": "AkashHooda",
      "upvotes": 2,
      "views": 63,
      "problem_title": "percentage of letter in string",
      "number": 2278,
      "acceptance": 0.741,
      "difficulty": "Easy",
      "__index_level_0__": 31468,
      "question": "Given a string s and a character letter, return the percentage of characters in s that equal letter rounded down to the nearest whole percent.\n  Example 1:\nInput: s = \"foobar\", letter = \"o\"\nOutput: 33\nExplanation:\nThe percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.\nExample 2:\nInput: s = \"jjjj\", letter = \"k\"\nOutput: 0\nExplanation:\nThe percentage of characters in s that equal the letter 'k' is 0%, so we return 0.\n  Constraints:\n1 <= s.length <= 100\ns consists of lowercase English letters.\nletter is a lowercase English letter."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-bags-with-full-capacity-of-rocks/discuss/2062186/Python-Easy-Solution",
      "python_solutions": "class Solution:\n    def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:\n        remaining = [0] * len(capacity)\n        res = 0\n        \n        for i in range(len(capacity)):\n            remaining[i] = capacity[i] - rocks[i]\n        remaining.sort()\n        \n        for i in range(len(remaining)):\n            if remaining[i] > additionalRocks:\n                break\n                \n            additionalRocks -= remaining[i]\n            res += 1\n        \n        return res",
      "slug": "maximum-bags-with-full-capacity-of-rocks",
      "post_title": "Python Easy Solution",
      "user": "MiKueen",
      "upvotes": 1,
      "views": 28,
      "problem_title": "maximum bags with full capacity of rocks",
      "number": 2279,
      "acceptance": 0.626,
      "difficulty": "Medium",
      "__index_level_0__": 31492,
      "question": "You have n bags numbered from 0 to n - 1. You are given two 0-indexed integer arrays capacity and rocks. The ith bag can hold a maximum of capacity[i] rocks and currently contains rocks[i] rocks. You are also given an integer additionalRocks, the number of additional rocks you can place in any of the bags.\nReturn the maximum number of bags that could have full capacity after placing the additional rocks in some bags.\n  Example 1:\nInput: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2\nOutput: 3\nExplanation:\nPlace 1 rock in bag 0 and 1 rock in bag 1.\nThe number of rocks in each bag are now [2,3,4,4].\nBags 0, 1, and 2 have full capacity.\nThere are 3 bags at full capacity, so we return 3.\nIt can be shown that it is not possible to have more than 3 bags at full capacity.\nNote that there may be other ways of placing the rocks that result in an answer of 3.\nExample 2:\nInput: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100\nOutput: 3\nExplanation:\nPlace 8 rocks in bag 0 and 2 rocks in bag 2.\nThe number of rocks in each bag are now [10,2,2].\nBags 0, 1, and 2 have full capacity.\nThere are 3 bags at full capacity, so we return 3.\nIt can be shown that it is not possible to have more than 3 bags at full capacity.\nNote that we did not use all of the additional rocks.\n  Constraints:\nn == capacity.length == rocks.length\n1 <= n <= 5 * 104\n1 <= capacity[i] <= 109\n0 <= rocks[i] <= capacity[i]\n1 <= additionalRocks <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-lines-to-represent-a-line-chart/discuss/2061893/Python-or-Easy-to-Understand",
      "python_solutions": "class Solution:\n    def minimumLines(self, stockPrices: List[List[int]]) -> int:\n        # key point: never use devision to judge whether 3 points are on a same line or not, use the multiplication instead !!\n        \n        n = len(stockPrices)\n        stockPrices.sort(key = lambda x: (x[0], x[1]))\n        \n        if n == 1:\n            return 0\n        \n        pre_delta_y = stockPrices[0][1] - stockPrices[1][1]\n        pre_delta_x = stockPrices[0][0] - stockPrices[1][0]\n        num = 1\n        \n        for i in range(1, n-1):\n            cur_delta_y = stockPrices[i][1] - stockPrices[i+1][1]\n            cur_delta_x = stockPrices[i][0] - stockPrices[i+1][0]\n            \n            if pre_delta_y * cur_delta_x != pre_delta_x * cur_delta_y:\n                num += 1\n                pre_delta_x = cur_delta_x\n                pre_delta_y = cur_delta_y\n        \n        return num",
      "slug": "minimum-lines-to-represent-a-line-chart",
      "post_title": "Python | Easy to Understand",
      "user": "Mikey98",
      "upvotes": 11,
      "views": 548,
      "problem_title": "minimum lines to represent a line chart",
      "number": 2280,
      "acceptance": 0.238,
      "difficulty": "Medium",
      "__index_level_0__": 31507,
      "question": "You are given a 2D integer array stockPrices where stockPrices[i] = [dayi, pricei] indicates the price of the stock on day dayi is pricei. A line chart is created from the array by plotting the points on an XY plane with the X-axis representing the day and the Y-axis representing the price and connecting adjacent points. One such example is shown below:\nReturn the minimum number of lines needed to represent the line chart.\n  Example 1:\nInput: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]\nOutput: 3\nExplanation:\nThe diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.\nThe following 3 lines can be drawn to represent the line chart:\n- Line 1 (in red) from (1,7) to (4,4) passing through (1,7), (2,6), (3,5), and (4,4).\n- Line 2 (in blue) from (4,4) to (5,4).\n- Line 3 (in green) from (5,4) to (8,1) passing through (5,4), (6,3), (7,2), and (8,1).\nIt can be shown that it is not possible to represent the line chart using less than 3 lines.\nExample 2:\nInput: stockPrices = [[3,4],[1,2],[7,8],[2,3]]\nOutput: 1\nExplanation:\nAs shown in the diagram above, the line chart can be represented with a single line.\n  Constraints:\n1 <= stockPrices.length <= 105\nstockPrices[i].length == 2\n1 <= dayi, pricei <= 109\nAll dayi are distinct."
    },
    {
      "post_href": "https://leetcode.com/problems/sum-of-total-strength-of-wizards/discuss/2373525/faster-than-98.90-or-easy-python-or-solution",
      "python_solutions": "class Solution:\n    def totalStrength(self, strength: List[int]) -> int:\n        strength = [0] + strength + [0]\n        def calc_prefix_sum(array):\n            if not array: return []\n            result = [array[0]]\n            for el in array[1:]:\n                result.append(array[-1]+el)\n            return result\n        prefix_sums = calc_prefix_sum(strength)\n        pp_sums = calc_prefix_sum(prefix_sums)\n        stack = [0]\n        total = 0\n        for right in range(len(strength)):\n            while pp_sums[stack[-1]] > pp_sums[right]:\n                left = stack[-2]\n                i = stack.pop()\n                pos = (i - left) * (pp_sums[right] - pp_sums[i])\n                neg = (right - i) * (pp_sums[i] - pp_sums[left])\n                total += pp_sums[i] * (pos - neg)\n                stack.push(right)\n        return total % (10**9+7)\n    def totalStrength(self, strength):\n        res, S, A = 0, [0], [0] + strength + [0]                           # O(N)\n        P = list(itertools.accumulate(itertools.accumulate(A), initial=0)) # O(N)\n        for r in range(len(A)):                                            # O(N)\n            while A[S[-1]] > A[r]:                                         # O(1) amortized\n                l, i = S[-2], S.pop()\n                res += A[i] * ((i - l) * (P[r] - P[i]) - (r - i) * (P[i] - P[l]))\n            S.append(r)\n        return res % (10 ** 9 + 7)",
      "slug": "sum-of-total-strength-of-wizards",
      "post_title": "faster than 98.90% | easy python | solution",
      "user": "vimla_kushwaha",
      "upvotes": 2,
      "views": 1800,
      "problem_title": "sum of total strength of wizards",
      "number": 2281,
      "acceptance": 0.2789999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 31516,
      "question": "As the ruler of a kingdom, you have an army of wizards at your command.\nYou are given a 0-indexed integer array strength, where strength[i] denotes the strength of the ith wizard. For a contiguous group of wizards (i.e. the wizards' strengths form a subarray of strength), the total strength is defined as the product of the following two values:\nThe strength of the weakest wizard in the group.\nThe total of all the individual strengths of the wizards in the group.\nReturn the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7.\nA subarray is a contiguous non-empty sequence of elements within an array.\n  Example 1:\nInput: strength = [1,3,1,2]\nOutput: 44\nExplanation: The following are all the contiguous groups of wizards:\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [3] from [1,3,1,2] has a total strength of min([3]) * sum([3]) = 3 * 3 = 9\n- [1] from [1,3,1,2] has a total strength of min([1]) * sum([1]) = 1 * 1 = 1\n- [2] from [1,3,1,2] has a total strength of min([2]) * sum([2]) = 2 * 2 = 4\n- [1,3] from [1,3,1,2] has a total strength of min([1,3]) * sum([1,3]) = 1 * 4 = 4\n- [3,1] from [1,3,1,2] has a total strength of min([3,1]) * sum([3,1]) = 1 * 4 = 4\n- [1,2] from [1,3,1,2] has a total strength of min([1,2]) * sum([1,2]) = 1 * 3 = 3\n- [1,3,1] from [1,3,1,2] has a total strength of min([1,3,1]) * sum([1,3,1]) = 1 * 5 = 5\n- [3,1,2] from [1,3,1,2] has a total strength of min([3,1,2]) * sum([3,1,2]) = 1 * 6 = 6\n- [1,3,1,2] from [1,3,1,2] has a total strength of min([1,3,1,2]) * sum([1,3,1,2]) = 1 * 7 = 7\nThe sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.\nExample 2:\nInput: strength = [5,4,6]\nOutput: 213\nExplanation: The following are all the contiguous groups of wizards: \n- [5] from [5,4,6] has a total strength of min([5]) * sum([5]) = 5 * 5 = 25\n- [4] from [5,4,6] has a total strength of min([4]) * sum([4]) = 4 * 4 = 16\n- [6] from [5,4,6] has a total strength of min([6]) * sum([6]) = 6 * 6 = 36\n- [5,4] from [5,4,6] has a total strength of min([5,4]) * sum([5,4]) = 4 * 9 = 36\n- [4,6] from [5,4,6] has a total strength of min([4,6]) * sum([4,6]) = 4 * 10 = 40\n- [5,4,6] from [5,4,6] has a total strength of min([5,4,6]) * sum([5,4,6]) = 4 * 15 = 60\nThe sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.\n  Constraints:\n1 <= strength.length <= 105\n1 <= strength[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/check-if-number-has-equal-digit-count-and-digit-value/discuss/2084112/Python-Easy-solution",
      "python_solutions": "class Solution:\n    def digitCount(self, num: str) -> bool:\n        counter=Counter(num)\n        for i in range(len(num)):\n            if counter[f'{i}'] != int(num[i]):\n                return False\n        return True",
      "slug": "check-if-number-has-equal-digit-count-and-digit-value",
      "post_title": "Python Easy solution",
      "user": "constantine786",
      "upvotes": 3,
      "views": 142,
      "problem_title": "check if number has equal digit count and digit value",
      "number": 2283,
      "acceptance": 0.735,
      "difficulty": "Easy",
      "__index_level_0__": 31518,
      "question": "You are given a 0-indexed string num of length n consisting of digits.\nReturn true if for every index i in the range 0 <= i < n, the digit i occurs num[i] times in num, otherwise return false.\n  Example 1:\nInput: num = \"1210\"\nOutput: true\nExplanation:\nnum[0] = '1'. The digit 0 occurs once in num.\nnum[1] = '2'. The digit 1 occurs twice in num.\nnum[2] = '1'. The digit 2 occurs once in num.\nnum[3] = '0'. The digit 3 occurs zero times in num.\nThe condition holds true for every index in \"1210\", so return true.\nExample 2:\nInput: num = \"030\"\nOutput: false\nExplanation:\nnum[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.\nnum[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.\nnum[2] = '0'. The digit 2 occurs zero times in num.\nThe indices 0 and 1 both violate the condition, so return false.\n  Constraints:\nn == num.length\n1 <= n <= 10\nnum consists of digits."
    },
    {
      "post_href": "https://leetcode.com/problems/sender-with-largest-word-count/discuss/2084222/Easy-Python-Solution-With-Dictionary",
      "python_solutions": "class Solution:\n    def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n        d={}\n        l=[]\n        for i in range(len(messages)):\n            if senders[i] not in d:\n                d[senders[i]]=len(messages[i].split())\n            else:\n                d[senders[i]]+=len(messages[i].split())\n        x=max(d.values())\n        for k,v in d.items():\n            if v==x :\n                l.append(k)\n        if len(l)==1:\n            return l[0]\n        else:\n            l=sorted(l)[::-1]      #Lexigograhical sorting of list\n            return l[0]",
      "slug": "sender-with-largest-word-count",
      "post_title": "Easy Python Solution With Dictionary",
      "user": "a_dityamishra",
      "upvotes": 7,
      "views": 356,
      "problem_title": "sender with largest word count",
      "number": 2284,
      "acceptance": 0.561,
      "difficulty": "Medium",
      "__index_level_0__": 31546,
      "question": "You have a chat log of n messages. You are given two string arrays messages and senders where messages[i] is a message sent by senders[i].\nA message is list of words that are separated by a single space with no leading or trailing spaces. The word count of a sender is the total number of words sent by the sender. Note that a sender may send more than one message.\nReturn the sender with the largest word count. If there is more than one sender with the largest word count, return the one with the lexicographically largest name.\nNote:\nUppercase letters come before lowercase letters in lexicographical order.\n\"Alice\" and \"alice\" are distinct.\n  Example 1:\nInput: messages = [\"Hello userTwooo\",\"Hi userThree\",\"Wonderful day Alice\",\"Nice day userThree\"], senders = [\"Alice\",\"userTwo\",\"userThree\",\"Alice\"]\nOutput: \"Alice\"\nExplanation: Alice sends a total of 2 + 3 = 5 words.\nuserTwo sends a total of 2 words.\nuserThree sends a total of 3 words.\nSince Alice has the largest word count, we return \"Alice\".\nExample 2:\nInput: messages = [\"How is leetcode for everyone\",\"Leetcode is useful for practice\"], senders = [\"Bob\",\"Charlie\"]\nOutput: \"Charlie\"\nExplanation: Bob sends a total of 5 words.\nCharlie sends a total of 5 words.\nSince there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.\n  Constraints:\nn == messages.length == senders.length\n1 <= n <= 104\n1 <= messages[i].length <= 100\n1 <= senders[i].length <= 10\nmessages[i] consists of uppercase and lowercase English letters and ' '.\nAll the words in messages[i] are separated by a single space.\nmessages[i] does not have leading or trailing spaces.\nsenders[i] consists of uppercase and lowercase English letters only."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-total-importance-of-roads/discuss/2083990/Very-simple-Python-solution-O(nlog(n))",
      "python_solutions": "class Solution:\n    def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n        Arr = [0] * n  # i-th city has Arr[i] roads\n        for A,B in roads:\n            Arr[A] += 1 # Each road increase the road count\n            Arr[B] += 1\n        Arr.sort()  # Cities with most road should receive the most score\n        summ = 0\n        for i in range(len(Arr)):\n            summ += Arr[i] * (i+1)  # Multiply city roads with corresponding score\n        \n        return summ",
      "slug": "maximum-total-importance-of-roads",
      "post_title": "Very simple Python solution O(nlog(n))",
      "user": "Eba472",
      "upvotes": 14,
      "views": 452,
      "problem_title": "maximum total importance of roads",
      "number": 2285,
      "acceptance": 0.608,
      "difficulty": "Medium",
      "__index_level_0__": 31580,
      "question": "You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.\nYou are also given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.\nYou need to assign each city with an integer value from 1 to n, where each value can only be used once. The importance of a road is then defined as the sum of the values of the two cities it connects.\nReturn the maximum total importance of all roads possible after assigning the values optimally.\n  Example 1:\nInput: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\nOutput: 43\nExplanation: The figure above shows the country and the assigned values of [2,4,5,3,1].\n- The road (0,1) has an importance of 2 + 4 = 6.\n- The road (1,2) has an importance of 4 + 5 = 9.\n- The road (2,3) has an importance of 5 + 3 = 8.\n- The road (0,2) has an importance of 2 + 5 = 7.\n- The road (1,3) has an importance of 4 + 3 = 7.\n- The road (2,4) has an importance of 5 + 1 = 6.\nThe total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\nIt can be shown that we cannot obtain a greater total importance than 43.\nExample 2:\nInput: n = 5, roads = [[0,3],[2,4],[1,3]]\nOutput: 20\nExplanation: The figure above shows the country and the assigned values of [4,3,2,5,1].\n- The road (0,3) has an importance of 4 + 5 = 9.\n- The road (2,4) has an importance of 2 + 1 = 3.\n- The road (1,3) has an importance of 3 + 5 = 8.\nThe total importance of all roads is 9 + 3 + 8 = 20.\nIt can be shown that we cannot obtain a greater total importance than 20.\n  Constraints:\n2 <= n <= 5 * 104\n1 <= roads.length <= 5 * 104\nroads[i].length == 2\n0 <= ai, bi <= n - 1\nai != bi\nThere are no duplicate roads."
    },
    {
      "post_href": "https://leetcode.com/problems/rearrange-characters-to-make-target-string/discuss/2085849/Python-Two-Liner-Beats-~95",
      "python_solutions": "class Solution:\n    def rearrangeCharacters(self, s: str, target: str) -> int:\n        counter_s = Counter(s)        \n        return min(counter_s[c] // count for c,count in Counter(target).items())",
      "slug": "rearrange-characters-to-make-target-string",
      "post_title": "Python Two Liner Beats ~95%",
      "user": "constantine786",
      "upvotes": 14,
      "views": 854,
      "problem_title": "rearrange characters to make target string",
      "number": 2287,
      "acceptance": 0.578,
      "difficulty": "Easy",
      "__index_level_0__": 31592,
      "question": "You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.\nReturn the maximum number of copies of target that can be formed by taking letters from s and rearranging them.\n  Example 1:\nInput: s = \"ilovecodingonleetcode\", target = \"code\"\nOutput: 2\nExplanation:\nFor the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\nFor the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\nThe strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\nWe can make at most two copies of \"code\", so we return 2.\nExample 2:\nInput: s = \"abcba\", target = \"abc\"\nOutput: 1\nExplanation:\nWe can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\nWe can make at most one copy of \"abc\", so we return 1.\nNote that while there is an extra 'a' and 'b' at indices 3 and 4, we cannot reuse the letter 'c' at index 2, so we cannot make a second copy of \"abc\".\nExample 3:\nInput: s = \"abbaccaddaeea\", target = \"aaaaa\"\nOutput: 1\nExplanation:\nWe can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\nWe can make at most one copy of \"aaaaa\", so we return 1.\n  Constraints:\n1 <= s.length <= 100\n1 <= target.length <= 10\ns and target consist of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/apply-discount-to-prices/discuss/2085723/Simple-Python-with-explanation",
      "python_solutions": "class Solution:\n    def discountPrices(self, sentence: str, discount: int) -> str:\n        s = sentence.split() # convert to List to easily update\n        m = discount / 100 \n        for i,word in enumerate(s):\n            if word[0] == \"$\" and word[1:].isdigit(): # Check whether it is in correct format\n                num = int(word[1:]) * (1-m) # discounted price\n                w = \"$\" + \"{:.2f}\".format(num) #correctly format\n                s[i] = w #Change inside the list\n        \n        return \" \".join(s) #Combine the updated list\n\t\t```",
      "slug": "apply-discount-to-prices",
      "post_title": "Simple Python with explanation",
      "user": "Eba472",
      "upvotes": 7,
      "views": 311,
      "problem_title": "apply discount to prices",
      "number": 2288,
      "acceptance": 0.2739999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 31615,
      "question": "A sentence is a string of single-space separated words where each word can contain digits, lowercase letters, and the dollar sign '$'. A word represents a price if it is a sequence of digits preceded by a dollar sign.\nFor example, \"$100\", \"$23\", and \"$6\" represent prices while \"100\", \"$\", and \"$1e5\" do not.\nYou are given a string sentence representing a sentence and an integer discount. For each word representing a price, apply a discount of discount% on the price and update the word in the sentence. All updated prices should be represented with exactly two decimal places.\nReturn a string representing the modified sentence.\nNote that all prices will contain at most 10 digits.\n  Example 1:\nInput: sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50\nOutput: \"there are $0.50 $1.00 and 5$ candies in the shop\"\nExplanation: \nThe words which represent prices are \"$1\" and \"$2\". \n- A 50% discount on \"$1\" yields \"$0.50\", so \"$1\" is replaced by \"$0.50\".\n- A 50% discount on \"$2\" yields \"$1\". Since we need to have exactly 2 decimal places after a price, we replace \"$2\" with \"$1.00\".\nExample 2:\nInput: sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100\nOutput: \"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"\nExplanation: \nApplying a 100% discount on any price will result in 0.\nThe words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\nEach of them is replaced by \"$0.00\".\n  Constraints:\n1 <= sentence.length <= 105\nsentence consists of lowercase English letters, digits, ' ', and '$'.\nsentence does not have leading or trailing spaces.\nAll words in sentence are separated by a single space.\nAll prices will be positive numbers without leading zeros.\nAll prices will have at most 10 digits.\n0 <= discount <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/steps-to-make-array-non-decreasing/discuss/2567529/BFS-with-updating-neighbours-or-O(n)-or-Python3",
      "python_solutions": "class Solution:\n    def totalSteps(self, nums: List[int]) -> int:\n        n = len(nums)\n        l = [i-1 for i in range(n)]\n        r = [i+1 for i in range(n)]\n        q = []\n        dist = dict()\n        ans = 0\n        for i in range(1, n):\n            if nums[i] < nums[i-1]:\n                q.append(i)\n                dist[i] = 1\n                ans = 1\n        while len(q) != 0:\n            u = q.pop(0)\n            ans = max(ans, dist[u])\n            if r[u] < n:\n                l[r[u]] = l[u]\n            if l[u] > -1:\n                r[l[u]] = r[u]\n            if r[u] not in dist and r[u] < n and nums[r[u]] < nums[l[u]]:\n                dist[r[u]] = dist[u] + 1\n                q.append(r[u])\n        return ans",
      "slug": "steps-to-make-array-non-decreasing",
      "post_title": "BFS with updating neighbours | O(n) | Python3",
      "user": "DheerajGadwala",
      "upvotes": 0,
      "views": 67,
      "problem_title": "steps to make array non decreasing",
      "number": 2289,
      "acceptance": 0.214,
      "difficulty": "Medium",
      "__index_level_0__": 31634,
      "question": "You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.\nReturn the number of steps performed until nums becomes a non-decreasing array.\n  Example 1:\nInput: nums = [5,3,4,4,7,3,6,11,8,5,11]\nOutput: 3\nExplanation: The following are the steps performed:\n- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]\n- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]\n- Step 3: [5,4,7,11,11] becomes [5,7,11,11]\n[5,7,11,11] is a non-decreasing array. Therefore, we return 3.\nExample 2:\nInput: nums = [4,5,7,7,13]\nOutput: 0\nExplanation: nums is already a non-decreasing array. Therefore, we return 0.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/discuss/2313936/Python3-Dijkstra's-algo",
      "python_solutions": "class Solution:\n    def minimumObstacles(self, grid: List[List[int]]) -> int:\n        m, n = len(grid), len(grid[0])\n        dist = [[inf]*n for _ in range(m)]\n        dist[0][0] = 0\n        pq = [(0, 0, 0)]\n        while pq: \n            x, i, j = heappop(pq)\n            if i == m-1 and j == n-1: return x\n            for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n                if 0 <= ii < m and 0 <= jj < n and x + grid[ii][jj] < dist[ii][jj]: \n                    dist[ii][jj] = x + grid[ii][jj]\n                    heappush(pq, (dist[ii][jj], ii, jj))",
      "slug": "minimum-obstacle-removal-to-reach-corner",
      "post_title": "[Python3] Dijkstra's algo",
      "user": "ye15",
      "upvotes": 1,
      "views": 32,
      "problem_title": "minimum obstacle removal to reach corner",
      "number": 2290,
      "acceptance": 0.487,
      "difficulty": "Hard",
      "__index_level_0__": 31637,
      "question": "You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:\n0 represents an empty cell,\n1 represents an obstacle that may be removed.\nYou can move up, down, left, or right from and to an empty cell.\nReturn the minimum number of obstacles to remove so you can move from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1).\n  Example 1:\nInput: grid = [[0,1,1],[1,1,0],[1,1,0]]\nOutput: 2\nExplanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\nIt can be shown that we need to remove at least 2 obstacles, so we return 2.\nNote that there may be other ways to remove 2 obstacles to create a path.\nExample 2:\nInput: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]\nOutput: 0\nExplanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.\n  Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 105\n2 <= m * n <= 105\ngrid[i][j] is either 0 or 1.\ngrid[0][0] == grid[m - 1][n - 1] == 0"
    },
    {
      "post_href": "https://leetcode.com/problems/min-max-game/discuss/2112349/Python-Easy-Approach",
      "python_solutions": "class Solution:\n    def minMaxGame(self, nums: List[int]) -> int:                \n        l=nums\n        while len(l)>1:\n            is_min=True     \n            tmp=[]\n            for i in range(0, len(l), 2):\n                if is_min:\n                    tmp.append(min(l[i:i+2]))\n                else:\n                    tmp.append(max(l[i:i+2]))\n                is_min=not is_min            \n            l=tmp            \n        return l[0]",
      "slug": "min-max-game",
      "post_title": "\u2705 Python Easy Approach",
      "user": "constantine786",
      "upvotes": 8,
      "views": 503,
      "problem_title": "min max game",
      "number": 2293,
      "acceptance": 0.643,
      "difficulty": "Easy",
      "__index_level_0__": 31641,
      "question": "You are given a 0-indexed integer array nums whose length is a power of 2.\nApply the following algorithm on nums:\nLet n be the length of nums. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n / 2.\nFor every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).\nFor every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).\nReplace the array nums with newNums.\nRepeat the entire process starting from step 1.\nReturn the last number that remains in nums after applying the algorithm.\n  Example 1:\nInput: nums = [1,3,5,2,4,8,2,2]\nOutput: 1\nExplanation: The following arrays are the results of applying the algorithm repeatedly.\nFirst: nums = [1,5,4,2]\nSecond: nums = [1,4]\nThird: nums = [1]\n1 is the last remaining number, so we return 1.\nExample 2:\nInput: nums = [3]\nOutput: 3\nExplanation: 3 is already the last remaining number, so we return 3.\n  Constraints:\n1 <= nums.length <= 1024\n1 <= nums[i] <= 109\nnums.length is a power of 2."
    },
    {
      "post_href": "https://leetcode.com/problems/partition-array-such-that-maximum-difference-is-k/discuss/2111923/Python-Easy-Solution-using-Sorting",
      "python_solutions": "class Solution:\n    def partitionArray(self, nums: List[int], k: int) -> int:\n        nums.sort()\n        ans = 1\n\t\t# To keep track of starting element of each subsequence\n        start = nums[0]\n        \n        for i in range(1, len(nums)):\n            diff = nums[i] - start\n            if diff > k:\n\t\t\t\t# If difference of starting and current element of subsequence is greater\n\t\t\t\t# than K, then only start new subsequence\n                ans += 1\n                start = nums[i]\n        \n        return ans",
      "slug": "partition-array-such-that-maximum-difference-is-k",
      "post_title": "Python Easy Solution using Sorting",
      "user": "MiKueen",
      "upvotes": 19,
      "views": 877,
      "problem_title": "partition array such that maximum difference is k",
      "number": 2294,
      "acceptance": 0.726,
      "difficulty": "Medium",
      "__index_level_0__": 31669,
      "question": "You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.\nReturn the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.\nA subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.\n  Example 1:\nInput: nums = [3,6,1,2,5], k = 2\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [3,1,2] and [6,5].\nThe difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\nThe difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\nSince two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.\nExample 2:\nInput: nums = [1,2,3], k = 1\nOutput: 2\nExplanation:\nWe can partition nums into the two subsequences [1,2] and [3].\nThe difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\nThe difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\nSince two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].\nExample 3:\nInput: nums = [2,2,4,5], k = 0\nOutput: 3\nExplanation:\nWe can partition nums into the three subsequences [2,2], [4], and [5].\nThe difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\nThe difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\nThe difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\nSince three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.\n  Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 105\n0 <= k <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/replace-elements-in-an-array/discuss/2112285/Python-Simple-Map-Approach",
      "python_solutions": "class Solution:\n    def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:\n            replacements = {}\n            for x, y in reversed(operations):\n                replacements[x] = replacements.get(y, y)\n            for idx, val in enumerate(nums):\n                if val in replacements:\n                    nums[idx] = replacements[val]\n            return nums",
      "slug": "replace-elements-in-an-array",
      "post_title": "\u2705 Python Simple Map Approach",
      "user": "constantine786",
      "upvotes": 25,
      "views": 1300,
      "problem_title": "replace elements in an array",
      "number": 2295,
      "acceptance": 0.5760000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 31692,
      "question": "You are given a 0-indexed array nums that consists of n distinct positive integers. Apply m operations to this array, where in the ith operation you replace the number operations[i][0] with operations[i][1].\nIt is guaranteed that in the ith operation:\noperations[i][0] exists in nums.\noperations[i][1] does not exist in nums.\nReturn the array obtained after applying all the operations.\n  Example 1:\nInput: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]\nOutput: [3,2,7,1]\nExplanation: We perform the following operations on nums:\n- Replace the number 1 with 3. nums becomes [3,2,4,6].\n- Replace the number 4 with 7. nums becomes [3,2,7,6].\n- Replace the number 6 with 1. nums becomes [3,2,7,1].\nWe return the final array [3,2,7,1].\nExample 2:\nInput: nums = [1,2], operations = [[1,3],[2,1],[3,2]]\nOutput: [2,1]\nExplanation: We perform the following operations to nums:\n- Replace the number 1 with 3. nums becomes [3,2].\n- Replace the number 2 with 1. nums becomes [3,1].\n- Replace the number 3 with 2. nums becomes [2,1].\nWe return the array [2,1].\n  Constraints:\nn == nums.length\nm == operations.length\n1 <= n, m <= 105\nAll the values of nums are distinct.\noperations[i].length == 2\n1 <= nums[i], operations[i][0], operations[i][1] <= 106\noperations[i][0] will exist in nums when applying the ith operation.\noperations[i][1] will not exist in nums when applying the ith operation."
    },
    {
      "post_href": "https://leetcode.com/problems/strong-password-checker-ii/discuss/2139499/Nothing-Special",
      "python_solutions": "class Solution:\n    def strongPasswordCheckerII(self, pwd: str) -> bool:\n        return (\n            len(pwd) > 7\n            and max(len(list(p[1])) for p in groupby(pwd)) == 1\n            and reduce(\n                lambda a, b: a | (1 if b.isdigit() else 2 if b.islower() else 4 if b.isupper() else 8), pwd, 0\n            ) == 15\n        )",
      "slug": "strong-password-checker-ii",
      "post_title": "Nothing Special",
      "user": "votrubac",
      "upvotes": 22,
      "views": 882,
      "problem_title": "strong password checker ii",
      "number": 2299,
      "acceptance": 0.5670000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 31708,
      "question": "A password is said to be strong if it satisfies all the following criteria:\nIt has at least 8 characters.\nIt contains at least one lowercase letter.\nIt contains at least one uppercase letter.\nIt contains at least one digit.\nIt contains at least one special character. The special characters are the characters in the following string: \"!@#$%^&*()-+\".\nIt does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not).\nGiven a string password, return true if it is a strong password. Otherwise, return false.\n  Example 1:\nInput: password = \"IloveLe3tcode!\"\nOutput: true\nExplanation: The password meets all the requirements. Therefore, we return true.\nExample 2:\nInput: password = \"Me+You--IsMyDream\"\nOutput: false\nExplanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.\nExample 3:\nInput: password = \"1aB!\"\nOutput: false\nExplanation: The password does not meet the length requirement. Therefore, we return false.\n  Constraints:\n1 <= password.length <= 100\npassword consists of letters, digits, and special characters: \"!@#$%^&*()-+\"."
    },
    {
      "post_href": "https://leetcode.com/problems/successful-pairs-of-spells-and-potions/discuss/2139547/Python-3-or-Math-Binary-Search-or-Explanation",
      "python_solutions": "class Solution:\n    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n        potions.sort()\n        ans, n = [], len(potions)\n        for spell in spells:\n            val = success // spell\n            if success % spell == 0:\n                idx = bisect.bisect_left(potions, val)\n            else:    \n                idx = bisect.bisect_right(potions, val)\n            ans.append(n - idx)\n        return ans",
      "slug": "successful-pairs-of-spells-and-potions",
      "post_title": "Python 3 | Math, Binary Search | Explanation",
      "user": "idontknoooo",
      "upvotes": 2,
      "views": 89,
      "problem_title": "successful pairs of spells and potions",
      "number": 2300,
      "acceptance": 0.317,
      "difficulty": "Medium",
      "__index_level_0__": 31719,
      "question": "You are given two positive integer arrays spells and potions, of length n and m respectively, where spells[i] represents the strength of the ith spell and potions[j] represents the strength of the jth potion.\nYou are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.\nReturn an integer array pairs of length n where pairs[i] is the number of potions that will form a successful pair with the ith spell.\n  Example 1:\nInput: spells = [5,1,3], potions = [1,2,3,4,5], success = 7\nOutput: [4,0,3]\nExplanation:\n- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.\n- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.\n- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.\nThus, [4,0,3] is returned.\nExample 2:\nInput: spells = [3,1,2], potions = [8,5,8], success = 16\nOutput: [2,0,2]\nExplanation:\n- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.\n- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. \n- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. \nThus, [2,0,2] is returned.\n  Constraints:\nn == spells.length\nm == potions.length\n1 <= n, m <= 105\n1 <= spells[i], potions[i] <= 105\n1 <= success <= 1010"
    },
    {
      "post_href": "https://leetcode.com/problems/match-substring-after-replacement/discuss/2140652/Python-Precalculation-O(n*k)-without-TLE",
      "python_solutions": "class Solution:\n    def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n        s_maps = defaultdict(lambda : set())\n        for x,y in mappings:\n            s_maps[x].add(y)\n                \n        # build a sequence of set for substring match\n        # eg: sub=leet, mappings = {e: 3, t:7}\n        # subs = [{l}, {e, 3}, {e, 3}, {t, 7}]\n        # precalculation helps to eliminate TLE\n        subs = [s_maps[c] | {c} for c in sub] \n        \n        for i in range(len(s)-len(sub) + 1):\n            c=s[i]            \n            j=i\n            # Try to match substring\n            while j-i int:\n        sum, res, j = 0, 0, 0\n        for i, n in enumerate(nums):\n            sum += n\n            while sum * (i - j + 1) >= k:\n                sum -= nums[j]\n                j += 1\n            res += i - j + 1\n        return res",
      "slug": "count-subarrays-with-score-less-than-k",
      "post_title": "Sliding Window",
      "user": "votrubac",
      "upvotes": 126,
      "views": 4700,
      "problem_title": "count subarrays with score less than k",
      "number": 2302,
      "acceptance": 0.522,
      "difficulty": "Hard",
      "__index_level_0__": 31734,
      "question": "The score of an array is defined as the product of its sum and its length.\nFor example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.\nGiven a positive integer array nums and an integer k, return the number of non-empty subarrays of nums whose score is strictly less than k.\nA subarray is a contiguous sequence of elements within an array.\n  Example 1:\nInput: nums = [2,1,4,3,5], k = 10\nOutput: 6\nExplanation:\nThe 6 subarrays having scores less than 10 are:\n- [2] with score 2 * 1 = 2.\n- [1] with score 1 * 1 = 1.\n- [4] with score 4 * 1 = 4.\n- [3] with score 3 * 1 = 3. \n- [5] with score 5 * 1 = 5.\n- [2,1] with score (2 + 1) * 2 = 6.\nNote that subarrays such as [1,4] and [4,3,5] are not considered because their scores are 10 and 36 respectively, while we need scores strictly less than 10.\nExample 2:\nInput: nums = [1,1,1], k = 5\nOutput: 5\nExplanation:\nEvery subarray except [1,1,1] has a score less than 5.\n[1,1,1] has a score (1 + 1 + 1) * 3 = 9, which is greater than 5.\nThus, there are 5 subarrays having scores less than 5.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 105\n1 <= k <= 1015"
    },
    {
      "post_href": "https://leetcode.com/problems/calculate-amount-paid-in-taxes/discuss/2141187/Python3-bracket-by-bracket",
      "python_solutions": "class Solution:\n    def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n        ans = prev = 0 \n        for hi, pct in brackets: \n            hi = min(hi, income)\n            ans += (hi - prev)*pct/100\n            prev = hi \n        return ans",
      "slug": "calculate-amount-paid-in-taxes",
      "post_title": "[Python3] bracket by bracket",
      "user": "ye15",
      "upvotes": 14,
      "views": 535,
      "problem_title": "calculate amount paid in taxes",
      "number": 2303,
      "acceptance": 0.634,
      "difficulty": "Easy",
      "__index_level_0__": 31740,
      "question": "You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).\nTax is calculated as follows:\nThe first upper0 dollars earned are taxed at a rate of percent0.\nThe next upper1 - upper0 dollars earned are taxed at a rate of percent1.\nThe next upper2 - upper1 dollars earned are taxed at a rate of percent2.\nAnd so on.\nYou are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted.\n  Example 1:\nInput: brackets = [[3,50],[7,10],[12,25]], income = 10\nOutput: 2.65000\nExplanation:\nBased on your income, you have 3 dollars in the 1st tax bracket, 4 dollars in the 2nd tax bracket, and 3 dollars in the 3rd tax bracket.\nThe tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\nIn total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.\nExample 2:\nInput: brackets = [[1,0],[4,25],[5,50]], income = 2\nOutput: 0.25000\nExplanation:\nBased on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.\nThe tax rate for the two tax brackets is 0% and 25%, respectively.\nIn total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.\nExample 3:\nInput: brackets = [[2,50]], income = 0\nOutput: 0.00000\nExplanation:\nYou have no income to tax, so you have to pay a total of $0 in taxes.\n  Constraints:\n1 <= brackets.length <= 100\n1 <= upperi <= 1000\n0 <= percenti <= 100\n0 <= income <= 1000\nupperi is sorted in ascending order.\nAll the values of upperi are unique.\nThe upper bound of the last tax bracket is greater than or equal to income."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-path-cost-in-a-grid/discuss/2141004/Python-Recursion-%2B-Memoization",
      "python_solutions": "class Solution:\n    def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:\n        max_row, max_col = len(grid), len(grid[0])\n        dp = [[-1] * max_col for _ in range(max_row)] \n\n        def recursion(row, col):\n            if row == max_row - 1: # If last row then return nodes value\n                return grid[row][col]\n            if dp[row][col] == -1: # If DP for this node is not computed then we will do so now.\n                current = grid[row][col] # Current Node Value\n                res = float('inf') # To store best path from Current Node\n                for c in range(max_col): # Traverse all path from Current Node\n                    val = moveCost[current][c] + recursion(row + 1, c) # Move cost + Target Node Value\n                    res = min(res, val)\n                dp[row][col] = res + current # DP[current node] = Best Path + Target Node Val + Current Node Val\n            return dp[row][col]\n\n        for c in range(max_col):\n            recursion(0, c) # Start recursion from all nodes in 1st row\n        return min(dp[0]) # Return min value from 1st row",
      "slug": "minimum-path-cost-in-a-grid",
      "post_title": "Python Recursion + Memoization",
      "user": "anCoderr",
      "upvotes": 13,
      "views": 501,
      "problem_title": "minimum path cost in a grid",
      "number": 2304,
      "acceptance": 0.6559999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 31761,
      "question": "You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0), (x + 1, 1), ..., (x + 1, n - 1). Note that it is not possible to move from cells in the last row.\nEach possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored.\nThe cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.\n  Example 1:\nInput: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]\nOutput: 17\nExplanation: The path with the minimum possible cost is the path 5 -> 0 -> 1.\n- The sum of the values of cells visited is 5 + 0 + 1 = 6.\n- The cost of moving from 5 to 0 is 3.\n- The cost of moving from 0 to 1 is 8.\nSo the total cost of the path is 6 + 3 + 8 = 17.\nExample 2:\nInput: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]\nOutput: 6\nExplanation: The path with the minimum possible cost is the path 2 -> 3.\n- The sum of the values of cells visited is 2 + 3 = 5.\n- The cost of moving from 2 to 3 is 1.\nSo the total cost of this path is 5 + 1 = 6.\n  Constraints:\nm == grid.length\nn == grid[i].length\n2 <= m, n <= 50\ngrid consists of distinct integers from 0 to m * n - 1.\nmoveCost.length == m * n\nmoveCost[i].length == n\n1 <= moveCost[i][j] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/fair-distribution-of-cookies/discuss/2141013/Python-optimized-solution-or-Backtracking-Implemented-or-O(KN)-Time-Complexity",
      "python_solutions": "class Solution:\n    def distributeCookies(self, cookies: List[int], k: int) -> int:\n        l = [0]*k \n        self.s = float('inf')\n        def ser(l,i):\n            if i>=len(cookies):\n                self.s = min(self.s,max(l))\n                return \n            if max(l)>=self.s:\n                return \n            for j in range(k):\n                l[j]+=cookies[i]\n                ser(l,i+1)\n                l[j]-=cookies[i]\n        \n        ser(l,0)\n        return self.s",
      "slug": "fair-distribution-of-cookies",
      "post_title": "Python optimized solution | Backtracking Implemented | O(K^N) Time Complexity",
      "user": "AkashHooda",
      "upvotes": 5,
      "views": 852,
      "problem_title": "fair distribution of cookies",
      "number": 2305,
      "acceptance": 0.626,
      "difficulty": "Medium",
      "__index_level_0__": 31780,
      "question": "You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.\nThe unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.\nReturn the minimum unfairness of all distributions.\n  Example 1:\nInput: cookies = [8,15,10,20,8], k = 2\nOutput: 31\nExplanation: One optimal distribution is [8,15,8] and [10,20]\n- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.\n- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.\nThe unfairness of the distribution is max(31,30) = 31.\nIt can be shown that there is no distribution with an unfairness less than 31.\nExample 2:\nInput: cookies = [6,1,3,2,2,4,1,2], k = 3\nOutput: 7\nExplanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]\n- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.\n- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.\n- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.\nThe unfairness of the distribution is max(7,7,7) = 7.\nIt can be shown that there is no distribution with an unfairness less than 7.\n  Constraints:\n2 <= cookies.length <= 8\n1 <= cookies[i] <= 105\n2 <= k <= cookies.length"
    },
    {
      "post_href": "https://leetcode.com/problems/naming-a-company/discuss/2147565/Python-or-Faster-than-100-or-groupby-detailed-explanation",
      "python_solutions": "class Solution:\n    def distinctNames(self, ideas: List[str]) -> int:\n        \n        names=defaultdict(set)\n        res=0  \n        \n        #to store first letter as key and followed suffix as val\n        for i in ideas:\n            names[i[0]].add(i[1:])\n            \n        #list of distinct first-letters available in ideas (may or may not contain all alphabets,depends upon elements in ideas)\n        arr=list(names.keys())\n        ans,n=0,len(arr)\n        \n        for i in range(n):\n            for j in range(i+1,n):\n                #a,b => 2 distinct first letters\n                a,b=arr[i],arr[j]\n                # adding the number of distinct posssible suffixes and multiplying by 2 as the new word formed might be \"newword1 newword2\" or \"newword2 newword1\"\n                res+=len(names[a]-names[b])*len(names[b]-names[a])*2\n                \n        return res",
      "slug": "naming-a-company",
      "post_title": "Python | Faster than 100% | groupby detailed explanation",
      "user": "anjalianupam23",
      "upvotes": 4,
      "views": 172,
      "problem_title": "naming a company",
      "number": 2306,
      "acceptance": 0.344,
      "difficulty": "Hard",
      "__index_level_0__": 31793,
      "question": "You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:\nChoose 2 distinct names from ideas, call them ideaA and ideaB.\nSwap the first letters of ideaA and ideaB with each other.\nIf both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.\nOtherwise, it is not a valid name.\nReturn the number of distinct valid names for the company.\n  Example 1:\nInput: ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]\nOutput: 6\nExplanation: The following selections are valid:\n- (\"coffee\", \"donuts\"): The company name created is \"doffee conuts\".\n- (\"donuts\", \"coffee\"): The company name created is \"conuts doffee\".\n- (\"donuts\", \"time\"): The company name created is \"tonuts dime\".\n- (\"donuts\", \"toffee\"): The company name created is \"tonuts doffee\".\n- (\"time\", \"donuts\"): The company name created is \"dime tonuts\".\n- (\"toffee\", \"donuts\"): The company name created is \"doffee tonuts\".\nTherefore, there are a total of 6 distinct company names.\n\nThe following are some examples of invalid selections:\n- (\"coffee\", \"time\"): The name \"toffee\" formed after swapping already exists in the original array.\n- (\"time\", \"toffee\"): Both names are still the same after swapping and exist in the original array.\n- (\"coffee\", \"toffee\"): Both names formed after swapping already exist in the original array.\nExample 2:\nInput: ideas = [\"lack\",\"back\"]\nOutput: 0\nExplanation: There are no valid selections. Therefore, 0 is returned.\n  Constraints:\n2 <= ideas.length <= 5 * 104\n1 <= ideas[i].length <= 10\nideas[i] consists of lowercase English letters.\nAll the strings in ideas are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/greatest-english-letter-in-upper-and-lower-case/discuss/2168442/Counter",
      "python_solutions": "class Solution:\n    def greatestLetter(self, s: str) -> str:\n        cnt = Counter(s)\n        return next((u for u in reversed(ascii_uppercase) if cnt[u] and cnt[u.lower()]), \"\")",
      "slug": "greatest-english-letter-in-upper-and-lower-case",
      "post_title": "Counter",
      "user": "votrubac",
      "upvotes": 37,
      "views": 2500,
      "problem_title": "greatest english letter in upper and lower case",
      "number": 2309,
      "acceptance": 0.6859999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 31796,
      "question": "Given a string of English letters s, return the greatest English letter which occurs as both a lowercase and uppercase letter in s. The returned letter should be in uppercase. If no such letter exists, return an empty string.\nAn English letter b is greater than another letter a if b appears after a in the English alphabet.\n  Example 1:\nInput: s = \"lEeTcOdE\"\nOutput: \"E\"\nExplanation:\nThe letter 'E' is the only letter to appear in both lower and upper case.\nExample 2:\nInput: s = \"arRAzFif\"\nOutput: \"R\"\nExplanation:\nThe letter 'R' is the greatest letter to appear in both lower and upper case.\nNote that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.\nExample 3:\nInput: s = \"AbCdEfGhIjK\"\nOutput: \"\"\nExplanation:\nThere is no letter that appears in both lower and upper case.\n  Constraints:\n1 <= s.length <= 1000\ns consists of lowercase and uppercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/sum-of-numbers-with-units-digit-k/discuss/2168546/Python-oror-Easy-Approach-oror-beats-90.00-Both-Runtime-and-Memory-oror-Remainder",
      "python_solutions": "class Solution:\n    def minimumNumbers(self, num: int, k: int) -> int:\n        \n        if num == 0:\n            return 0\n        \n        if num < k:\n            return -1\n        \n        if num == k:\n            return 1\n        \n        ans = -1\n        i = 1\n\n        while i <= 10:\n            if (num - i * k) % 10 == 0 and i * k <= num:\n                return i\n            i += 1\n\n        return ans",
      "slug": "sum-of-numbers-with-units-digit-k",
      "post_title": "\u2705Python || Easy Approach || beats 90.00% Both Runtime & Memory || Remainder",
      "user": "chuhonghao01",
      "upvotes": 1,
      "views": 43,
      "problem_title": "sum of numbers with units digit k",
      "number": 2310,
      "acceptance": 0.255,
      "difficulty": "Medium",
      "__index_level_0__": 31845,
      "question": "Given two integers num and k, consider a set of positive integers with the following properties:\nThe units digit of each integer is k.\nThe sum of the integers is num.\nReturn the minimum possible size of such a set, or -1 if no such set exists.\nNote:\nThe set can contain multiple instances of the same integer, and the sum of an empty set is considered 0.\nThe units digit of a number is the rightmost digit of the number.\n  Example 1:\nInput: num = 58, k = 9\nOutput: 2\nExplanation:\nOne valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\nAnother valid set is [19,39].\nIt can be shown that 2 is the minimum possible size of a valid set.\nExample 2:\nInput: num = 37, k = 2\nOutput: -1\nExplanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.\nExample 3:\nInput: num = 0, k = 7\nOutput: 0\nExplanation: The sum of an empty set is considered 0.\n  Constraints:\n0 <= num <= 3000\n0 <= k <= 9"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-binary-subsequence-less-than-or-equal-to-k/discuss/2168527/PythonororGreedyororFastororEasy-to-undestandoror-With-explanations",
      "python_solutions": "class Solution:\n    def longestSubsequence(self, s: str, k: int) -> int:\n        n = len(s)\n        ones = []\n\t\t# Notice how I reversed the string,\n\t\t# because the binary representation is written from greatest value of 2**n\n        for i, val in enumerate(s[::-1]):\n            if val == '1':\n                ones.append(i)\n\t\t# Initialize ans, there are already number of zeroes (num_of_zeroes = len(nums) - len(ones)\n        ans = n - len(ones)\n        i = 0\n\t\t# imagine k == 5 and binary string 001011\n\t\t# ones = [0, 1, 3]\n\t\t# first loop: 5 - 2**0 -> 4, ans += 1\n\t\t# second loop: 4 - 2**1 -> 2, ans +=1\n\t\t# Third loop does not occur because 2 - 2**3 -> -6 which is less than zero\n\t\t# So the ans is 3 + 2 = 5\n        while i < len(ones) and k - 2 ** ones[i] >= 0:\n            ans += 1\n            k -= 2 ** ones[i]\n            i += 1\n\t\n        return ans",
      "slug": "longest-binary-subsequence-less-than-or-equal-to-k",
      "post_title": "Python||Greedy||Fast||Easy to undestand|| With explanations",
      "user": "muctep_k",
      "upvotes": 5,
      "views": 127,
      "problem_title": "longest binary subsequence less than or equal to k",
      "number": 2311,
      "acceptance": 0.364,
      "difficulty": "Medium",
      "__index_level_0__": 31860,
      "question": "You are given a binary string s and a positive integer k.\nReturn the length of the longest subsequence of s that makes up a binary number less than or equal to k.\nNote:\nThe subsequence can contain leading zeroes.\nThe empty string is considered to be equal to 0.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\n  Example 1:\nInput: s = \"1001010\", k = 5\nOutput: 5\nExplanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is \"00010\", as this number is equal to 2 in decimal.\nNote that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\nThe length of this subsequence is 5, so 5 is returned.\nExample 2:\nInput: s = \"00101001\", k = 1\nOutput: 6\nExplanation: \"000001\" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.\nThe length of this subsequence is 6, so 6 is returned.\n  Constraints:\n1 <= s.length <= 1000\ns[i] is either '0' or '1'.\n1 <= k <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/selling-pieces-of-wood/discuss/2194345/Python-bottom-up-DP-faster-than-99",
      "python_solutions": "class Solution:\n    def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n        dp = [[0]*(n+1) for _ in range(m+1)]\n        for h, w, p in prices:\n            dp[h][w] = p\n        for i in range(1, m+1):\n            for j in range(1, n+1):\n                v = max(dp[k][j] + dp[i - k][j] for k in range(1, i // 2 + 1)) if i > 1 else 0\n                h = max(dp[i][k] + dp[i][j - k] for k in range(1, j // 2 + 1)) if j > 1 else 0\n                dp[i][j] = max(dp[i][j], v, h)\n        return dp[m][n]",
      "slug": "selling-pieces-of-wood",
      "post_title": "Python bottom up DP faster than 99%",
      "user": "metaphysicalist",
      "upvotes": 1,
      "views": 75,
      "problem_title": "selling pieces of wood",
      "number": 2312,
      "acceptance": 0.482,
      "difficulty": "Hard",
      "__index_level_0__": 31875,
      "question": "You are given two integers m and n that represent the height and width of a rectangular piece of wood. You are also given a 2D integer array prices, where prices[i] = [hi, wi, pricei] indicates you can sell a rectangular piece of wood of height hi and width wi for pricei dollars.\nTo cut a piece of wood, you must make a vertical or horizontal cut across the entire height or width of the piece to split it into two smaller pieces. After cutting a piece of wood into some number of smaller pieces, you can sell pieces according to prices. You may sell multiple pieces of the same shape, and you do not have to sell all the shapes. The grain of the wood makes a difference, so you cannot rotate a piece to swap its height and width.\nReturn the maximum money you can earn after cutting an m x n piece of wood.\nNote that you can cut the piece of wood as many times as you want.\n  Example 1:\nInput: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]\nOutput: 19\nExplanation: The diagram above shows a possible scenario. It consists of:\n- 2 pieces of wood shaped 2 x 2, selling for a price of 2 * 7 = 14.\n- 1 piece of wood shaped 2 x 1, selling for a price of 1 * 3 = 3.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 14 + 3 + 2 = 19 money earned.\nIt can be shown that 19 is the maximum amount of money that can be earned.\nExample 2:\nInput: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]\nOutput: 32\nExplanation: The diagram above shows a possible scenario. It consists of:\n- 3 pieces of wood shaped 3 x 2, selling for a price of 3 * 10 = 30.\n- 1 piece of wood shaped 1 x 4, selling for a price of 1 * 2 = 2.\nThis obtains a total of 30 + 2 = 32 money earned.\nIt can be shown that 32 is the maximum amount of money that can be earned.\nNotice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.\n  Constraints:\n1 <= m, n <= 200\n1 <= prices.length <= 2 * 104\nprices[i].length == 3\n1 <= hi <= m\n1 <= wi <= n\n1 <= pricei <= 106\nAll the shapes of wood (hi, wi) are pairwise distinct."
    },
    {
      "post_href": "https://leetcode.com/problems/count-asterisks/discuss/2484633/Python-Elegant-and-Short-or-Two-solutions-or-One-pass-One-line",
      "python_solutions": "class Solution:\n\t\"\"\"\n\tTime:   O(n)\n\tMemory: O(1)\n\t\"\"\"\n\n\tdef countAsterisks(self, s: str) -> int:\n\t\tis_closed = True\n\t\tcount = 0\n\n\t\tfor c in s:\n\t\t\tcount += is_closed * c == '*'\n\t\t\tis_closed ^= c == '|'\n\n\t\treturn count\n\n\nclass Solution:\n\t\"\"\"\n\tTime:   O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef countAsterisks(self, s: str) -> int:\n\t\treturn sum(chunk.count('*') for chunk in s.split('|')[0::2])",
      "slug": "count-asterisks",
      "post_title": "Python Elegant & Short | Two solutions | One pass / One line",
      "user": "Kyrylo-Ktl",
      "upvotes": 3,
      "views": 137,
      "problem_title": "count asterisks",
      "number": 2315,
      "acceptance": 0.825,
      "difficulty": "Easy",
      "__index_level_0__": 31877,
      "question": "You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.\nReturn the number of '*' in s, excluding the '*' between each pair of '|'.\nNote that each '|' will belong to exactly one pair.\n  Example 1:\nInput: s = \"l|*e*et|c**o|*de|\"\nOutput: 2\nExplanation: The considered characters are underlined: \"l|*e*et|c**o|*de|\".\nThe characters between the first and second '|' are excluded from the answer.\nAlso, the characters between the third and fourth '|' are excluded from the answer.\nThere are 2 asterisks considered. Therefore, we return 2.\nExample 2:\nInput: s = \"iamprogrammer\"\nOutput: 0\nExplanation: In this example, there are no asterisks in s. Therefore, we return 0.\nExample 3:\nInput: s = \"yo|uar|e**|b|e***au|tifu|l\"\nOutput: 5\nExplanation: The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.\n  Constraints:\n1 <= s.length <= 1000\ns consists of lowercase English letters, vertical bars '|', and asterisks '*'.\ns contains an even number of vertical bars '|'."
    },
    {
      "post_href": "https://leetcode.com/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/discuss/2199190/Simple-and-easy-to-understand-using-dfs-with-explanation-Python",
      "python_solutions": "class Solution:\n    def countPairs(self, n: int, edges: List[List[int]]) -> int:\n        def dfs(graph,node,visited):\n            visited.add(node)\n            self.c += 1\n            for child in graph[node]:\n                if child not in visited:\n                    dfs(graph, child, visited)\n        \n        #build graph\n        graph = {}\n        for i in range(n):\n            graph[i] = []\n            \n        for u, v in edges:\n            graph[u].append(v)\n            graph[v].append(u)\n        \n        visited = set()\n        count = 0\n        totalNodes = 0\n        \n        #run dfs in unvisited nodes\n        for i in range(n):\n            if i not in visited:\n                self.c = 0\n                dfs(graph, i, visited)\n                \n                count += totalNodes*self.c    # result \n                totalNodes += self.c          # total nodes visited \n        return count",
      "slug": "count-unreachable-pairs-of-nodes-in-an-undirected-graph",
      "post_title": "Simple and easy to understand using dfs with explanation [Python]",
      "user": "ratre21",
      "upvotes": 8,
      "views": 217,
      "problem_title": "count unreachable pairs of nodes in an undirected graph",
      "number": 2316,
      "acceptance": 0.386,
      "difficulty": "Medium",
      "__index_level_0__": 31909,
      "question": "You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.\nReturn the number of pairs of different nodes that are unreachable from each other.\n  Example 1:\nInput: n = 3, edges = [[0,1],[0,2],[1,2]]\nOutput: 0\nExplanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.\nExample 2:\nInput: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\nOutput: 14\nExplanation: There are 14 pairs of nodes that are unreachable from each other:\n[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].\nTherefore, we return 14.\n  Constraints:\n1 <= n <= 105\n0 <= edges.length <= 2 * 105\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nThere are no repeated edges."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-xor-after-operations/discuss/2366537/Python3-oror-1-line-bit-operations-w-explanation-oror-TM%3A-8887",
      "python_solutions": "class Solution:\n   def maximumXOR(self, nums: List[int]) -> int:\n       return reduce(lambda x,y: x|y, nums)\n\nclass Solution:\n   def maximumXOR(self, nums: List[int]) -> int:\n       return reduce(or_, nums)\n\nclass Solution:\n   def maximumXOR(self, nums: List[int]) -> int:\n       \n       ans = 0\n       for n in nums:\n           ans |= n      \n       return ans",
      "slug": "maximum-xor-after-operations",
      "post_title": "Python3     ||  1 line, bit operations, w/ explanation    ||    T/M: 88%/87%",
      "user": "warrenruud",
      "upvotes": 5,
      "views": 88,
      "problem_title": "maximum xor after operations",
      "number": 2317,
      "acceptance": 0.7859999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 31922,
      "question": "You are given a 0-indexed integer array nums. In one operation, select any non-negative integer x and an index i, then update nums[i] to be equal to nums[i] AND (nums[i] XOR x).\nNote that AND is the bitwise AND operation and XOR is the bitwise XOR operation.\nReturn the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.\n  Example 1:\nInput: nums = [3,2,4,6]\nOutput: 7\nExplanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\nNow, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\nIt can be shown that 7 is the maximum possible bitwise XOR.\nNote that other operations may be used to achieve a bitwise XOR of 7.\nExample 2:\nInput: nums = [1,2,3,9,2]\nOutput: 11\nExplanation: Apply the operation zero times.\nThe bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\nIt can be shown that 11 is the maximum possible bitwise XOR.\n  Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 108"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-distinct-roll-sequences/discuss/2196009/Python3-top-down-dp",
      "python_solutions": "class Solution:\n    def distinctSequences(self, n: int) -> int:\n        \n        @lru_cache\n        def fn(n, p0, p1): \n            \"\"\"Return total number of distinct sequences.\"\"\"\n            if n == 0: return 1\n            ans = 0\n            for x in range(1, 7): \n                if x not in (p0, p1) and gcd(x, p0) == 1: ans += fn(n-1, x, p0)\n            return ans % 1_000_000_007\n        \n        return fn(n, -1, -1)",
      "slug": "number-of-distinct-roll-sequences",
      "post_title": "[Python3] top-down dp",
      "user": "ye15",
      "upvotes": 2,
      "views": 48,
      "problem_title": "number of distinct roll sequences",
      "number": 2318,
      "acceptance": 0.562,
      "difficulty": "Hard",
      "__index_level_0__": 31929,
      "question": "You are given an integer n. You roll a fair 6-sided dice n times. Determine the total number of distinct sequences of rolls possible such that the following conditions are satisfied:\nThe greatest common divisor of any adjacent values in the sequence is equal to 1.\nThere is at least a gap of 2 rolls between equal valued rolls. More formally, if the value of the ith roll is equal to the value of the jth roll, then abs(i - j) > 2.\nReturn the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7.\nTwo sequences are considered distinct if at least one element is different.\n  Example 1:\nInput: n = 4\nOutput: 184\nExplanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.\nSome invalid sequences are (1, 2, 1, 3), (1, 2, 3, 6).\n(1, 2, 1, 3) is invalid since the first and third roll have an equal value and abs(1 - 3) = 2 (i and j are 1-indexed).\n(1, 2, 3, 6) is invalid since the greatest common divisor of 3 and 6 = 3.\nThere are a total of 184 distinct sequences possible, so we return 184.\nExample 2:\nInput: n = 2\nOutput: 22\nExplanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).\nSome invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.\nThere are a total of 22 distinct sequences possible, so we return 22.\n  Constraints:\n1 <= n <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/check-if-matrix-is-x-matrix/discuss/2368873/Easiest-Python-solution-you-will-find.......-Single-loop",
      "python_solutions": "class Solution:\n    def checkXMatrix(self, grid: List[List[int]]) -> bool:\n        a=0\n        j=len(grid)-1\n        for i in range(0,len(grid)):\n            if grid[i][i]==0 or grid[i][j]==0:\n                return False\n            else:\n                if i!=j:\n                    a=grid[i][i]+grid[i][j]\n                elif i==j:\n                    a=grid[i][i]\n            if a!=sum(grid[i]):\n                return False\n            j-=1\n        return True",
      "slug": "check-if-matrix-is-x-matrix",
      "post_title": "Easiest Python solution you will find....... Single loop",
      "user": "guneet100",
      "upvotes": 1,
      "views": 46,
      "problem_title": "check if matrix is x matrix",
      "number": 2319,
      "acceptance": 0.6729999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 31934,
      "question": "A square matrix is said to be an X-Matrix if both of the following conditions hold:\nAll the elements in the diagonals of the matrix are non-zero.\nAll other elements are 0.\nGiven a 2D integer array grid of size n x n representing a square matrix, return true if grid is an X-Matrix. Otherwise, return false.\n  Example 1:\nInput: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]\nOutput: true\nExplanation: Refer to the diagram above. \nAn X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\nThus, grid is an X-Matrix.\nExample 2:\nInput: grid = [[5,7,0],[0,3,1],[0,5,0]]\nOutput: false\nExplanation: Refer to the diagram above.\nAn X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\nThus, grid is not an X-Matrix.\n  Constraints:\nn == grid.length == grid[i].length\n3 <= n <= 100\n0 <= grid[i][j] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/count-number-of-ways-to-place-houses/discuss/2198265/Python-Simple-Solution-or-O(n)-time-complexity-or-Basic-Approach-or-DP",
      "python_solutions": "class Solution:\n    def countHousePlacements(self, n: int) -> int:\n        pre,ppre = 2,1\n        if n==1:\n            return 4\n        for i in range(1,n):\n            temp = pre+ppre \n            ppre = pre \n            pre = temp \n        return ((pre)**2)%((10**9) + 7)",
      "slug": "count-number-of-ways-to-place-houses",
      "post_title": "Python Simple Solution | O(n) time complexity | Basic Approach | DP",
      "user": "AkashHooda",
      "upvotes": 2,
      "views": 95,
      "problem_title": "count number of ways to place houses",
      "number": 2320,
      "acceptance": 0.401,
      "difficulty": "Medium",
      "__index_level_0__": 31953,
      "question": "There is a street with n * 2 plots, where there are n plots on each side of the street. The plots on each side are numbered from 1 to n. On each plot, a house can be placed.\nReturn the number of ways houses can be placed such that no two houses are adjacent to each other on the same side of the street. Since the answer may be very large, return it modulo 109 + 7.\nNote that if a house is placed on the ith plot on one side of the street, a house can also be placed on the ith plot on the other side of the street.\n  Example 1:\nInput: n = 1\nOutput: 4\nExplanation: \nPossible arrangements:\n1. All plots are empty.\n2. A house is placed on one side of the street.\n3. A house is placed on the other side of the street.\n4. Two houses are placed, one on each side of the street.\nExample 2:\nInput: n = 2\nOutput: 9\nExplanation: The 9 possible arrangements are shown in the diagram above.\n  Constraints:\n1 <= n <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-score-of-spliced-array/discuss/2198195/Python-or-Easy-to-Understand-or-With-Explanation-or-No-Kadane",
      "python_solutions": "class Solution:\n    def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:\n        # create a difference array between nums1 and nums2\n        # idea: find two subarray(elements are contiguous) in the diff\n        # one is the subarray that have the minimum negative sum\n        # another one is the subarray that have the maximum positive sum\n        # so there are four candidates for maximum score:\n        # 1. original_sum1 \n        # 2. original_sum \n        # 3. original_sum1 - min_negative_sum\n        # 4. original_sum2 + max_positive_sum\n        \n        original_sum1 = sum(nums1)\n        original_sum2 = sum(nums2)\n        diff = [num1 - num2 for num1, num2 in zip(nums1, nums2)]\n        min_negative_sum = float('inf')\n        max_positive_sum = - float('inf')\n        cur_negative_sum = 0\n        cur_positive_sum = 0\n        \n        for val in diff:\n            cur_negative_sum += val\n\n            if cur_negative_sum > 0:\n                cur_negative_sum = 0\n            \n            cur_positive_sum += val\n            \n            if cur_positive_sum < 0:\n                cur_positive_sum = 0\n                    \n            min_negative_sum = min(min_negative_sum, cur_negative_sum)\n            max_positive_sum = max(max_positive_sum, cur_positive_sum)\n\n        return max(original_sum1 - min_negative_sum, original_sum2 + max_positive_sum, original_sum2, original_sum1)",
      "slug": "maximum-score-of-spliced-array",
      "post_title": "Python | Easy to Understand | With Explanation | No Kadane",
      "user": "Mikey98",
      "upvotes": 2,
      "views": 150,
      "problem_title": "maximum score of spliced array",
      "number": 2321,
      "acceptance": 0.5539999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 31968,
      "question": "You are given two 0-indexed integer arrays nums1 and nums2, both of length n.\nYou can choose two integers left and right where 0 <= left <= right < n and swap the subarray nums1[left...right] with the subarray nums2[left...right].\nFor example, if nums1 = [1,2,3,4,5] and nums2 = [11,12,13,14,15] and you choose left = 1 and right = 2, nums1 becomes [1,12,13,4,5] and nums2 becomes [11,2,3,14,15].\nYou may choose to apply the mentioned operation once or not do anything.\nThe score of the arrays is the maximum of sum(nums1) and sum(nums2), where sum(arr) is the sum of all the elements in the array arr.\nReturn the maximum possible score.\nA subarray is a contiguous sequence of elements within an array. arr[left...right] denotes the subarray that contains the elements of nums between indices left and right (inclusive).\n  Example 1:\nInput: nums1 = [60,60,60], nums2 = [10,90,10]\nOutput: 210\nExplanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\nThe score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.\nExample 2:\nInput: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]\nOutput: 220\nExplanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\nThe score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.\nExample 3:\nInput: nums1 = [7,11,13], nums2 = [1,1,1]\nOutput: 31\nExplanation: We choose not to swap any subarray.\nThe score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.\n  Constraints:\nn == nums1.length == nums2.length\n1 <= n <= 105\n1 <= nums1[i], nums2[i] <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-score-after-removals-on-a-tree/discuss/2198386/Python3-dfs",
      "python_solutions": "class Solution:\n    def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:        \n        n = len(nums)\n        graph = [[] for _ in range(n)]\n        for u, v in edges: \n            graph[u].append(v)\n            graph[v].append(u)\n            \n        def fn(u): \n            score[u] = nums[u]\n            child[u] = {u}\n            for v in graph[u]: \n                if seen[v] == 0: \n                    seen[v] = 1\n                    fn(v)\n                    score[u] ^= score[v]\n                    child[u] |= child[v]\n        \n        seen = [1] + [0]*(n-1)\n        score = [0]*n\n        child = [set() for _ in range(n)]\n        fn(0)\n        \n        ans = inf \n        for u in range(1, n): \n            for v in range(u+1, n): \n                if u in child[v]: \n                    uu = score[u]\n                    vv = score[v] ^ score[u]\n                    xx = score[0] ^ score[v]\n                elif v in child[u]: \n                    uu = score[u] ^ score[v]\n                    vv = score[v]\n                    xx = score[0] ^ score[u]\n                else: \n                    uu = score[u]\n                    vv = score[v]\n                    xx = score[0] ^ score[u] ^ score[v]\n                ans = min(ans, max(uu, vv, xx) - min(uu, vv, xx))\n        return ans",
      "slug": "minimum-score-after-removals-on-a-tree",
      "post_title": "[Python3] dfs",
      "user": "ye15",
      "upvotes": 6,
      "views": 241,
      "problem_title": "minimum score after removals on a tree",
      "number": 2322,
      "acceptance": 0.506,
      "difficulty": "Hard",
      "__index_level_0__": 31980,
      "question": "There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\nYou are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\nRemove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:\nGet the XOR of all the values of the nodes for each of the three components respectively.\nThe difference between the largest XOR value and the smallest XOR value is the score of the pair.\nFor example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.\nReturn the minimum score of any possible pair of edge removals on the given tree.\n  Example 1:\nInput: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]\nOutput: 9\nExplanation: The diagram above shows a way to make a pair of removals.\n- The 1st component has nodes [1,3,4] with values [5,4,11]. Its XOR value is 5 ^ 4 ^ 11 = 10.\n- The 2nd component has node [0] with value [1]. Its XOR value is 1 = 1.\n- The 3rd component has node [2] with value [5]. Its XOR value is 5 = 5.\nThe score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\nIt can be shown that no other pair of removals will obtain a smaller score than 9.\nExample 2:\nInput: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]\nOutput: 0\nExplanation: The diagram above shows a way to make a pair of removals.\n- The 1st component has nodes [3,4] with values [4,4]. Its XOR value is 4 ^ 4 = 0.\n- The 2nd component has nodes [1,0] with values [5,5]. Its XOR value is 5 ^ 5 = 0.\n- The 3rd component has nodes [2,5] with values [2,2]. Its XOR value is 2 ^ 2 = 0.\nThe score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\nWe cannot obtain a smaller score than 0.\n  Constraints:\nn == nums.length\n3 <= n <= 1000\n1 <= nums[i] <= 108\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nedges represents a valid tree."
    },
    {
      "post_href": "https://leetcode.com/problems/decode-the-message/discuss/2229844/Easy-Python-solution-using-Hashing",
      "python_solutions": "class Solution:\n    def decodeMessage(self, key: str, message: str) -> str:\n        mapping = {' ': ' '}\n        i = 0\n        res = ''\n        letters = 'abcdefghijklmnopqrstuvwxyz'\n        \n        for char in key:\n            if char not in mapping:\n                mapping[char] = letters[i]\n                i += 1\n        \n        for char in message:\n            res += mapping[char]\n                \n        return res",
      "slug": "decode-the-message",
      "post_title": "Easy Python solution using Hashing",
      "user": "MiKueen",
      "upvotes": 23,
      "views": 1400,
      "problem_title": "decode the message",
      "number": 2325,
      "acceptance": 0.848,
      "difficulty": "Easy",
      "__index_level_0__": 31986,
      "question": "You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows:\nUse the first appearance of all 26 lowercase English letters in key as the order of the substitution table.\nAlign the substitution table with the regular English alphabet.\nEach letter in message is then substituted using the table.\nSpaces ' ' are transformed to themselves.\nFor example, given key = \"happy boy\" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f').\nReturn the decoded message.\n  Example 1:\nInput: key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"\nOutput: \"this is a secret\"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"the quick brown fox jumps over the lazy dog\".\nExample 2:\nInput: key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"\nOutput: \"the five boxing wizards jump quickly\"\nExplanation: The diagram above shows the substitution table.\nIt is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".\n  Constraints:\n26 <= key.length <= 2000\nkey consists of lowercase English letters and ' '.\nkey contains every letter in the English alphabet ('a' to 'z') at least once.\n1 <= message.length <= 2000\nmessage consists of lowercase English letters and ' '."
    },
    {
      "post_href": "https://leetcode.com/problems/spiral-matrix-iv/discuss/2230251/Python-easy-solution-using-direction-variable",
      "python_solutions": "class Solution:\n    def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n        \n        matrix = [[-1]*n for i in range(m)]\n        \n        current = head\n        direction = 1\n        i, j = 0, -1\n        \n        while current:\n            for _ in range(n):\n                if current:\n                    j += direction\n                    matrix[i][j] = current.val\n                    current = current.next\n                    \n            m -= 1\n            \n            for _ in range(m):\n                if current:\n                    i += direction\n                    matrix[i][j] = current.val\n                    current = current.next\n            n -= 1\n            \n            direction *= -1\n        \n        return matrix",
      "slug": "spiral-matrix-iv",
      "post_title": "Python easy solution using direction variable",
      "user": "HunkWhoCodes",
      "upvotes": 1,
      "views": 36,
      "problem_title": "spiral matrix iv",
      "number": 2326,
      "acceptance": 0.745,
      "difficulty": "Medium",
      "__index_level_0__": 32017,
      "question": "You are given two integers m and n, which represent the dimensions of a matrix.\nYou are also given the head of a linked list of integers.\nGenerate an m x n matrix that contains the integers in the linked list presented in spiral order (clockwise), starting from the top-left of the matrix. If there are remaining empty spaces, fill them with -1.\nReturn the generated matrix.\n  Example 1:\nInput: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\nOutput: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\nExplanation: The diagram above shows how the values are printed in the matrix.\nNote that the remaining spaces in the matrix are filled with -1.\nExample 2:\nInput: m = 1, n = 4, head = [0,1,2]\nOutput: [[0,1,2,-1]]\nExplanation: The diagram above shows how the values are printed from left to right in the matrix.\nThe last space in the matrix is set to -1.\n  Constraints:\n1 <= m, n <= 105\n1 <= m * n <= 105\nThe number of nodes in the list is in the range [1, m * n].\n0 <= Node.val <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-people-aware-of-a-secret/discuss/2229808/Two-Queues-or-Rolling-Array",
      "python_solutions": "class Solution:\n    def peopleAwareOfSecret(self, n: int, d: int, f: int) -> int:\n        dp, md = [1] + [0] * (f - 1), 10**9 + 7\n        for i in range(1, n):\n            dp[i % f] = (md + dp[(i + f - d) % f] - dp[i % f] + (0 if i == 1 else dp[(i - 1) % f])) % md\n        return sum(dp) % md",
      "slug": "number-of-people-aware-of-a-secret",
      "post_title": "Two Queues or Rolling Array",
      "user": "votrubac",
      "upvotes": 53,
      "views": 3300,
      "problem_title": "number of people aware of a secret",
      "number": 2327,
      "acceptance": 0.445,
      "difficulty": "Medium",
      "__index_level_0__": 32025,
      "question": "On day 1, one person discovers a secret.\nYou are given an integer delay, which means that each person will share the secret with a new person every day, starting from delay days after discovering the secret. You are also given an integer forget, which means that each person will forget the secret forget days after discovering it. A person cannot share the secret on the same day they forgot it, or on any day afterwards.\nGiven an integer n, return the number of people who know the secret at the end of day n. Since the answer may be very large, return it modulo 109 + 7.\n  Example 1:\nInput: n = 6, delay = 2, forget = 4\nOutput: 5\nExplanation:\nDay 1: Suppose the first person is named A. (1 person)\nDay 2: A is the only person who knows the secret. (1 person)\nDay 3: A shares the secret with a new person, B. (2 people)\nDay 4: A shares the secret with a new person, C. (3 people)\nDay 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\nDay 6: B shares the secret with E, and C shares the secret with F. (5 people)\nExample 2:\nInput: n = 4, delay = 1, forget = 3\nOutput: 6\nExplanation:\nDay 1: The first person is named A. (1 person)\nDay 2: A shares the secret with B. (2 people)\nDay 3: A and B share the secret with 2 new people, C and D. (4 people)\nDay 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)\n  Constraints:\n2 <= n <= 1000\n1 <= delay < forget <= n"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-increasing-paths-in-a-grid/discuss/2691096/Python-(Faster-than-94)-or-DFS-%2B-DP-O(N*M)-solution",
      "python_solutions": "class Solution:\n    def countPaths(self, grid: List[List[int]]) -> int:\n        rows, cols = len(grid), len(grid[0])\n        dp = {}\n        mod = (10 ** 9) + 7\n\n        def dfs(r, c, prev):\n            if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] <= prev:\n                return 0\n\n            if (r, c) in dp:\n                return dp[(r, c)]\n\n            pathLength = 1\n            pathLength += (dfs(r + 1, c, grid[r][c]) + dfs(r - 1, c, grid[r][c]) +\n                dfs(r, c + 1, grid[r][c]) + dfs(r, c - 1, grid[r][c]))\n            dp[(r, c)] = pathLength\n            return pathLength\n            \n        count = 0\n        for r in range(rows):\n            for c in range(cols):\n                count += dfs(r, c, 0)\n\n        return count % mod",
      "slug": "number-of-increasing-paths-in-a-grid",
      "post_title": "Python (Faster than 94%) | DFS + DP O(N*M) solution",
      "user": "KevinJM17",
      "upvotes": 0,
      "views": 3,
      "problem_title": "number of increasing paths in a grid",
      "number": 2328,
      "acceptance": 0.476,
      "difficulty": "Hard",
      "__index_level_0__": 32038,
      "question": "You are given an m x n integer matrix grid, where you can move from a cell to any adjacent cell in all 4 directions.\nReturn the number of strictly increasing paths in the grid such that you can start from any cell and end at any cell. Since the answer may be very large, return it modulo 109 + 7.\nTwo paths are considered different if they do not have exactly the same sequence of visited cells.\n  Example 1:\nInput: grid = [[1,1],[3,4]]\nOutput: 8\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [1], [3], [4].\n- Paths with length 2: [1 -> 3], [1 -> 4], [3 -> 4].\n- Paths with length 3: [1 -> 3 -> 4].\nThe total number of paths is 4 + 3 + 1 = 8.\nExample 2:\nInput: grid = [[1],[2]]\nOutput: 3\nExplanation: The strictly increasing paths are:\n- Paths with length 1: [1], [2].\n- Paths with length 2: [1 -> 2].\nThe total number of paths is 2 + 1 = 3.\n  Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 1000\n1 <= m * n <= 105\n1 <= grid[i][j] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/evaluate-boolean-binary-tree/discuss/2566445/Easy-python-6-line-solution",
      "python_solutions": "class Solution:\n    def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n            if root.val==0 or root.val==1:\n                return root.val\n            if root.val==2:\n                return self.evaluateTree(root.left) or self.evaluateTree(root.right)\n            if root.val==3:\n                return self.evaluateTree(root.left) and self.evaluateTree(root.right)",
      "slug": "evaluate-boolean-binary-tree",
      "post_title": "Easy python 6 line solution",
      "user": "shubham_1307",
      "upvotes": 6,
      "views": 282,
      "problem_title": "evaluate boolean binary tree",
      "number": 2331,
      "acceptance": 0.7909999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 32044,
      "question": "You are given the root of a full binary tree with the following properties:\nLeaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.\nNon-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.\nThe evaluation of a node is as follows:\nIf the node is a leaf node, the evaluation is the value of the node, i.e. True or False.\nOtherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.\nReturn the boolean result of evaluating the root node.\nA full binary tree is a binary tree where each node has either 0 or 2 children.\nA leaf node is a node that has zero children.\n  Example 1:\nInput: root = [2,1,3,null,null,0,1]\nOutput: true\nExplanation: The above diagram illustrates the evaluation process.\nThe AND node evaluates to False AND True = False.\nThe OR node evaluates to True OR False = True.\nThe root node evaluates to True, so we return true.\nExample 2:\nInput: root = [0]\nOutput: false\nExplanation: The root node is a leaf node and it evaluates to false, so we return false.\n  Constraints:\nThe number of nodes in the tree is in the range [1, 1000].\n0 <= Node.val <= 3\nEvery node has either 0 or 2 children.\nLeaf nodes have a value of 0 or 1.\nNon-leaf nodes have a value of 2 or 3."
    },
    {
      "post_href": "https://leetcode.com/problems/the-latest-time-to-catch-a-bus/discuss/2259189/Clean-and-Concise-Greedy-with-Intuitive-Explanation",
      "python_solutions": "class Solution:\n    def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:\n        buses.sort()\n        passengers.sort()\n        \n        passenger = 0\n        for bus in buses:\n            maxed_out = False\n            cap = capacity\n            \n            while passenger < len(passengers) and passengers[passenger] <= bus and cap != 0:\n                passenger += 1\n                cap -= 1\n                \n            if cap == 0:\n                maxed_out = True\n                \n        if maxed_out:\n            max_seat = passengers[passenger - 1]\n        else:\n            max_seat = buses[-1]\n    \n        booked = set(passengers)\n        for seat in range(max_seat, 0, -1):\n            if seat not in booked:\n                return seat",
      "slug": "the-latest-time-to-catch-a-bus",
      "post_title": "Clean and Concise Greedy with Intuitive Explanation",
      "user": "wickedmishra",
      "upvotes": 5,
      "views": 472,
      "problem_title": "the latest time to catch a bus",
      "number": 2332,
      "acceptance": 0.2289999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 32058,
      "question": "You are given a 0-indexed integer array buses of length n, where buses[i] represents the departure time of the ith bus. You are also given a 0-indexed integer array passengers of length m, where passengers[j] represents the arrival time of the jth passenger. All bus departure times are unique. All passenger arrival times are unique.\nYou are given an integer capacity, which represents the maximum number of passengers that can get on each bus.\nWhen a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at x minutes if you arrive at y minutes where y <= x, and the bus is not full. Passengers with the earliest arrival times get on the bus first.\nMore formally when a bus arrives, either:\nIf capacity or fewer passengers are waiting for a bus, they will all get on the bus, or\nThe capacity passengers with the earliest arrival times will get on the bus.\nReturn the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.\nNote: The arrays buses and passengers are not necessarily sorted.\n  Example 1:\nInput: buses = [10,20], passengers = [2,17,18,19], capacity = 2\nOutput: 16\nExplanation: Suppose you arrive at time 16.\nAt time 10, the first bus departs with the 0th passenger. \nAt time 20, the second bus departs with you and the 1st passenger.\nNote that you may not arrive at the same time as another passenger, which is why you must arrive before the 1st passenger to catch the bus.\nExample 2:\nInput: buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2\nOutput: 20\nExplanation: Suppose you arrive at time 20.\nAt time 10, the first bus departs with the 3rd passenger. \nAt time 20, the second bus departs with the 5th and 1st passengers.\nAt time 30, the third bus departs with the 0th passenger and you.\nNotice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus.\n  Constraints:\nn == buses.length\nm == passengers.length\n1 <= n, m, capacity <= 105\n2 <= buses[i], passengers[i] <= 109\nEach element in buses is unique.\nEach element in passengers is unique."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-sum-of-squared-difference/discuss/2259712/Python-Easy-to-understand-binary-search-solution",
      "python_solutions": "class Solution:\n    def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:\n        n = len(nums1)\n        k = k1+k2 # can combine k's because items can be turned negative\n        diffs = sorted((abs(x - y) for x, y in zip(nums1, nums2)))\n        \n        # First binary search to find our new max for our diffs array\n        l, r = 0, max(diffs)\n        while l < r:\n            mid = (l+r)//2\n            \n            # steps needed to reduce all nums greater than newMax\n            steps = sum(max(0, num-mid) for num in diffs)\n            \n            if steps <= k:\n                r = mid\n            else:\n                l = mid+1\n                \n        newMax = l\n        k -= sum(max(0, num-newMax) for num in diffs) # remove used k\n\n        # Second binary search to find first index to replace with max val\n        l, r = 0, n-1\n        while l < r:\n            mid = (l+r)//2\n            if diffs[mid] < newMax:\n                l = mid+1\n            else:\n                r = mid\n\n        # Replace items at index >= l with newMax\n        diffs = diffs[:l]+[newMax]*(n-l)\n        \n        # Use remaining steps to reduce overall score\n        for i in range(len(diffs)-1,-1,-1):\n            if k == 0 or diffs[i] == 0: break\n            diffs[i] -= 1\n            k -= 1\n            \n        return sum(diff*diff for diff in diffs)",
      "slug": "minimum-sum-of-squared-difference",
      "post_title": "[Python] Easy to understand binary search solution",
      "user": "fomiee",
      "upvotes": 1,
      "views": 106,
      "problem_title": "minimum sum of squared difference",
      "number": 2333,
      "acceptance": 0.255,
      "difficulty": "Medium",
      "__index_level_0__": 32063,
      "question": "You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.\nThe sum of squared difference of arrays nums1 and nums2 is defined as the sum of (nums1[i] - nums2[i])2 for each 0 <= i < n.\nYou are also given two positive integers k1 and k2. You can modify any of the elements of nums1 by +1 or -1 at most k1 times. Similarly, you can modify any of the elements of nums2 by +1 or -1 at most k2 times.\nReturn the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.\nNote: You are allowed to modify the array elements to become negative integers.\n  Example 1:\nInput: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0\nOutput: 579\nExplanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \nThe sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.\nExample 2:\nInput: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1\nOutput: 43\nExplanation: One way to obtain the minimum sum of square difference is: \n- Increase nums1[0] once.\n- Increase nums2[2] once.\nThe minimum of the sum of square difference will be: \n(2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43.\nNote that, there are other ways to obtain the minimum of the sum of square difference, but there is no way to obtain a sum smaller than 43.\n  Constraints:\nn == nums1.length == nums2.length\n1 <= n <= 105\n0 <= nums1[i], nums2[i] <= 105\n0 <= k1, k2 <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/subarray-with-elements-greater-than-varying-threshold/discuss/2260689/Python3.-oror-Stack-9-lines-oror-TM-%3A-986-ms28-MB",
      "python_solutions": "class Solution:\n    def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n                            # Stack elements are the array's indices idx, and montonic with respect to nums[idx].\n                            # When the index of the nearest smaller value to nums[idx] comes to the top of the \n                            # stack, we check whether the threshold criterion is satisfied. If so, we are done.\n                            #  If not, we continue. Return -1 if we reach the end of nums without a winner.\n\t\t\t\t\t\t\t\n        nums.append(0)\n        stack = deque()\n\n        for idx in range(len(nums)):\n\n            while stack and nums[idx] <= nums[stack[-1]]:           \n                n = nums[stack.pop()]                               # n is the next smaller value for nums[idx]\n                k = idx if not stack else idx - stack[-1] -1        \n                if n > threshold //k: return k                      # threshold criterion. if n passes, all\n                                                                    # elements of the interval pass\n            stack.append(idx)\n\n        return -1",
      "slug": "subarray-with-elements-greater-than-varying-threshold",
      "post_title": "Python3.  ||     Stack, 9 lines   ||   T/M : 986 ms/28 MB",
      "user": "warrenruud",
      "upvotes": 7,
      "views": 101,
      "problem_title": "subarray with elements greater than varying threshold",
      "number": 2334,
      "acceptance": 0.4039999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 32070,
      "question": "You are given an integer array nums and an integer threshold.\nFind any subarray of nums of length k such that every element in the subarray is greater than threshold / k.\nReturn the size of any such subarray. If there is no such subarray, return -1.\nA subarray is a contiguous non-empty sequence of elements within an array.\n  Example 1:\nInput: nums = [1,3,4,3,1], threshold = 6\nOutput: 3\nExplanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.\nNote that this is the only valid subarray.\nExample 2:\nInput: nums = [6,5,6,5,8], threshold = 7\nOutput: 1\nExplanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.\nNote that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \nSimilarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\nTherefore, 2, 3, 4, or 5 may also be returned.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i], threshold <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-amount-of-time-to-fill-cups/discuss/2262041/Python-or-Straightforward-MaxHeap-Solution",
      "python_solutions": "class Solution:\n    def fillCups(self, amount: List[int]) -> int:\n        pq = [-q for q in amount if q != 0]\n        heapq.heapify(pq)\n        ret = 0\n        \n        while len(pq) > 1:\n            first = heapq.heappop(pq)\n            second = heapq.heappop(pq)\n            first += 1\n            second += 1\n            ret += 1\n            if first:\n                heapq.heappush(pq, first)\n            if second:\n                heapq.heappush(pq, second)\n\n        if pq:\n            return ret - pq[0]\n        else:\n            return ret",
      "slug": "minimum-amount-of-time-to-fill-cups",
      "post_title": "Python |  Straightforward MaxHeap Solution",
      "user": "lukefall425",
      "upvotes": 7,
      "views": 563,
      "problem_title": "minimum amount of time to fill cups",
      "number": 2335,
      "acceptance": 0.555,
      "difficulty": "Easy",
      "__index_level_0__": 32075,
      "question": "You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.\nYou are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.\n  Example 1:\nInput: amount = [1,4,2]\nOutput: 4\nExplanation: One way to fill up the cups is:\nSecond 1: Fill up a cold cup and a warm cup.\nSecond 2: Fill up a warm cup and a hot cup.\nSecond 3: Fill up a warm cup and a hot cup.\nSecond 4: Fill up a warm cup.\nIt can be proven that 4 is the minimum number of seconds needed.\nExample 2:\nInput: amount = [5,4,4]\nOutput: 7\nExplanation: One way to fill up the cups is:\nSecond 1: Fill up a cold cup, and a hot cup.\nSecond 2: Fill up a cold cup, and a warm cup.\nSecond 3: Fill up a cold cup, and a warm cup.\nSecond 4: Fill up a warm cup, and a hot cup.\nSecond 5: Fill up a cold cup, and a hot cup.\nSecond 6: Fill up a cold cup, and a warm cup.\nSecond 7: Fill up a hot cup.\nExample 3:\nInput: amount = [5,0,0]\nOutput: 5\nExplanation: Every second, we fill up a cold cup.\n  Constraints:\namount.length == 3\n0 <= amount[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/move-pieces-to-obtain-a-string/discuss/2274805/Python3-oror-10-lines-w-explanation-oror-TM%3A-96-44",
      "python_solutions": "class Solution:\n                    # Criteria for a valid transormation:\n\n                    #   1) The # of Ls, # of Rs , and # of _s must be equal between the two strings\n                    #\n                    #   2) The ordering of Ls and Rs in the two strings must be the same.\n                    #\n                    #   3) Ls can only move left and Rs can only move right, so each L in start \n                    #      cannot be to the left of its corresponding L in target, and each R cannot\n                    #      be to the right of its corresponding R in target.\n\n    def canChange(self, start: str, target: str) -> bool:\n                                                          \n        if (len(start) != len(target) or \n            start.count('_') != target.count('_')): return False   #  <-- Criterion 1\n\n        s = [(ch,i) for i, ch in enumerate(start ) if ch != '_']\n        t = [(ch,i) for i, ch in enumerate(target) if ch != '_']\n\n        for i in range(len(s)):\n            (sc, si), (tc,ti) = s[i], t[i]\n            if sc != tc: return False                              # <-- Criteria 1 & 2\n            if sc == 'L' and si < ti: return False                 # <-- Criterion 3\n            if sc == 'R' and si > ti: return False                 # <--/\n\n        return True                                                # <-- It's a winner!",
      "slug": "move-pieces-to-obtain-a-string",
      "post_title": "Python3   ||    10 lines, w/ explanation  ||    T/M: 96%/ 44%",
      "user": "warrenruud",
      "upvotes": 3,
      "views": 127,
      "problem_title": "move pieces to obtain a string",
      "number": 2337,
      "acceptance": 0.481,
      "difficulty": "Medium",
      "__index_level_0__": 32090,
      "question": "You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where:\nThe characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.\nThe character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces.\nReturn true if it is possible to obtain the string target by moving the pieces of the string start any number of times. Otherwise, return false.\n  Example 1:\nInput: start = \"_L__R__R_\", target = \"L______RR\"\nOutput: true\nExplanation: We can obtain the string target from start by doing the following moves:\n- Move the first piece one step to the left, start becomes equal to \"L___R__R_\".\n- Move the last piece one step to the right, start becomes equal to \"L___R___R\".\n- Move the second piece three steps to the right, start becomes equal to \"L______RR\".\nSince it is possible to get the string target from start, we return true.\nExample 2:\nInput: start = \"R_L_\", target = \"__LR\"\nOutput: false\nExplanation: The 'R' piece in the string start can move one step to the right to obtain \"_RL_\".\nAfter that, no pieces can move anymore, so it is impossible to obtain the string target from start.\nExample 3:\nInput: start = \"_R\", target = \"R_\"\nOutput: false\nExplanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.\n  Constraints:\nn == start.length == target.length\n1 <= n <= 105\nstart and target consist of the characters 'L', 'R', and '_'."
    },
    {
      "post_href": "https://leetcode.com/problems/count-the-number-of-ideal-arrays/discuss/2261351/Python3-freq-table",
      "python_solutions": "class Solution:\n    def idealArrays(self, n: int, maxValue: int) -> int:\n        ans = maxValue\n        freq = {x : 1 for x in range(1, maxValue+1)}\n        for k in range(1, n): \n            temp = Counter()\n            for x in freq: \n                for m in range(2, maxValue//x+1): \n                    ans += comb(n-1, k)*freq[x]\n                    temp[m*x] += freq[x]\n            freq = temp\n            ans %= 1_000_000_007\n        return ans",
      "slug": "count-the-number-of-ideal-arrays",
      "post_title": "[Python3] freq table",
      "user": "ye15",
      "upvotes": 26,
      "views": 1500,
      "problem_title": "count the number of ideal arrays",
      "number": 2338,
      "acceptance": 0.255,
      "difficulty": "Hard",
      "__index_level_0__": 32101,
      "question": "You are given two integers n and maxValue, which are used to describe an ideal array.\nA 0-indexed integer array arr of length n is considered ideal if the following conditions hold:\nEvery arr[i] is a value from 1 to maxValue, for 0 <= i < n.\nEvery arr[i] is divisible by arr[i - 1], for 0 < i < n.\nReturn the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7.\n  Example 1:\nInput: n = 2, maxValue = 5\nOutput: 10\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (5 arrays): [1,1], [1,2], [1,3], [1,4], [1,5]\n- Arrays starting with the value 2 (2 arrays): [2,2], [2,4]\n- Arrays starting with the value 3 (1 array): [3,3]\n- Arrays starting with the value 4 (1 array): [4,4]\n- Arrays starting with the value 5 (1 array): [5,5]\nThere are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.\nExample 2:\nInput: n = 5, maxValue = 3\nOutput: 11\nExplanation: The following are the possible ideal arrays:\n- Arrays starting with the value 1 (9 arrays): \n   - With no other distinct values (1 array): [1,1,1,1,1] \n   - With 2nd distinct value 2 (4 arrays): [1,1,1,1,2], [1,1,1,2,2], [1,1,2,2,2], [1,2,2,2,2]\n   - With 2nd distinct value 3 (4 arrays): [1,1,1,1,3], [1,1,1,3,3], [1,1,3,3,3], [1,3,3,3,3]\n- Arrays starting with the value 2 (1 array): [2,2,2,2,2]\n- Arrays starting with the value 3 (1 array): [3,3,3,3,3]\nThere are a total of 9 + 1 + 1 = 11 distinct ideal arrays.\n  Constraints:\n2 <= n <= 104\n1 <= maxValue <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-number-of-pairs-in-array/discuss/2472693/Python-Elegant-and-Short-or-Two-lines-or-99.91-faster-or-Counter",
      "python_solutions": "class Solution:\n\t\"\"\"\n\tTime:   O(n)\n\tMemory: O(n)\n\t\"\"\"\n\n\tdef numberOfPairs(self, nums: List[int]) -> List[int]:\n\t\tpairs = sum(cnt // 2 for cnt in Counter(nums).values())\n\t\treturn [pairs, len(nums) - 2 * pairs]",
      "slug": "maximum-number-of-pairs-in-array",
      "post_title": "Python Elegant & Short | Two lines | 99.91% faster | Counter",
      "user": "Kyrylo-Ktl",
      "upvotes": 5,
      "views": 171,
      "problem_title": "maximum number of pairs in array",
      "number": 2341,
      "acceptance": 0.7659999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 32106,
      "question": "You are given a 0-indexed integer array nums. In one operation, you may do the following:\nChoose two integers in nums that are equal.\nRemove both integers from nums, forming a pair.\nThe operation is done on nums as many times as possible.\nReturn a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.\n  Example 1:\nInput: nums = [1,3,2,1,3,2,2]\nOutput: [3,1]\nExplanation:\nForm a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\nForm a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\nForm a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\nNo more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.\nExample 2:\nInput: nums = [1,1]\nOutput: [1,0]\nExplanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\nNo more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.\nExample 3:\nInput: nums = [0]\nOutput: [0,1]\nExplanation: No pairs can be formed, and there is 1 number leftover in nums.\n  Constraints:\n1 <= nums.length <= 100\n0 <= nums[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/max-sum-of-a-pair-with-equal-sum-of-digits/discuss/2297244/Python3-oror-dict(heaps)-8-lines-w-explanation-oror-TM%3A-1300ms27MB",
      "python_solutions": "class Solution:     # The plan here is to:\n                    # \n                    #   \u2022 sort the elements of nums into a dict of maxheaps,\n                    #     according to sum-of-digits.\n                    #\n                    #   \u2022 For each key, determine whether there are at least two \n                    #     elements in that key's values, and if so, compute the\n                    #     product of the greatest two elements.\n                    #\n                    #   \u2022 return the the greatest such product as the answer.\n\n                    # For example:\n\t\t\t\t\t\n                    #     nums = [6,15,13,12,24,21] \u2013> {3:[12,21], 4:[13], 6:[6,15,24]}\n\t\t\t\t\t\n                    #     Only two keys qualify, 3 and 6, for which the greatest two elements\n                    #     are 12,21 and 15,24, respectively. 12+21 = 33 and 15+24 = 39,\n                    #     so the answer is 39.\n\n    def maximumSum(self, nums: List[int]) -> int:\n        d, mx = defaultdict(list), -1\n        digits = lambda x: sum(map(int, list(str(x))))      # <-- sum-of-digits function\n       \n        for n in nums:                                      # <-- construct max-heaps\n            heappush(d[digits(n)],-n)                       #     (note \"-n\") \n\n        for i in d:                                         # <-- pop the two greatest values off\n            if len(d[i]) > 1:                               #     each maxheap (when possible) and\n                mx= max(mx, -heappop(d[i])-heappop(d[i]))   #     compare with current max value.\n                                                           \n        return mx",
      "slug": "max-sum-of-a-pair-with-equal-sum-of-digits",
      "post_title": "Python3 || dict(heaps), 8 lines, w/ explanation   ||  T/M: 1300ms/27MB",
      "user": "warrenruud",
      "upvotes": 3,
      "views": 111,
      "problem_title": "max sum of a pair with equal sum of digits",
      "number": 2342,
      "acceptance": 0.532,
      "difficulty": "Medium",
      "__index_level_0__": 32140,
      "question": "You are given a 0-indexed array nums consisting of positive integers. You can choose two indices i and j, such that i != j, and the sum of digits of the number nums[i] is equal to that of nums[j].\nReturn the maximum value of nums[i] + nums[j] that you can obtain over all possible indices i and j that satisfy the conditions.\n  Example 1:\nInput: nums = [18,43,36,13,7]\nOutput: 54\nExplanation: The pairs (i, j) that satisfy the conditions are:\n- (0, 2), both numbers have a sum of digits equal to 9, and their sum is 18 + 36 = 54.\n- (1, 4), both numbers have a sum of digits equal to 7, and their sum is 43 + 7 = 50.\nSo the maximum sum that we can obtain is 54.\nExample 2:\nInput: nums = [10,12,19,14]\nOutput: -1\nExplanation: There are no two numbers that satisfy the conditions, so we return -1.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/query-kth-smallest-trimmed-number/discuss/2296143/Python-O(m-*-n)-solution-based-on-O(m)-counting-sort",
      "python_solutions": "class Solution:\n  def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:\n        def countingSort(indices, pos):\n            count = [0] * 10\n            for idx in indices:\n                count[ord(nums[idx][pos]) - ord('0')] += 1\n            start_pos = list(accumulate([0] + count, add))\n            result = [None] * len(indices)\n            for idx in indices:\n                digit = ord(nums[idx][pos]) - ord('0')\n                result[start_pos[digit]] = idx\n                start_pos[digit] += 1\n            return result\n            \n        n = len(nums)\n        m = len(nums[0])\n        suffix_ordered = [list(range(n))]\n        for i in range(m - 1, -1, -1):\n            suffix_ordered.append(countingSort(suffix_ordered[-1], i))\n        return [suffix_ordered[t][k-1] for k, t in queries]",
      "slug": "query-kth-smallest-trimmed-number",
      "post_title": "Python O(m * n) solution based on O(m) counting sort",
      "user": "lifuh",
      "upvotes": 2,
      "views": 99,
      "problem_title": "query kth smallest trimmed number",
      "number": 2343,
      "acceptance": 0.408,
      "difficulty": "Medium",
      "__index_level_0__": 32159,
      "question": "You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits.\nYou are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to:\nTrim each number in nums to its rightmost trimi digits.\nDetermine the index of the kith smallest trimmed number in nums. If two trimmed numbers are equal, the number with the lower index is considered to be smaller.\nReset each number in nums to its original length.\nReturn an array answer of the same length as queries, where answer[i] is the answer to the ith query.\nNote:\nTo trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain.\nStrings in nums may contain leading zeros.\n  Example 1:\nInput: nums = [\"102\",\"473\",\"251\",\"814\"], queries = [[1,1],[2,3],[4,2],[1,2]]\nOutput: [2,2,1,0]\nExplanation:\n1. After trimming to the last digit, nums = [\"2\",\"3\",\"1\",\"4\"]. The smallest number is 1 at index 2.\n2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.\n3. Trimmed to the last 2 digits, nums = [\"02\",\"73\",\"51\",\"14\"]. The 4th smallest number is 73.\n4. Trimmed to the last 2 digits, the smallest number is 2 at index 0.\n   Note that the trimmed number \"02\" is evaluated as 2.\nExample 2:\nInput: nums = [\"24\",\"37\",\"96\",\"04\"], queries = [[2,1],[2,2]]\nOutput: [3,0]\nExplanation:\n1. Trimmed to the last digit, nums = [\"4\",\"7\",\"6\",\"4\"]. The 2nd smallest number is 4 at index 3.\n   There are two occurrences of 4, but the one at index 0 is considered smaller than the one at index 3.\n2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.\n  Constraints:\n1 <= nums.length <= 100\n1 <= nums[i].length <= 100\nnums[i] consists of only digits.\nAll nums[i].length are equal.\n1 <= queries.length <= 100\nqueries[i].length == 2\n1 <= ki <= nums.length\n1 <= trimi <= nums[i].length\n  Follow up: Could you use the Radix Sort Algorithm to solve this problem? What will be the complexity of that solution?"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-deletions-to-make-array-divisible/discuss/2296334/Python3-oror-GCD-and-heap-6-lines-w-explanation-oror-TM%3A-56100",
      "python_solutions": "class Solution:\n                    # From number theory, we know that an integer num divides each\n                    # integer in a list if and only if num divides the list's gcd.\n                    # \n                    # Our plan here is to:\n                    #   \u2022 find the gcd of numDivide\n                    #   \u2022 heapify(nums) and count the popped elements that do not\n                    #     divide the gcd.\n                    #   \u2022 return that count when and if a popped element eventually\n                    #     divides the gcd. If that never happens, return -1 \n        \n    def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:\n\t\n        g, ans = gcd(*numsDivide), 0            # <-- find gcd (using * operator)\n\n        heapify(nums)                           # <-- create heap\n\n        while nums:                             # <-- pop and count\n\n            if not g%heappop(nums): return ans  # <-- found a divisor? return count\n            else: ans+= 1                       # <-- if not, increment the count\n\n        return -1                               # <-- no divisors found\n\t\t\n#--------------------------------------------------\nclass Solution:    # version w/o heap. Seems to run slower\n    def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:\n\t\n        g = gcd(*numsDivide)\n        nums.sort()\n\n        for i,num in enumerate(nums):\n            if not g%num: return i\n\n        return -1",
      "slug": "minimum-deletions-to-make-array-divisible",
      "post_title": "Python3 || GCD and heap, 6 lines, w/ explanation   ||  T/M: 56%/100%",
      "user": "warrenruud",
      "upvotes": 3,
      "views": 37,
      "problem_title": "minimum deletions to make array divisible",
      "number": 2344,
      "acceptance": 0.57,
      "difficulty": "Hard",
      "__index_level_0__": 32177,
      "question": "You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.\nReturn the minimum number of deletions such that the smallest element in nums divides all the elements of numsDivide. If this is not possible, return -1.\nNote that an integer x divides y if y % x == 0.\n  Example 1:\nInput: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]\nOutput: 2\nExplanation: \nThe smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.\nWe use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].\nThe smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.\nIt can be shown that 2 is the minimum number of deletions needed.\nExample 2:\nInput: nums = [4,3,6], numsDivide = [8,2,6,10]\nOutput: -1\nExplanation: \nWe want the smallest element in nums to divide all the elements of numsDivide.\nThere is no way to delete elements from nums to allow this.\n  Constraints:\n1 <= nums.length, numsDivide.length <= 105\n1 <= nums[i], numsDivide[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/best-poker-hand/discuss/2322411/Python-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n\n        dictRanks = {}\n        dictSuits = {}\n        \n        for key in ranks:\n            dictRanks[key] = dictRanks.get(key, 0) + 1\n\n        for key in suits:\n            dictSuits[key] = dictSuits.get(key, 0) + 1\n            \n        maxRanks = max(dictRanks.values())\n        maxSuits = max(dictSuits.values())\n        \n        if maxSuits == 5:\n            return \"Flush\"\n        if maxRanks >= 3:\n            return \"Three of a Kind\"\n        if maxRanks >= 2:\n            return \"Pair\" \n        return \"High Card\"",
      "slug": "best-poker-hand",
      "post_title": "\u2705Python ||  Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 3,
      "views": 116,
      "problem_title": "best poker hand",
      "number": 2347,
      "acceptance": 0.606,
      "difficulty": "Easy",
      "__index_level_0__": 32188,
      "question": "You are given an integer array ranks and a character array suits. You have 5 cards where the ith card has a rank of ranks[i] and a suit of suits[i].\nThe following are the types of poker hands you can make from best to worst:\n\"Flush\": Five cards of the same suit.\n\"Three of a Kind\": Three cards of the same rank.\n\"Pair\": Two cards of the same rank.\n\"High Card\": Any single card.\nReturn a string representing the best type of poker hand you can make with the given cards.\nNote that the return values are case-sensitive.\n  Example 1:\nInput: ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]\nOutput: \"Flush\"\nExplanation: The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".\nExample 2:\nInput: ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]\nOutput: \"Three of a Kind\"\nExplanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a \"Three of a Kind\".\nNote that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\nAlso note that other cards could be used to make the \"Three of a Kind\" hand.\nExample 3:\nInput: ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]\nOutput: \"Pair\"\nExplanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\nNote that we cannot make a \"Flush\" or a \"Three of a Kind\".\n  Constraints:\nranks.length == suits.length == 5\n1 <= ranks[i] <= 13\n'a' <= suits[i] <= 'd'\nNo two cards have the same rank and suit."
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-zero-filled-subarrays/discuss/2322455/Python-oror-Two-pointers-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def zeroFilledSubarray(self, nums: List[int]) -> int:\n        \n        n = len(nums)\n\n        ans = 0\n        i, j = 0, 0\n        while i <= n - 1:\n            j = 0\n            if nums[i] == 0:\n                while i + j <= n - 1 and nums[i + j] == 0:\n                    j += 1\n                ans += (j + 1) * j // 2\n\n            i = i + j + 1\n        \n        return ans",
      "slug": "number-of-zero-filled-subarrays",
      "post_title": "\u2705Python || Two-pointers || Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 2,
      "views": 72,
      "problem_title": "number of zero filled subarrays",
      "number": 2348,
      "acceptance": 0.5710000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 32201,
      "question": "Given an integer array nums, return the number of subarrays filled with 0.\nA subarray is a contiguous non-empty sequence of elements within an array.\n  Example 1:\nInput: nums = [1,3,0,0,2,0,0,4]\nOutput: 6\nExplanation: \nThere are 4 occurrences of [0] as a subarray.\nThere are 2 occurrences of [0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.\nExample 2:\nInput: nums = [0,0,0,2,0,0]\nOutput: 9\nExplanation:\nThere are 5 occurrences of [0] as a subarray.\nThere are 3 occurrences of [0,0] as a subarray.\nThere is 1 occurrence of [0,0,0] as a subarray.\nThere is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.\nExample 3:\nInput: nums = [2,10,2019]\nOutput: 0\nExplanation: There is no subarray filled with 0. Therefore, we return 0.\n  Constraints:\n1 <= nums.length <= 105\n-109 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/shortest-impossible-sequence-of-rolls/discuss/2351553/100-faster-at-my-time-or-easy-python3-solution",
      "python_solutions": "class Solution:\n    def shortestSequence(self, rolls: List[int], k: int) -> int:\n        ans = 0 \n        seen = set()\n        for x in rolls: \n            seen.add(x)\n            if len(seen) == k: \n                ans += 1\n                seen.clear()\n        return ans+1",
      "slug": "shortest-impossible-sequence-of-rolls",
      "post_title": "100% faster at my time | easy python3 solution",
      "user": "vimla_kushwaha",
      "upvotes": 1,
      "views": 40,
      "problem_title": "shortest impossible sequence of rolls",
      "number": 2350,
      "acceptance": 0.684,
      "difficulty": "Hard",
      "__index_level_0__": 32214,
      "question": "You are given an integer array rolls of length n and an integer k. You roll a k sided dice numbered from 1 to k, n times, where the result of the ith roll is rolls[i].\nReturn the length of the shortest sequence of rolls that cannot be taken from rolls.\nA sequence of rolls of length len is the result of rolling a k sided dice len times.\nNote that the sequence taken does not have to be consecutive as long as it is in order.\n  Example 1:\nInput: rolls = [4,2,1,2,3,3,2,4,1], k = 4\nOutput: 3\nExplanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\nEvery sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\nThe sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\nNote that there are other sequences that cannot be taken from rolls.\nExample 2:\nInput: rolls = [1,1,2,2], k = 2\nOutput: 2\nExplanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\nThe sequence [2, 1] cannot be taken from rolls, so we return 2.\nNote that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.\nExample 3:\nInput: rolls = [1,1,3,2,2,2,3,3], k = 4\nOutput: 1\nExplanation: The sequence [4] cannot be taken from rolls, so we return 1.\nNote that there are other sequences that cannot be taken from rolls but [4] is the shortest.\n  Constraints:\nn == rolls.length\n1 <= n <= 105\n1 <= rolls[i] <= k <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/first-letter-to-appear-twice/discuss/2324754/Python-oror-Map-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def repeatedCharacter(self, s: str) -> str:\n        \n        setS = set()\n\n        for x in s:\n            if x in setS:\n                return x\n            else:\n                setS.add(x)",
      "slug": "first-letter-to-appear-twice",
      "post_title": "\u2705Python || Map || Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 17,
      "views": 1100,
      "problem_title": "first letter to appear twice",
      "number": 2351,
      "acceptance": 0.76,
      "difficulty": "Easy",
      "__index_level_0__": 32219,
      "question": "Given a string s consisting of lowercase English letters, return the first letter to appear twice.\nNote:\nA letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.\ns will contain at least one letter that appears twice.\n  Example 1:\nInput: s = \"abccbaacz\"\nOutput: \"c\"\nExplanation:\nThe letter 'a' appears on the indexes 0, 5 and 6.\nThe letter 'b' appears on the indexes 1 and 4.\nThe letter 'c' appears on the indexes 2, 3 and 7.\nThe letter 'z' appears on the index 8.\nThe letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.\nExample 2:\nInput: s = \"abcdd\"\nOutput: \"d\"\nExplanation:\nThe only letter that appears twice is 'd' so we return 'd'.\n  Constraints:\n2 <= s.length <= 100\ns consists of lowercase English letters.\ns has at least one repeated letter."
    },
    {
      "post_href": "https://leetcode.com/problems/equal-row-and-column-pairs/discuss/2328910/Python3-oror-3-lines-transpose-Ctr-w-explanation-oror-TM%3A-100100",
      "python_solutions": "class Solution:                 # Consider this grid for an example:\n                                #           grid = [[1,2,1,9]\n                                #                   [2,8,9,2]\n                                #                   [1,2,1,9]\n                                #                   [9,2,6,3]]\n    \n                                # Here's the plan:\n\n                                #   \u2022 Determine tpse, the transpose of grid (using zip(*grid)):\n                                #           tspe = [[1,2,1,9] \n                                #                   [2,8,2,2]\n                                #                   [1,9,1,6]\n                                #                   [9,2,9,3]] \n                                #     The problem now is to determine the pairs of \n                                #     identical rows, one row in tpse and the other in grid.\n\n                                #   \u2022 We hash grid and tspe:\n                                #\n                                #           Counter(tuple(grid)):\n                                #               {(1,2,1,9): 2, (2,8,9,2): 1, (9,2,6,3): 1}\n                                #  \n                                #           Counter(zip(*grid)):\n                                #            {(1,2,1,9): 1, (2,8,2,2): 1, (1,9,1,6): 1, (9,2,9,3): 1}\n                                #\n                                #   \u2022 We determine the number of pairs:\n                                #       (1,2,1,9): 2 and (1,2,1,9): 1    => 2x1 = 2\n                                \n    def equalPairs(self, grid: List[List[int]]) -> int:\n\n        tpse = Counter(zip(*grid))                  # <-- determine the transpose\n                                                    #     and hash the rows\n\n        grid = Counter(map(tuple,grid))             # <-- hash the rows of grid. (Note the tuple-map, so\n                                                    #     we can compare apples w/ apples in next step.)\n\n        return  sum(tpse[t]*grid[t] for t in tpse)  # <-- compute the number of identical pairs\n\t\t\n\t\t                                            # https://leetcode.com/submissions/detail/755717162/",
      "slug": "equal-row-and-column-pairs",
      "post_title": "Python3     ||    3 lines,  transpose, Ctr w/ explanation    ||    T/M: 100%/100%",
      "user": "warrenruud",
      "upvotes": 12,
      "views": 443,
      "problem_title": "equal row and column pairs",
      "number": 2352,
      "acceptance": 0.71,
      "difficulty": "Medium",
      "__index_level_0__": 32258,
      "question": "Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.\nA row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).\n  Example 1:\nInput: grid = [[3,2,1],[1,7,6],[2,7,7]]\nOutput: 1\nExplanation: There is 1 equal row and column pair:\n- (Row 2, Column 1): [2,7,7]\nExample 2:\nInput: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\nOutput: 3\nExplanation: There are 3 equal row and column pairs:\n- (Row 0, Column 0): [3,1,2,2]\n- (Row 2, Column 2): [2,4,2,2]\n- (Row 3, Column 2): [2,4,2,2]\n  Constraints:\nn == grid.length == grid[i].length\n1 <= n <= 200\n1 <= grid[i][j] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-excellent-pairs/discuss/2324641/Python3-Sorting-Hamming-Weights-%2B-Binary-Search-With-Detailed-Explanations",
      "python_solutions": "class Solution:\n    def countExcellentPairs(self, nums: List[int], k: int) -> int:\n        hamming = sorted([self.hammingWeight(num) for num in set(nums)])\n        ans = 0\n        for h in hamming:\n            ans += len(hamming) - bisect.bisect_left(hamming, k - h)\n        return ans\n        \n    def hammingWeight(self, n):\n        ans = 0\n        while n:\n            n &= (n - 1)\n            ans += 1\n        return ans",
      "slug": "number-of-excellent-pairs",
      "post_title": "[Python3] Sorting Hamming Weights + Binary Search With Detailed Explanations",
      "user": "xil899",
      "upvotes": 20,
      "views": 674,
      "problem_title": "number of excellent pairs",
      "number": 2354,
      "acceptance": 0.4579999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 32283,
      "question": "You are given a 0-indexed positive integer array nums and a positive integer k.\nA pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:\nBoth the numbers num1 and num2 exist in the array nums.\nThe sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.\nReturn the number of distinct excellent pairs.\nTwo pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.\nNote that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.\n  Example 1:\nInput: nums = [1,2,3,1], k = 3\nOutput: 5\nExplanation: The excellent pairs are the following:\n- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.\n- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\n- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.\nSo the number of excellent pairs is 5.\nExample 2:\nInput: nums = [5,1,1], k = 10\nOutput: 0\nExplanation: There are no excellent pairs for this array.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109\n1 <= k <= 60"
    },
    {
      "post_href": "https://leetcode.com/problems/make-array-zero-by-subtracting-equal-amounts/discuss/2357747/Set",
      "python_solutions": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        return len(set(nums) - {0})",
      "slug": "make-array-zero-by-subtracting-equal-amounts",
      "post_title": "Set",
      "user": "votrubac",
      "upvotes": 17,
      "views": 1500,
      "problem_title": "make array zero by subtracting equal amounts",
      "number": 2357,
      "acceptance": 0.727,
      "difficulty": "Easy",
      "__index_level_0__": 32291,
      "question": "You are given a non-negative integer array nums. In one operation, you must:\nChoose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.\nSubtract x from every positive element in nums.\nReturn the minimum number of operations to make every element in nums equal to 0.\n  Example 1:\nInput: nums = [1,5,0,3,5]\nOutput: 3\nExplanation:\nIn the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\nIn the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\nIn the third operation, choose x = 2. Now, nums = [0,0,0,0,0].\nExample 2:\nInput: nums = [0]\nOutput: 0\nExplanation: Each element in nums is already 0 so no operations are needed.\n  Constraints:\n1 <= nums.length <= 100\n0 <= nums[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-number-of-groups-entering-a-competition/discuss/2358259/Python-oror-Math-oror-Two-Easy-Approaches",
      "python_solutions": "class Solution:\n    def maximumGroups(self, grades: List[int]) -> int:\n        \n        x = len(grades)\n        n = 0.5 * ((8 * x + 1) ** 0.5 - 1)\n        ans = int(n)\n        \n        return ans",
      "slug": "maximum-number-of-groups-entering-a-competition",
      "post_title": "\u2705Python || Math || Two Easy Approaches",
      "user": "chuhonghao01",
      "upvotes": 4,
      "views": 155,
      "problem_title": "maximum number of groups entering a competition",
      "number": 2358,
      "acceptance": 0.675,
      "difficulty": "Medium",
      "__index_level_0__": 32325,
      "question": "You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:\nThe sum of the grades of students in the ith group is less than the sum of the grades of students in the (i + 1)th group, for all groups (except the last).\nThe total number of students in the ith group is less than the total number of students in the (i + 1)th group, for all groups (except the last).\nReturn the maximum number of groups that can be formed.\n  Example 1:\nInput: grades = [10,6,12,7,3,5]\nOutput: 3\nExplanation: The following is a possible way to form 3 groups of students:\n- 1st group has the students with grades = [12]. Sum of grades: 12. Student count: 1\n- 2nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2\n- 3rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3\nIt can be shown that it is not possible to form more than 3 groups.\nExample 2:\nInput: grades = [8,8]\nOutput: 1\nExplanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.\n  Constraints:\n1 <= grades.length <= 105\n1 <= grades[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/find-closest-node-to-given-two-nodes/discuss/2357692/Simple-Breadth-First-Search-with-Explanation",
      "python_solutions": "class Solution:\n\tdef get_neighbors(self, start: int) -> Dict[int, int]:\n\t\tdistances = defaultdict(lambda: math.inf)\n\n\t\tqueue = deque([start])\n\t\tlevel = 0\n\n\t\twhile queue:\n\t\t\tfor _ in range(len(queue)):\n\t\t\t\tcurr = queue.popleft()\n\n\t\t\t\tif distances[curr] <= level:    \n\t\t\t\t\tcontinue\n\n\t\t\t\tdistances[curr] = level\n\n\t\t\t\tfor neighbor in graph[curr]:\n\t\t\t\t\tqueue.append(neighbor)\n\n\t\t\tlevel += 1        \n\n\t\treturn distances\n\n    def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:\n        n = len(edges)\n        graph = [[] for _ in range(n)]\n        \n        for _from, to in enumerate(edges):\n            if to != -1:\n                graph[_from].append(to)\n        \n        a = self.get_neighbors(node1)\n        b = self.get_neighbors(node2)\n                \n        options = []    \n        \n        for idx in range(n):\n            if a[idx] != math.inf and b[idx] != math.inf:\n                options.append((max(a[idx], b[idx]), idx))\n                \n        if not options:\n            return -1        \n        \n        return min(options)[1]",
      "slug": "find-closest-node-to-given-two-nodes",
      "post_title": "Simple Breadth First Search with Explanation",
      "user": "wickedmishra",
      "upvotes": 2,
      "views": 137,
      "problem_title": "find closest node to given two nodes",
      "number": 2359,
      "acceptance": 0.342,
      "difficulty": "Medium",
      "__index_level_0__": 32334,
      "question": "You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.\nThe graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from i, then edges[i] == -1.\nYou are also given two integers node1 and node2.\nReturn the index of the node that can be reached from both node1 and node2, such that the maximum between the distance from node1 to that node, and from node2 to that node is minimized. If there are multiple answers, return the node with the smallest index, and if no possible answer exists, return -1.\nNote that edges may contain cycles.\n  Example 1:\nInput: edges = [2,2,3,-1], node1 = 0, node2 = 1\nOutput: 2\nExplanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.\nThe maximum of those two distances is 1. It can be proven that we cannot get a node with a smaller maximum distance than 1, so we return node 2.\nExample 2:\nInput: edges = [1,2,-1], node1 = 0, node2 = 2\nOutput: 2\nExplanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.\nThe maximum of those two distances is 2. It can be proven that we cannot get a node with a smaller maximum distance than 2, so we return node 2.\n  Constraints:\nn == edges.length\n2 <= n <= 105\n-1 <= edges[i] < n\nedges[i] != i\n0 <= node1, node2 < n"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-cycle-in-a-graph/discuss/2357772/Python3-One-pass-dfs",
      "python_solutions": "class Solution:\n    def longestCycle(self, edges: List[int]) -> int:\n        in_d = set()\n        out_d = set()\n        for i, j in enumerate(edges):\n            if j != -1:\n                in_d.add(j)\n                out_d.add(i)\n        potential = in_d & out_d\n        visited = set()\n        self.ans = -1\n        def dfs(node, curr, v):\n            visited.add(node)\n            v[node] = curr\n            nei = edges[node]\n            if nei in v:\n                self.ans = max(self.ans, curr - v[nei] + 1)\n                visited.add(nei)\n                return\n            if nei not in visited and nei in potential:\n                dfs(nei, curr + 1, v)\n        for node in potential:\n            dfs(node, 1, {})\n        return self.ans",
      "slug": "longest-cycle-in-a-graph",
      "post_title": "[Python3] One pass dfs",
      "user": "Remineva",
      "upvotes": 5,
      "views": 257,
      "problem_title": "longest cycle in a graph",
      "number": 2360,
      "acceptance": 0.386,
      "difficulty": "Hard",
      "__index_level_0__": 32340,
      "question": "You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.\nThe graph is represented with a given 0-indexed array edges of size n, indicating that there is a directed edge from node i to node edges[i]. If there is no outgoing edge from node i, then edges[i] == -1.\nReturn the length of the longest cycle in the graph. If no cycle exists, return -1.\nA cycle is a path that starts and ends at the same node.\n  Example 1:\nInput: edges = [3,3,4,2,3]\nOutput: 3\nExplanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\nThe length of this cycle is 3, so 3 is returned.\nExample 2:\nInput: edges = [2,-1,3,1]\nOutput: -1\nExplanation: There are no cycles in this graph.\n  Constraints:\nn == edges.length\n2 <= n <= 105\n-1 <= edges[i] < n\nedges[i] != i"
    },
    {
      "post_href": "https://leetcode.com/problems/merge-similar-items/discuss/2388802/Python-Simple-Python-Solution-Using-HashMap",
      "python_solutions": "class Solution:\n\tdef mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n\n\t\tmerge_item = items1 + items2\n\n\t\td = defaultdict(int)\n\n\t\tfor i in merge_item:\n\t\t\tvalue,weight = i\n\t\t\td[value] = d[value] + weight\n\n\t\tresult = []\n\n\t\tfor j in sorted(d):\n\t\t\tresult.append([j,d[j]])\n\n\t\treturn result",
      "slug": "merge-similar-items",
      "post_title": "[ Python ] \u2705\u2705 Simple Python Solution Using HashMap \ud83e\udd73\u270c\ud83d\udc4d",
      "user": "ASHOK_KUMAR_MEGHVANSHI",
      "upvotes": 8,
      "views": 393,
      "problem_title": "merge similar items",
      "number": 2363,
      "acceptance": 0.753,
      "difficulty": "Easy",
      "__index_level_0__": 32354,
      "question": "You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties:\nitems[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.\nThe value of each item in items is unique.\nReturn a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.\nNote: ret should be returned in ascending order by value.\n  Example 1:\nInput: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]\nOutput: [[1,6],[3,9],[4,5]]\nExplanation: \nThe item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.\nThe item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.\nThe item with value = 4 occurs in items1 with weight = 5, total weight = 5.  \nTherefore, we return [[1,6],[3,9],[4,5]].\nExample 2:\nInput: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]\nOutput: [[1,4],[2,4],[3,4]]\nExplanation: \nThe item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.\nThe item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.\nThe item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.\nTherefore, we return [[1,4],[2,4],[3,4]].\nExample 3:\nInput: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]\nOutput: [[1,7],[2,4],[7,1]]\nExplanation:\nThe item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7. \nThe item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. \nThe item with value = 7 occurs in items2 with weight = 1, total weight = 1.\nTherefore, we return [[1,7],[2,4],[7,1]].\n  Constraints:\n1 <= items1.length, items2.length <= 1000\nitems1[i].length == items2[i].length == 2\n1 <= valuei, weighti <= 1000\nEach valuei in items1 is unique.\nEach valuei in items2 is unique."
    },
    {
      "post_href": "https://leetcode.com/problems/count-number-of-bad-pairs/discuss/2388687/Python-oror-Detailed-Explanation-oror-Faster-Than-100-oror-Less-than-100-oror-Simple-oror-MATH",
      "python_solutions": "class Solution:\n    def countBadPairs(self, nums: List[int]) -> int:\n        nums_len = len(nums)\n        count_dict = dict()\n        for i in range(nums_len):\n            nums[i] -= i\n            if nums[i] not in count_dict:\n                count_dict[nums[i]] = 0\n            count_dict[nums[i]] += 1\n        \n        count = 0\n        for key in count_dict:\n            count += math.comb(count_dict[key], 2)\n        return math.comb(nums_len, 2) - count",
      "slug": "count-number-of-bad-pairs",
      "post_title": "\ud83d\udd25 Python || Detailed Explanation \u2705 || Faster Than 100% \u2705|| Less than 100% \u2705 || Simple || MATH",
      "user": "wingskh",
      "upvotes": 32,
      "views": 648,
      "problem_title": "count number of bad pairs",
      "number": 2364,
      "acceptance": 0.408,
      "difficulty": "Medium",
      "__index_level_0__": 32380,
      "question": "You are given a 0-indexed integer array nums. A pair of indices (i, j) is a bad pair if i < j and j - i != nums[j] - nums[i].\nReturn the total number of bad pairs in nums.\n  Example 1:\nInput: nums = [4,1,3,3]\nOutput: 5\nExplanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\nThe pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\nThe pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\nThe pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\nThe pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\nThere are a total of 5 bad pairs, so we return 5.\nExample 2:\nInput: nums = [1,2,3,4,5]\nOutput: 0\nExplanation: There are no bad pairs.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/task-scheduler-ii/discuss/2388355/Python-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n        \n        ans = 0\n        hashset = {}\n        n = len(tasks)\n        \n        for x in set(tasks):\n            hashset[x] = 0\n            \n        i = 0\n        while i <= n - 1:\n            flag = ans - hashset[tasks[i]]\n            if flag >= 0:\n                ans += 1\n                hashset[tasks[i]] = ans + space\n                i += 1\n            else:\n                ans += -flag\n        \n        return ans",
      "slug": "task-scheduler-ii",
      "post_title": "\u2705Python || Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 2,
      "views": 75,
      "problem_title": "task scheduler ii",
      "number": 2365,
      "acceptance": 0.462,
      "difficulty": "Medium",
      "__index_level_0__": 32391,
      "question": "You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the ith task.\nYou are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.\nEach day, until all tasks have been completed, you must either:\nComplete the next task from tasks, or\nTake a break.\nReturn the minimum number of days needed to complete all tasks.\n  Example 1:\nInput: tasks = [1,2,1,2,3,1], space = 3\nOutput: 9\nExplanation:\nOne way to complete all tasks in 9 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nDay 7: Take a break.\nDay 8: Complete the 4th task.\nDay 9: Complete the 5th task.\nIt can be shown that the tasks cannot be completed in less than 9 days.\nExample 2:\nInput: tasks = [5,8,8,5], space = 2\nOutput: 6\nExplanation:\nOne way to complete all tasks in 6 days is as follows:\nDay 1: Complete the 0th task.\nDay 2: Complete the 1st task.\nDay 3: Take a break.\nDay 4: Take a break.\nDay 5: Complete the 2nd task.\nDay 6: Complete the 3rd task.\nIt can be shown that the tasks cannot be completed in less than 6 days.\n  Constraints:\n1 <= tasks.length <= 105\n1 <= tasks[i] <= 109\n1 <= space <= tasks.length"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-replacements-to-sort-the-array/discuss/2388550/Python-oror-One-reversed-pass-oror-Easy-Approaches",
      "python_solutions": "class Solution:\n    def minimumReplacement(self, nums: List[int]) -> int:\n        \n        n = len(nums)\n        k = nums[n - 1]\n        ans = 0\n        \n        for i in reversed(range(n - 1)):\n            if nums[i] > k:\n                l =  nums[i] / k\n                if l == int(l):\n                    ans += int(l) - 1\n                    k = nums[i] / int(l)\n                else:\n                    ans += int(l)\n                    k = int(nums[i] / (int(l) + 1))\n            else:\n                k = nums[i]\n\n        return ans",
      "slug": "minimum-replacements-to-sort-the-array",
      "post_title": "\u2705Python || One reversed pass || Easy Approaches",
      "user": "chuhonghao01",
      "upvotes": 2,
      "views": 84,
      "problem_title": "minimum replacements to sort the array",
      "number": 2366,
      "acceptance": 0.3989999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 32402,
      "question": "You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.\nFor example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].\nReturn the minimum number of operations to make an array that is sorted in non-decreasing order.\n  Example 1:\nInput: nums = [3,9,3]\nOutput: 2\nExplanation: Here are the steps to sort the array in non-decreasing order:\n- From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]\n- From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]\nThere are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.\nExample 2:\nInput: nums = [1,2,3,4,5]\nOutput: 0\nExplanation: The array is already in non-decreasing order. Therefore, we return 0. \n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-arithmetic-triplets/discuss/2395275/Python-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n        \n        ans = 0\n        n = len(nums)\n        for i in range(n):\n            if nums[i] + diff in nums and nums[i] + 2 * diff in nums:\n                ans += 1\n        \n        return ans",
      "slug": "number-of-arithmetic-triplets",
      "post_title": "\u2705Python || Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 19,
      "views": 1200,
      "problem_title": "number of arithmetic triplets",
      "number": 2367,
      "acceptance": 0.8370000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 32409,
      "question": "You are given a 0-indexed, strictly increasing integer array nums and a positive integer diff. A triplet (i, j, k) is an arithmetic triplet if the following conditions are met:\ni < j < k,\nnums[j] - nums[i] == diff, and\nnums[k] - nums[j] == diff.\nReturn the number of unique arithmetic triplets.\n  Example 1:\nInput: nums = [0,1,4,6,7,10], diff = 3\nOutput: 2\nExplanation:\n(1, 2, 4) is an arithmetic triplet because both 7 - 4 == 3 and 4 - 1 == 3.\n(2, 4, 5) is an arithmetic triplet because both 10 - 7 == 3 and 7 - 4 == 3. \nExample 2:\nInput: nums = [4,5,6,7,8,9], diff = 2\nOutput: 2\nExplanation:\n(0, 2, 4) is an arithmetic triplet because both 8 - 6 == 2 and 6 - 4 == 2.\n(1, 3, 5) is an arithmetic triplet because both 9 - 7 == 2 and 7 - 5 == 2.\n  Constraints:\n3 <= nums.length <= 200\n0 <= nums[i] <= 200\n1 <= diff <= 50\nnums is strictly increasing."
    },
    {
      "post_href": "https://leetcode.com/problems/reachable-nodes-with-restrictions/discuss/2395280/Python-oror-Graph-oror-UnionFind-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n        \n        restrictedSet = set(restricted)\n        uf = UnionFindSet(n)\n        for edge in edges:\n            if edge[0] in restrictedSet or edge[1] in restrictedSet:\n                continue\n            else:\n                uf.union(edge[0], edge[1])\n\n        ans = 1\n        rootNode = uf.find(0)\n        for i in range(1, n):\n            if uf.find(i) == rootNode:\n                ans += 1\n        return ans\n\nclass UnionFindSet:\n    def __init__(self, size):\n        self.root = [i for i in range(size)]\n        # Use a rank array to record the height of each vertex, i.e., the \"rank\" of each vertex.\n        # The initial \"rank\" of each vertex is 1, because each of them is\n        # a standalone vertex with no connection to other vertices.\n        self.rank = [1] * size\n\n    # The find function here is the same as that in the disjoint set with path compression.\n    def find(self, x):\n        if x == self.root[x]:\n            return x\n        self.root[x] = self.find(self.root[x])\n        return self.root[x]\n\n    # The union function with union by rank\n    def union(self, x, y):\n        rootX = self.find(x)\n        rootY = self.find(y)\n        if rootX != rootY:\n            if self.rank[rootX] > self.rank[rootY]:\n                self.root[rootY] = rootX\n            elif self.rank[rootX] < self.rank[rootY]:\n                self.root[rootX] = rootY\n            else:\n                self.root[rootY] = rootX",
      "slug": "reachable-nodes-with-restrictions",
      "post_title": "\u2705Python || Graph || UnionFind || Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 3,
      "views": 152,
      "problem_title": "reachable nodes with restrictions",
      "number": 2368,
      "acceptance": 0.574,
      "difficulty": "Medium",
      "__index_level_0__": 32438,
      "question": "There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\nYou are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree. You are also given an integer array restricted which represents restricted nodes.\nReturn the maximum number of nodes you can reach from node 0 without visiting a restricted node.\nNote that node 0 will not be a restricted node.\n  Example 1:\nInput: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\nOutput: 4\nExplanation: The diagram above shows the tree.\nWe have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.\nExample 2:\nInput: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\nOutput: 3\nExplanation: The diagram above shows the tree.\nWe have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.\n  Constraints:\n2 <= n <= 105\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nedges represents a valid tree.\n1 <= restricted.length < n\n1 <= restricted[i] < n\nAll the values of restricted are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/check-if-there-is-a-valid-partition-for-the-array/discuss/2390552/Python3-Iterative-DFS",
      "python_solutions": "class Solution:\n    def validPartition(self, nums: List[int]) -> bool:\n        idxs = defaultdict(list)\n        n = len(nums)\n        \n        #Find all doubles\n        for idx in range(1, n):\n            if nums[idx] == nums[idx - 1]:\n                idxs[idx - 1].append(idx + 1)\n                \n        #Find all triples\n        for idx in range(2, n):\n            if nums[idx] == nums[idx - 1] == nums[idx - 2]:\n                idxs[idx - 2].append(idx + 1)\n                \n        #Find all triple increments\n        for idx in range(2, n):\n            if nums[idx] == nums[idx - 1] + 1 == nums[idx - 2] + 2:\n                idxs[idx - 2].append(idx + 1)\n        \n        #DFS \n        seen = set()\n        stack = [0]\n\n        while stack:\n            node = stack.pop()\n\n            if node not in seen:\n                if node == n:\n                    return True\n                seen.add(node)\n\n            for adj in idxs[node]:\n                if adj not in seen:\n                    stack.append(adj)\n        \n        return False",
      "slug": "check-if-there-is-a-valid-partition-for-the-array",
      "post_title": "[Python3] Iterative DFS",
      "user": "0xRoxas",
      "upvotes": 2,
      "views": 106,
      "problem_title": "check if there is a valid partition for the array",
      "number": 2369,
      "acceptance": 0.401,
      "difficulty": "Medium",
      "__index_level_0__": 32454,
      "question": "You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.\nWe call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:\nThe subarray consists of exactly 2, equal elements. For example, the subarray [2,2] is good.\nThe subarray consists of exactly 3, equal elements. For example, the subarray [4,4,4] is good.\nThe subarray consists of exactly 3 consecutive increasing elements, that is, the difference between adjacent elements is 1. For example, the subarray [3,4,5] is good, but the subarray [1,3,5] is not.\nReturn true if the array has at least one valid partition. Otherwise, return false.\n  Example 1:\nInput: nums = [4,4,4,5,6]\nOutput: true\nExplanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].\nThis partition is valid, so we return true.\nExample 2:\nInput: nums = [1,1,1,2]\nOutput: false\nExplanation: There is no valid partition for this array.\n  Constraints:\n2 <= nums.length <= 105\n1 <= nums[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-ideal-subsequence/discuss/2390471/DP",
      "python_solutions": "class Solution:\n    def longestIdealString(self, s: str, k: int) -> int:\n        dp = [0] * 26\n        for ch in s:\n            i = ord(ch) - ord(\"a\")\n            dp[i] = 1 + max(dp[max(0, i - k) : min(26, i + k + 1)])\n        return max(dp)",
      "slug": "longest-ideal-subsequence",
      "post_title": "DP",
      "user": "votrubac",
      "upvotes": 34,
      "views": 2300,
      "problem_title": "longest ideal subsequence",
      "number": 2370,
      "acceptance": 0.379,
      "difficulty": "Medium",
      "__index_level_0__": 32461,
      "question": "You are given a string s consisting of lowercase letters and an integer k. We call a string t ideal if the following conditions are satisfied:\nt is a subsequence of the string s.\nThe absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.\nReturn the length of the longest ideal string.\nA subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.\nNote that the alphabet order is not cyclic. For example, the absolute difference in the alphabet order of 'a' and 'z' is 25, not 1.\n  Example 1:\nInput: s = \"acfgbd\", k = 2\nOutput: 4\nExplanation: The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\nNote that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.\nExample 2:\nInput: s = \"abcd\", k = 3\nOutput: 4\nExplanation: The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.\n  Constraints:\n1 <= s.length <= 105\n0 <= k <= 25\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/largest-local-values-in-a-matrix/discuss/2422191/Python3-simulation",
      "python_solutions": "class Solution:\n    def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n        n = len(grid)\n        ans = [[0]*(n-2) for _ in range(n-2)]\n        for i in range(n-2): \n            for j in range(n-2): \n                ans[i][j] = max(grid[ii][jj] for ii in range(i, i+3) for jj in range(j, j+3))\n        return ans",
      "slug": "largest-local-values-in-a-matrix",
      "post_title": "[Python3] simulation",
      "user": "ye15",
      "upvotes": 14,
      "views": 1200,
      "problem_title": "largest local values in a matrix",
      "number": 2373,
      "acceptance": 0.8390000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 32470,
      "question": "You are given an n x n integer matrix grid.\nGenerate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:\nmaxLocal[i][j] is equal to the largest value of the 3 x 3 matrix in grid centered around row i + 1 and column j + 1.\nIn other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.\nReturn the generated matrix.\n  Example 1:\nInput: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]\nOutput: [[9,9],[8,6]]\nExplanation: The diagram above shows the original matrix and the generated matrix.\nNotice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.\nExample 2:\nInput: grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]\nOutput: [[2,2,2],[2,2,2],[2,2,2]]\nExplanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.\n  Constraints:\nn == grid.length == grid[i].length\n3 <= n <= 100\n1 <= grid[i][j] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/node-with-highest-edge-score/discuss/2422372/Python-oror-Easy-Approach-oror-Hashmap",
      "python_solutions": "class Solution:\n    def edgeScore(self, edges: List[int]) -> int:\n\n        n = len(edges)\n        cnt = defaultdict(int)\n        ans = 0\n        \n\t\t// we have the key stores the node edges[i], and the value indicates the edge score.\n        for i in range(n):\n            cnt[edges[i]] += i\n\n        m = max(cnt.values())\n\n\t\t// In the second iteration, i is also the index of the node. So the first one meets == m, is the smallest index.\n        for i in range(n):\n            if cnt[i] == m:\n                ans = i\n                break\n        \n        return ans",
      "slug": "node-with-highest-edge-score",
      "post_title": "\u2705Python || Easy Approach || Hashmap",
      "user": "chuhonghao01",
      "upvotes": 4,
      "views": 226,
      "problem_title": "node with highest edge score",
      "number": 2374,
      "acceptance": 0.462,
      "difficulty": "Medium",
      "__index_level_0__": 32500,
      "question": "You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge.\nThe graph is represented by a given 0-indexed integer array edges of length n, where edges[i] indicates that there is a directed edge from node i to node edges[i].\nThe edge score of a node i is defined as the sum of the labels of all the nodes that have an edge pointing to i.\nReturn the node with the highest edge score. If multiple nodes have the same edge score, return the node with the smallest index.\n  Example 1:\nInput: edges = [1,0,0,0,0,7,7,5]\nOutput: 7\nExplanation:\n- The nodes 1, 2, 3 and 4 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 + 3 + 4 = 10.\n- The node 0 has an edge pointing to node 1. The edge score of node 1 is 0.\n- The node 7 has an edge pointing to node 5. The edge score of node 5 is 7.\n- The nodes 5 and 6 have an edge pointing to node 7. The edge score of node 7 is 5 + 6 = 11.\nNode 7 has the highest edge score so return 7.\nExample 2:\nInput: edges = [2,0,0,2]\nOutput: 0\nExplanation:\n- The nodes 1 and 2 have an edge pointing to node 0. The edge score of node 0 is 1 + 2 = 3.\n- The nodes 0 and 3 have an edge pointing to node 2. The edge score of node 2 is 0 + 3 = 3.\nNodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0.\n  Constraints:\nn == edges.length\n2 <= n <= 105\n0 <= edges[i] < n\nedges[i] != i"
    },
    {
      "post_href": "https://leetcode.com/problems/construct-smallest-number-from-di-string/discuss/2422249/Python3-greedy",
      "python_solutions": "class Solution:\n    def smallestNumber(self, pattern: str) -> str:\n        ans = [1]\n        for ch in pattern: \n            if ch == 'I': \n                m = ans[-1]+1\n                while m in ans: m += 1\n                ans.append(m)\n            else: \n                ans.append(ans[-1])\n                for i in range(len(ans)-1, 0, -1): \n                    if ans[i-1] == ans[i]: ans[i-1] += 1\n        return ''.join(map(str, ans))",
      "slug": "construct-smallest-number-from-di-string",
      "post_title": "[Python3] greedy",
      "user": "ye15",
      "upvotes": 22,
      "views": 994,
      "problem_title": "construct smallest number from di string",
      "number": 2375,
      "acceptance": 0.7390000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 32515,
      "question": "You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.\nA 0-indexed string num of length n + 1 is created using the following conditions:\nnum consists of the digits '1' to '9', where each digit is used at most once.\nIf pattern[i] == 'I', then num[i] < num[i + 1].\nIf pattern[i] == 'D', then num[i] > num[i + 1].\nReturn the lexicographically smallest possible string num that meets the conditions.\n  Example 1:\nInput: pattern = \"IIIDIDDD\"\nOutput: \"123549876\"\nExplanation:\nAt indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].\nAt indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].\nSome possible values of num are \"245639871\", \"135749862\", and \"123849765\".\nIt can be proven that \"123549876\" is the smallest possible num that meets the conditions.\nNote that \"123414321\" is not possible because the digit '1' is used more than once.\nExample 2:\nInput: pattern = \"DDD\"\nOutput: \"4321\"\nExplanation:\nSome possible values of num are \"9876\", \"7321\", and \"8742\".\nIt can be proven that \"4321\" is the smallest possible num that meets the conditions.\n  Constraints:\n1 <= pattern.length <= 8\npattern consists of only the letters 'I' and 'D'."
    },
    {
      "post_href": "https://leetcode.com/problems/count-special-integers/discuss/2422258/Python3-dp",
      "python_solutions": "class Solution:\n    def countSpecialNumbers(self, n: int) -> int:\n        vals = list(map(int, str(n)))\n        \n        @cache\n        def fn(i, m, on): \n            \"\"\"Return count at index i with mask m and profile flag (True/False)\"\"\"\n            ans = 0 \n            if i == len(vals): return 1\n            for v in range(vals[i] if on else 10 ): \n                if m & 1< int:\n        \n        ans = 0\n        res = 0\n\n        for i in range(len(blocks) - k + 1):\n            res = blocks.count('B', i, i + k)\n            ans = max(res, ans)\n\n        ans = k - ans\n        return ans",
      "slug": "minimum-recolors-to-get-k-consecutive-black-blocks",
      "post_title": "\u2705Python || Easy Approach || Sliding Window || Count",
      "user": "chuhonghao01",
      "upvotes": 3,
      "views": 318,
      "problem_title": "minimum recolors to get k consecutive black blocks",
      "number": 2379,
      "acceptance": 0.568,
      "difficulty": "Easy",
      "__index_level_0__": 32534,
      "question": "You are given a 0-indexed string blocks of length n, where blocks[i] is either 'W' or 'B', representing the color of the ith block. The characters 'W' and 'B' denote the colors white and black, respectively.\nYou are also given an integer k, which is the desired number of consecutive black blocks.\nIn one operation, you can recolor a white block such that it becomes a black block.\nReturn the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.\n  Example 1:\nInput: blocks = \"WBBWWBBWBW\", k = 7\nOutput: 3\nExplanation:\nOne way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks\nso that blocks = \"BBBBBBBWBW\". \nIt can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.\nTherefore, we return 3.\nExample 2:\nInput: blocks = \"WBWBBBW\", k = 2\nOutput: 0\nExplanation:\nNo changes need to be made, since 2 consecutive black blocks already exist.\nTherefore, we return 0.\n  Constraints:\nn == blocks.length\n1 <= n <= 100\nblocks[i] is either 'W' or 'B'.\n1 <= k <= n"
    },
    {
      "post_href": "https://leetcode.com/problems/time-needed-to-rearrange-a-binary-string/discuss/2454195/Python3-O(N)-dp-approach",
      "python_solutions": "class Solution: \n    def secondsToRemoveOccurrences(self, s: str) -> int:\n        ans = prefix = prev = 0 \n        for i, ch in enumerate(s): \n            if ch == '1': \n                ans = max(prev, i - prefix)\n                prefix += 1\n                if ans: prev = ans+1\n        return ans",
      "slug": "time-needed-to-rearrange-a-binary-string",
      "post_title": "[Python3] O(N) dp approach",
      "user": "ye15",
      "upvotes": 49,
      "views": 2200,
      "problem_title": "time needed to rearrange a binary string",
      "number": 2380,
      "acceptance": 0.482,
      "difficulty": "Medium",
      "__index_level_0__": 32566,
      "question": "You are given a binary string s. In one second, all occurrences of \"01\" are simultaneously replaced with \"10\". This process repeats until no occurrences of \"01\" exist.\nReturn the number of seconds needed to complete this process.\n  Example 1:\nInput: s = \"0110101\"\nOutput: 4\nExplanation: \nAfter one second, s becomes \"1011010\".\nAfter another second, s becomes \"1101100\".\nAfter the third second, s becomes \"1110100\".\nAfter the fourth second, s becomes \"1111000\".\nNo occurrence of \"01\" exists any longer, and the process needed 4 seconds to complete,\nso we return 4.\nExample 2:\nInput: s = \"11100\"\nOutput: 0\nExplanation:\nNo occurrence of \"01\" exists in s, and the processes needed 0 seconds to complete,\nso we return 0.\n  Constraints:\n1 <= s.length <= 1000\ns[i] is either '0' or '1'.\n  Follow up:\nCan you solve this problem in O(n) time complexity?"
    },
    {
      "post_href": "https://leetcode.com/problems/shifting-letters-ii/discuss/2454404/Python-Cumulative-Sum-oror-Easy-Solution",
      "python_solutions": "class Solution:\n    def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:\n        cum_shifts = [0 for _ in range(len(s)+1)]\n        \n        for st, end, d in shifts:\n            if d == 0:\n                cum_shifts[st] -= 1\n                cum_shifts[end+1] += 1\n            else:\n                cum_shifts[st] += 1\n                cum_shifts[end+1] -= 1\n        \n        cum_sum = 0\n        for i in range(len(s)):\n            cum_sum += cum_shifts[i]\n            \n            new_code = (((ord(s[i]) + cum_sum) - 97) % 26) + 97\n            s = s[:i] + chr(new_code) + s[i+1:]\n        \n        return s",
      "slug": "shifting-letters-ii",
      "post_title": "\u2705 Python Cumulative Sum || Easy Solution",
      "user": "idntk",
      "upvotes": 15,
      "views": 850,
      "problem_title": "shifting letters ii",
      "number": 2381,
      "acceptance": 0.342,
      "difficulty": "Medium",
      "__index_level_0__": 32578,
      "question": "You are given a string s of lowercase English letters and a 2D integer array shifts where shifts[i] = [starti, endi, directioni]. For every i, shift the characters in s from the index starti to the index endi (inclusive) forward if directioni = 1, or shift the characters backward if directioni = 0.\nShifting a character forward means replacing it with the next letter in the alphabet (wrapping around so that 'z' becomes 'a'). Similarly, shifting a character backward means replacing it with the previous letter in the alphabet (wrapping around so that 'a' becomes 'z').\nReturn the final string after all such shifts to s are applied.\n  Example 1:\nInput: s = \"abc\", shifts = [[0,1,0],[1,2,1],[0,2,1]]\nOutput: \"ace\"\nExplanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = \"zac\".\nSecondly, shift the characters from index 1 to index 2 forward. Now s = \"zbd\".\nFinally, shift the characters from index 0 to index 2 forward. Now s = \"ace\".\nExample 2:\nInput: s = \"dztz\", shifts = [[0,0,0],[1,1,1]]\nOutput: \"catz\"\nExplanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = \"cztz\".\nFinally, shift the characters from index 1 to index 1 forward. Now s = \"catz\".\n  Constraints:\n1 <= s.length, shifts.length <= 5 * 104\nshifts[i].length == 3\n0 <= starti <= endi < s.length\n0 <= directioni <= 1\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-segment-sum-after-removals/discuss/2454397/Do-it-backwards-O(N)",
      "python_solutions": "class Solution:\n    def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:\n        mp, cur, res = {}, 0, []\n        for q in reversed(removeQueries[1:]):\n            mp[q] = (nums[q], 1)\n            rv, rLen = mp.get(q+1, (0, 0))\n            lv, lLen = mp.get(q-1, (0, 0))\n                \n            total = nums[q] + rv + lv\n            mp[q+rLen] = (total, lLen + rLen + 1)\n            mp[q-lLen] = (total, lLen + rLen + 1)\n        \n            cur = max(cur, total)\n            res.append(cur)\n            \n        return res[::-1] + [0]",
      "slug": "maximum-segment-sum-after-removals",
      "post_title": "Do it backwards O(N)",
      "user": "user9591",
      "upvotes": 29,
      "views": 1100,
      "problem_title": "maximum segment sum after removals",
      "number": 2382,
      "acceptance": 0.476,
      "difficulty": "Hard",
      "__index_level_0__": 32591,
      "question": "You are given two 0-indexed integer arrays nums and removeQueries, both of length n. For the ith query, the element in nums at the index removeQueries[i] is removed, splitting nums into different segments.\nA segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment.\nReturn an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal.\nNote: The same index will not be removed more than once.\n  Example 1:\nInput: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1]\nOutput: [14,7,2,2,0]\nExplanation: Using 0 to indicate a removed element, the answer is as follows:\nQuery 1: Remove the 0th element, nums becomes [0,2,5,6,1] and the maximum segment sum is 14 for segment [2,5,6,1].\nQuery 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5].\nQuery 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2]. \nQuery 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2]. \nQuery 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments.\nFinally, we return [14,7,2,2,0].\nExample 2:\nInput: nums = [3,2,11,1], removeQueries = [3,2,1,0]\nOutput: [16,5,3,0]\nExplanation: Using 0 to indicate a removed element, the answer is as follows:\nQuery 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11].\nQuery 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2].\nQuery 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3].\nQuery 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments.\nFinally, we return [16,5,3,0].\n  Constraints:\nn == nums.length == removeQueries.length\n1 <= n <= 105\n1 <= nums[i] <= 109\n0 <= removeQueries[i] < n\nAll the values of removeQueries are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-hours-of-training-to-win-a-competition/discuss/2456759/Python-oror-Easy-Approach",
      "python_solutions": "class Solution:\n    def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:\n        \n        ans = 0\n        n = len(energy)\n\n        for i in range(n):\n            while initialEnergy <= energy[i] or initialExperience <= experience[i]:\n                if initialEnergy <= energy[i]:\n                    initialEnergy += 1\n                    ans += 1\n                if initialExperience <= experience[i]:\n                    initialExperience += 1\n                    ans += 1\n            initialEnergy -= energy[i]\n            initialExperience += experience[i]\n        \n        return ans",
      "slug": "minimum-hours-of-training-to-win-a-competition",
      "post_title": "\u2705Python || Easy Approach",
      "user": "chuhonghao01",
      "upvotes": 6,
      "views": 460,
      "problem_title": "minimum hours of training to win a competition",
      "number": 2383,
      "acceptance": 0.41,
      "difficulty": "Easy",
      "__index_level_0__": 32595,
      "question": "You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively.\nYou are also given two 0-indexed integer arrays energy and experience, both of length n.\nYou will face n opponents in order. The energy and experience of the ith opponent is denoted by energy[i] and experience[i] respectively. When you face an opponent, you need to have both strictly greater experience and energy to defeat them and move to the next opponent if available.\nDefeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i].\nBefore starting the competition, you can train for some number of hours. After each hour of training, you can either choose to increase your initial experience by one, or increase your initial energy by one.\nReturn the minimum number of training hours required to defeat all n opponents.\n  Example 1:\nInput: initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]\nOutput: 8\nExplanation: You can increase your energy to 11 after 6 hours of training, and your experience to 5 after 2 hours of training.\nYou face the opponents in the following order:\n- You have more energy and experience than the 0th opponent so you win.\n  Your energy becomes 11 - 1 = 10, and your experience becomes 5 + 2 = 7.\n- You have more energy and experience than the 1st opponent so you win.\n  Your energy becomes 10 - 4 = 6, and your experience becomes 7 + 6 = 13.\n- You have more energy and experience than the 2nd opponent so you win.\n  Your energy becomes 6 - 3 = 3, and your experience becomes 13 + 3 = 16.\n- You have more energy and experience than the 3rd opponent so you win.\n  Your energy becomes 3 - 2 = 1, and your experience becomes 16 + 1 = 17.\nYou did a total of 6 + 2 = 8 hours of training before the competition, so we return 8.\nIt can be proven that no smaller answer exists.\nExample 2:\nInput: initialEnergy = 2, initialExperience = 4, energy = [1], experience = [3]\nOutput: 0\nExplanation: You do not need any additional energy or experience to win the competition, so we return 0.\n  Constraints:\nn == energy.length == experience.length\n1 <= n <= 100\n1 <= initialEnergy, initialExperience, energy[i], experience[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/largest-palindromic-number/discuss/2456725/Python-oror-Easy-Approach-oror-Hashmap",
      "python_solutions": "class Solution:\n    def largestPalindromic(self, num: str) -> str:\n\n        ans = []\n        b = [str(x) for x in range(9, -1, -1)]\n        from collections import defaultdict\n\n        a = defaultdict(int)\n\n        for x in num:\n            a[x] += 1\n\n        for x in b:\n            n = len(ans)\n            if n % 2 == 0:\n                if a[x] > 0:\n                    ans = ans[:n // 2] + [x] * a[x] + ans[n // 2:]\n            else:\n                if x == '0':\n                    if len(ans) != 1:\n                        ans = ans[:n // 2] + [x] * (a[x] // 2) + [ans[n // 2]] + [x] * (a[x] // 2) + ans[n // 2 + 1:]\n                else:\n                    if a[x] >= 2:\n                        ans = ans[:n // 2] + [x] * (a[x] // 2) + [ans[n // 2]] + [x] * (a[x] // 2) + ans[n // 2 + 1:]\n\n        res = \"\".join(ans)\n        return str(int(res))",
      "slug": "largest-palindromic-number",
      "post_title": "\u2705Python || Easy Approach || Hashmap",
      "user": "chuhonghao01",
      "upvotes": 4,
      "views": 178,
      "problem_title": "largest palindromic number",
      "number": 2384,
      "acceptance": 0.306,
      "difficulty": "Medium",
      "__index_level_0__": 32617,
      "question": "You are given a string num consisting of digits only.\nReturn the largest palindromic integer (in the form of a string) that can be formed using digits taken from num. It should not contain leading zeroes.\nNotes:\nYou do not need to use all the digits of num, but you must use at least one digit.\nThe digits can be reordered.\n  Example 1:\nInput: num = \"444947137\"\nOutput: \"7449447\"\nExplanation: \nUse the digits \"4449477\" from \"444947137\" to form the palindromic integer \"7449447\".\nIt can be shown that \"7449447\" is the largest palindromic integer that can be formed.\nExample 2:\nInput: num = \"00009\"\nOutput: \"9\"\nExplanation: \nIt can be shown that \"9\" is the largest palindromic integer that can be formed.\nNote that the integer returned should not contain leading zeroes.\n  Constraints:\n1 <= num.length <= 105\nnum consists of digits."
    },
    {
      "post_href": "https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/discuss/2456656/Python3-bfs",
      "python_solutions": "class Solution: \t\t\n    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:\n        graph = defaultdict(list)\n        \n        stack = [(root, None)]\n        while stack: \n            n, p = stack.pop()\n            if p: \n                graph[p.val].append(n.val)\n                graph[n.val].append(p.val)\n            if n.left: stack.append((n.left, n))\n            if n.right: stack.append((n.right, n))\n        \n        ans = -1\n        seen = {start}\n        queue = deque([start])\n        while queue: \n            for _ in range(len(queue)): \n                u = queue.popleft()\n                for v in graph[u]: \n                    if v not in seen: \n                        seen.add(v)\n                        queue.append(v)\n            ans += 1\n        return ans",
      "slug": "amount-of-time-for-binary-tree-to-be-infected",
      "post_title": "[Python3] bfs",
      "user": "ye15",
      "upvotes": 33,
      "views": 1400,
      "problem_title": "amount of time for binary tree to be infected",
      "number": 2385,
      "acceptance": 0.562,
      "difficulty": "Medium",
      "__index_level_0__": 32627,
      "question": "You are given the root of a binary tree with unique values, and an integer start. At minute 0, an infection starts from the node with value start.\nEach minute, a node becomes infected if:\nThe node is currently uninfected.\nThe node is adjacent to an infected node.\nReturn the number of minutes needed for the entire tree to be infected.\n  Example 1:\nInput: root = [1,5,3,null,4,10,6,9,2], start = 3\nOutput: 4\nExplanation: The following nodes are infected during:\n- Minute 0: Node 3\n- Minute 1: Nodes 1, 10 and 6\n- Minute 2: Node 5\n- Minute 3: Node 4\n- Minute 4: Nodes 9 and 2\nIt takes 4 minutes for the whole tree to be infected so we return 4.\nExample 2:\nInput: root = [1], start = 1\nOutput: 0\nExplanation: At minute 0, the only node in the tree is infected so we return 0.\n  Constraints:\nThe number of nodes in the tree is in the range [1, 105].\n1 <= Node.val <= 105\nEach node has a unique value.\nA node with a value of start exists in the tree."
    },
    {
      "post_href": "https://leetcode.com/problems/find-the-k-sum-of-an-array/discuss/2456716/Python3-HeapPriority-Queue-O(NlogN-%2B-klogk)",
      "python_solutions": "class Solution:\n    def kSum(self, nums: List[int], k: int) -> int:\n        maxSum = sum([max(0, num) for num in nums])\n        absNums = sorted([abs(num) for num in nums])\n        maxHeap = [(-maxSum + absNums[0], 0)]\n        ans = [maxSum]\n        while len(ans) < k:\n            nextSum, i = heapq.heappop(maxHeap)\n            heapq.heappush(ans, -nextSum)\n            if i + 1 < len(absNums):\n                heapq.heappush(maxHeap, (nextSum - absNums[i] + absNums[i + 1], i + 1))\n                heapq.heappush(maxHeap, (nextSum + absNums[i + 1], i + 1))\n        return ans[0]",
      "slug": "find-the-k-sum-of-an-array",
      "post_title": "[Python3] Heap/Priority Queue, O(NlogN + klogk)",
      "user": "xil899",
      "upvotes": 82,
      "views": 5300,
      "problem_title": "find the k sum of an array",
      "number": 2386,
      "acceptance": 0.377,
      "difficulty": "Hard",
      "__index_level_0__": 32635,
      "question": "You are given an integer array nums and a positive integer k. You can choose any subsequence of the array and sum all of its elements together.\nWe define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).\nReturn the K-Sum of the array.\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\nNote that the empty subsequence is considered to have a sum of 0.\n  Example 1:\nInput: nums = [2,4,-2], k = 5\nOutput: 2\nExplanation: All the possible subsequence sums that we can obtain are the following sorted in decreasing order:\n- 6, 4, 4, 2, 2, 0, 0, -2.\nThe 5-Sum of the array is 2.\nExample 2:\nInput: nums = [1,-2,3,4,-10,12], k = 16\nOutput: 10\nExplanation: The 16-Sum of the array is 10.\n  Constraints:\nn == nums.length\n1 <= n <= 105\n-109 <= nums[i] <= 109\n1 <= k <= min(2000, 2n)"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-subsequence-with-limited-sum/discuss/2492737/Prefix-Sum",
      "python_solutions": "class Solution:\n    def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:\n        nums = list(accumulate(sorted(nums)))\n        return [bisect_right(nums, q) for q in queries]",
      "slug": "longest-subsequence-with-limited-sum",
      "post_title": "Prefix Sum",
      "user": "votrubac",
      "upvotes": 9,
      "views": 1200,
      "problem_title": "longest subsequence with limited sum",
      "number": 2389,
      "acceptance": 0.648,
      "difficulty": "Easy",
      "__index_level_0__": 32638,
      "question": "You are given an integer array nums of length n, and an integer array queries of length m.\nReturn an array answer of length m where answer[i] is the maximum size of a subsequence that you can take from nums such that the sum of its elements is less than or equal to queries[i].\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n  Example 1:\nInput: nums = [4,5,2,1], queries = [3,10,21]\nOutput: [2,3,4]\nExplanation: We answer the queries as follows:\n- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.\n- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.\n- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.\nExample 2:\nInput: nums = [2,3,4,5], queries = [1]\nOutput: [0]\nExplanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.\n  Constraints:\nn == nums.length\nm == queries.length\n1 <= n, m <= 1000\n1 <= nums[i], queries[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/removing-stars-from-a-string/discuss/2492763/Python3-stack",
      "python_solutions": "class Solution: \n    def removeStars(self, s: str) -> str:\n        stack = []\n        for ch in s: \n            if ch == '*': stack.pop()\n            else: stack.append(ch)\n        return ''.join(stack)",
      "slug": "removing-stars-from-a-string",
      "post_title": "[Python3] stack",
      "user": "ye15",
      "upvotes": 3,
      "views": 46,
      "problem_title": "removing stars from a string",
      "number": 2390,
      "acceptance": 0.64,
      "difficulty": "Medium",
      "__index_level_0__": 32655,
      "question": "You are given a string s, which contains stars *.\nIn one operation, you can:\nChoose a star in s.\nRemove the closest non-star character to its left, as well as remove the star itself.\nReturn the string after all stars have been removed.\nNote:\nThe input will be generated such that the operation is always possible.\nIt can be shown that the resulting string will always be unique.\n  Example 1:\nInput: s = \"leet**cod*e\"\nOutput: \"lecoe\"\nExplanation: Performing the removals from left to right:\n- The closest character to the 1st star is 't' in \"leet**cod*e\". s becomes \"lee*cod*e\".\n- The closest character to the 2nd star is 'e' in \"lee*cod*e\". s becomes \"lecod*e\".\n- The closest character to the 3rd star is 'd' in \"lecod*e\". s becomes \"lecoe\".\nThere are no more stars, so we return \"lecoe\".\nExample 2:\nInput: s = \"erase*****\"\nOutput: \"\"\nExplanation: The entire string is removed, so we return an empty string.\n  Constraints:\n1 <= s.length <= 105\ns consists of lowercase English letters and stars *.\nThe operation above can be performed on s."
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-amount-of-time-to-collect-garbage/discuss/2492802/Python3-simulation",
      "python_solutions": "class Solution:\n    def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n        ans = sum(map(len, garbage))\n        prefix = list(accumulate(travel, initial=0))\n        for ch in \"MPG\": \n            ii = 0 \n            for i, s in enumerate(garbage): \n                if ch in s: ii = i \n            ans += prefix[ii]\n        return ans",
      "slug": "minimum-amount-of-time-to-collect-garbage",
      "post_title": "[Python3] simulation",
      "user": "ye15",
      "upvotes": 4,
      "views": 48,
      "problem_title": "minimum amount of time to collect garbage",
      "number": 2391,
      "acceptance": 0.851,
      "difficulty": "Medium",
      "__index_level_0__": 32682,
      "question": "You are given a 0-indexed array of strings garbage where garbage[i] represents the assortment of garbage at the ith house. garbage[i] consists only of the characters 'M', 'P' and 'G' representing one unit of metal, paper and glass garbage respectively. Picking up one unit of any type of garbage takes 1 minute.\nYou are also given a 0-indexed integer array travel where travel[i] is the number of minutes needed to go from house i to house i + 1.\nThere are three garbage trucks in the city, each responsible for picking up one type of garbage. Each garbage truck starts at house 0 and must visit each house in order; however, they do not need to visit every house.\nOnly one garbage truck may be used at any given moment. While one truck is driving or picking up garbage, the other two trucks cannot do anything.\nReturn the minimum number of minutes needed to pick up all the garbage.\n  Example 1:\nInput: garbage = [\"G\",\"P\",\"GP\",\"GG\"], travel = [2,4,3]\nOutput: 21\nExplanation:\nThe paper garbage truck:\n1. Travels from house 0 to house 1\n2. Collects the paper garbage at house 1\n3. Travels from house 1 to house 2\n4. Collects the paper garbage at house 2\nAltogether, it takes 8 minutes to pick up all the paper garbage.\nThe glass garbage truck:\n1. Collects the glass garbage at house 0\n2. Travels from house 0 to house 1\n3. Travels from house 1 to house 2\n4. Collects the glass garbage at house 2\n5. Travels from house 2 to house 3\n6. Collects the glass garbage at house 3\nAltogether, it takes 13 minutes to pick up all the glass garbage.\nSince there is no metal garbage, we do not need to consider the metal garbage truck.\nTherefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.\nExample 2:\nInput: garbage = [\"MMM\",\"PGM\",\"GP\"], travel = [3,10]\nOutput: 37\nExplanation:\nThe metal garbage truck takes 7 minutes to pick up all the metal garbage.\nThe paper garbage truck takes 15 minutes to pick up all the paper garbage.\nThe glass garbage truck takes 15 minutes to pick up all the glass garbage.\nIt takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.\n  Constraints:\n2 <= garbage.length <= 105\ngarbage[i] consists of only the letters 'M', 'P', and 'G'.\n1 <= garbage[i].length <= 10\ntravel.length == garbage.length - 1\n1 <= travel[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/build-a-matrix-with-conditions/discuss/2492822/Python3-topological-sort",
      "python_solutions": "class Solution:\n    def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n        \n        def fn(cond): \n            \"\"\"Return topological sort\"\"\"\n            graph = [[] for _ in range(k)]\n            indeg = [0]*k\n            for u, v in cond: \n                graph[u-1].append(v-1)\n                indeg[v-1] += 1\n            queue = deque(u for u, x in enumerate(indeg) if x == 0)\n            ans = []\n            while queue: \n                u = queue.popleft()\n                ans.append(u+1)\n                for v in graph[u]: \n                    indeg[v] -= 1\n                    if indeg[v] == 0: queue.append(v)\n            return ans \n        \n        row = fn(rowConditions)\n        col = fn(colConditions)\n        \n        if len(row) < k or len(col) < k: return []\n        ans = [[0]*k for _ in range(k)]\n        row = {x : i for i, x in enumerate(row)}\n        col = {x : j for j, x in enumerate(col)}\n        for x in range(1, k+1): ans[row[x]][col[x]] = x\n        return ans",
      "slug": "build-a-matrix-with-conditions",
      "post_title": "[Python3] topological sort",
      "user": "ye15",
      "upvotes": 12,
      "views": 339,
      "problem_title": "build a matrix with conditions",
      "number": 2392,
      "acceptance": 0.5920000000000001,
      "difficulty": "Hard",
      "__index_level_0__": 32704,
      "question": "You are given a positive integer k. You are also given:\na 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and\na 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].\nThe two arrays contain integers from 1 to k.\nYou have to build a k x k matrix that contains each of the numbers from 1 to k exactly once. The remaining cells should have the value 0.\nThe matrix should also satisfy the following conditions:\nThe number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.\nThe number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1.\nReturn any matrix that satisfies the conditions. If no answer exists, return an empty matrix.\n  Example 1:\nInput: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]\nOutput: [[3,0,0],[0,0,1],[0,2,0]]\nExplanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.\nThe row conditions are the following:\n- Number 1 is in row 1, and number 2 is in row 2, so 1 is above 2 in the matrix.\n- Number 3 is in row 0, and number 2 is in row 2, so 3 is above 2 in the matrix.\nThe column conditions are the following:\n- Number 2 is in column 1, and number 1 is in column 2, so 2 is left of 1 in the matrix.\n- Number 3 is in column 0, and number 2 is in column 1, so 3 is left of 2 in the matrix.\nNote that there may be multiple correct answers.\nExample 2:\nInput: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]\nOutput: []\nExplanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.\nNo matrix can satisfy all the conditions, so we return the empty matrix.\n  Constraints:\n2 <= k <= 400\n1 <= rowConditions.length, colConditions.length <= 104\nrowConditions[i].length == colConditions[i].length == 2\n1 <= abovei, belowi, lefti, righti <= k\nabovei != belowi\nlefti != righti"
    },
    {
      "post_href": "https://leetcode.com/problems/find-subarrays-with-equal-sum/discuss/2525818/Python-oror-Sliding-window-oror-Bruteforce",
      "python_solutions": "class Solution:\n    def findSubarrays(self, nums: List[int]) -> bool:\n    \"\"\" \n\tBruteforce approch\n\t\"\"\"\n#         for i in range(len(nums)-2):\n#             summ1 = nums[i] + nums[i+1]\n#             # for j in range(i+1,len(nums)):\n#             for j in range(i+1,len(nums)-1):\n#                 summ = nums[j] + nums[j+1]\n#                 if summ == summ1:\n#                     return True\n#         return False\n\t \"\"\"\n\t Sliding Window\n\t \"\"\"\n        one ,two = len(nums)-2,len(nums)-1      // at end of list\n        dic = {}\n        while one >= 0:\n            # print(one,two)\n            summ = nums[one] + nums[two]\n            if summ in dic:\n                return True               // if already there then there is 2 pairs\n            else:\n                dic[summ] = 1        // add summ in of window in dictonary\n            one -=1\n            two -=1\n        return False",
      "slug": "find-subarrays-with-equal-sum",
      "post_title": "Python || Sliding window || Bruteforce",
      "user": "1md3nd",
      "upvotes": 4,
      "views": 85,
      "problem_title": "find subarrays with equal sum",
      "number": 2395,
      "acceptance": 0.639,
      "difficulty": "Easy",
      "__index_level_0__": 32713,
      "question": "Given a 0-indexed integer array nums, determine whether there exist two subarrays of length 2 with equal sum. Note that the two subarrays must begin at different indices.\nReturn true if these subarrays exist, and false otherwise.\nA subarray is a contiguous non-empty sequence of elements within an array.\n  Example 1:\nInput: nums = [4,2,4]\nOutput: true\nExplanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.\nExample 2:\nInput: nums = [1,2,3,4,5]\nOutput: false\nExplanation: No two subarrays of size 2 have the same sum.\nExample 3:\nInput: nums = [0,0,0]\nOutput: true\nExplanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. \nNote that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.\n  Constraints:\n2 <= nums.length <= 1000\n-109 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/strictly-palindromic-number/discuss/2801453/Python-oror-95.34-Faster-oror-Easy-and-Actual-Solution-oror-O(n)-Solution",
      "python_solutions": "class Solution:\n    def isStrictlyPalindromic(self, n: int) -> bool:\n        def int2base(n,b):\n            r=\"\"\n            while n>0:\n                r+=str(n%b)\n                n//=b           \n            return int(r[-1::-1])\n        for i in range(2,n-1):\n            if int2base(n,i)!=n:\n                return False\n        return True",
      "slug": "strictly-palindromic-number",
      "post_title": "Python || 95.34% Faster || Easy and Actual Solution || O(n) Solution",
      "user": "DareDevil_007",
      "upvotes": 2,
      "views": 186,
      "problem_title": "strictly palindromic number",
      "number": 2396,
      "acceptance": 0.877,
      "difficulty": "Medium",
      "__index_level_0__": 32729,
      "question": "An integer n is strictly palindromic if, for every base b between 2 and n - 2 (inclusive), the string representation of the integer n in base b is palindromic.\nGiven an integer n, return true if n is strictly palindromic and false otherwise.\nA string is palindromic if it reads the same forward and backward.\n  Example 1:\nInput: n = 9\nOutput: false\nExplanation: In base 2: 9 = 1001 (base 2), which is palindromic.\nIn base 3: 9 = 100 (base 3), which is not palindromic.\nTherefore, 9 is not strictly palindromic so we return false.\nNote that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.\nExample 2:\nInput: n = 4\nOutput: false\nExplanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.\nTherefore, we return false.\n  Constraints:\n4 <= n <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-rows-covered-by-columns/discuss/2524746/Python-Simple-Solution",
      "python_solutions": "class Solution:\n    def maximumRows(self, mat: List[List[int]], cols: int) -> int:\n        n,m = len(mat),len(mat[0])\n        ans = 0\n\n        def check(state,row,rowIncludedCount):\n            nonlocal ans\n            if row==n:\n                if sum(state)<=cols:\n                    ans = max(ans,rowIncludedCount)\n                return\n            \n            check(state[::],row+1,rowIncludedCount)\n            for j in range(m):\n                if mat[row][j]==1:\n                    state[j] = 1\n            check(state,row+1,rowIncludedCount+1)\n        \n        check([0]*m,0,0)\n        return ans",
      "slug": "maximum-rows-covered-by-columns",
      "post_title": "Python Simple Solution",
      "user": "RedHeadphone",
      "upvotes": 4,
      "views": 431,
      "problem_title": "maximum rows covered by columns",
      "number": 2397,
      "acceptance": 0.525,
      "difficulty": "Medium",
      "__index_level_0__": 32744,
      "question": "You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix.\nLet us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if:\nFor each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or,\nNo cell in row has a value of 1.\nYou need to choose numSelect columns such that the number of rows that are covered is maximized.\nReturn the maximum number of rows that can be covered by a set of numSelect columns.\n  Example 1:\nInput: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2\nOutput: 3\nExplanation: One possible way to cover 3 rows is shown in the diagram above.\nWe choose s = {0, 2}.\n- Row 0 is covered because it has no occurrences of 1.\n- Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s.\n- Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s.\n- Row 3 is covered because matrix[2][2] == 1 and 2 is present in s.\nThus, we can cover three rows.\nNote that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered.\nExample 2:\nInput: matrix = [[1],[0]], numSelect = 1\nOutput: 2\nExplanation: Selecting the only column will result in both rows being covered since the entire matrix is selected.\nTherefore, we return 2.\n  Constraints:\nm == matrix.length\nn == matrix[i].length\n1 <= m, n <= 12\nmatrix[i][j] is either 0 or 1.\n1 <= numSelect <= n"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-number-of-robots-within-budget/discuss/2526141/Python3-Intuition-Explained-or-Sliding-Window-or-Similar-Problems-Link",
      "python_solutions": "class Solution:\n    def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int:\n        \n        n=len(chargeTimes)\n        start=0\n        runningsum=0\n        max_consecutive=0\n        max_so_far=0\n        secondmax=0\n        \n        for end in range(n):\n            runningsum+=runningCosts[end]\n            \n            if max_so_far<=chargeTimes[end]:\n                secondmax=max_so_far\n                max_so_far=chargeTimes[end]\n                \n            k=end-start+1\n            \n            currentbudget=max_so_far+(k*runningsum)\n            \n            if currentbudget>budget:\n                runningsum-=runningCosts[start]\n                max_so_far=secondmax if chargeTimes[start]==max_so_far else max_so_far\n                start+=1\n\t\t\t\t\n            max_consecutive=max(max_consecutive,end-start+1)\n\t\t\t\n        return max_consecutive",
      "slug": "maximum-number-of-robots-within-budget",
      "post_title": "[Python3] Intuition Explained \ud83d\udd25 | Sliding Window   | Similar Problems Link \ud83d\ude80",
      "user": "glimloop",
      "upvotes": 1,
      "views": 61,
      "problem_title": "maximum number of robots within budget",
      "number": 2398,
      "acceptance": 0.322,
      "difficulty": "Hard",
      "__index_level_0__": 32755,
      "question": "You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget.\nThe total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots.\nReturn the maximum number of consecutive robots you can run such that the total cost does not exceed budget.\n  Example 1:\nInput: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25\nOutput: 3\nExplanation: \nIt is possible to run all individual and consecutive pairs of robots within budget.\nTo obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25.\nIt can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3.\nExample 2:\nInput: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19\nOutput: 0\nExplanation: No robot can be run that does not exceed the budget, so we return 0.\n  Constraints:\nchargeTimes.length == runningCosts.length == n\n1 <= n <= 5 * 104\n1 <= chargeTimes[i], runningCosts[i] <= 105\n1 <= budget <= 1015"
    },
    {
      "post_href": "https://leetcode.com/problems/check-distances-between-same-letters/discuss/2531135/Python3-oror-3-lines-TM%3A-36ms13.8MB",
      "python_solutions": "class Solution:   # Pretty much explains itself.\n    def checkDistances(self, s: str, distance: List[int]) -> bool:\n        \n        d = defaultdict(list)\n\n        for i, ch in enumerate(s):\n            d[ch].append(i)\n\n        return all(b-a-1 == distance[ord(ch)-97] for ch, (a,b) in d.items())",
      "slug": "check-distances-between-same-letters",
      "post_title": "Python3    ||  3 lines,   T/M: 36ms/13.8MB",
      "user": "warrenruud",
      "upvotes": 8,
      "views": 596,
      "problem_title": "check distances between same letters",
      "number": 2399,
      "acceptance": 0.7040000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 32763,
      "question": "You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.\nEach letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25).\nIn a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.\nReturn true if s is a well-spaced string, otherwise return false.\n  Example 1:\nInput: s = \"abaccb\", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: true\nExplanation:\n- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.\n- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.\n- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.\nNote that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.\nReturn true because s is a well-spaced string.\nExample 2:\nInput: s = \"aa\", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\nOutput: false\nExplanation:\n- 'a' appears at indices 0 and 1 so there are zero letters between them.\nBecause distance[0] = 1, s is not a well-spaced string.\n  Constraints:\n2 <= s.length <= 52\ns consists only of lowercase English letters.\nEach letter appears in s exactly twice.\ndistance.length == 26\n0 <= distance[i] <= 50"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/discuss/2554923/Python3-oror-3-lines-combs-w-explanation-oror-TM%3A-9692",
      "python_solutions": "class Solution:          # A few points on the problem:\n                         #   \u2022 The start and end is a \"red herring.\" The answer to the problem \n                         #     depends only on the distance (dist = end-start) and k.\n                         #  \n                         #   \u2022 A little thought will convince one that theres no paths possible \n                         #     if k%2 != dist%2 or if abs(dist) > k.\n\n                         #   \u2022 The problem is equivalent to:\n                         #        Determine the count of distinct lists of length k with sum = dist\n                         #        and elements 1 and -1, in which the counts of 1s and -1s in each \n                         #        list differ by dist.\n                         # \n                         #   \u2022 The count of the lists is equal to the number of ways  the combination \n                         #     C((k, (dist+k)//2)). For example, if dist = 1 and k = 5. the count of 1s\n\t\t\t\t\t\t #.    is (5+1)//2 = 3, and C(5,3) = 10.\n                         #     (Note that if dist= -1 in this example, (5-1)//2 = 2, and C(5,2) = 10)\n\n    def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:\n\n        dist = endPos-startPos\n\n        if k%2 != dist%2 or abs(dist) > k: return 0\n\n        return comb(k, (dist+k)//2) %1000000007",
      "slug": "number-of-ways-to-reach-a-position-after-exactly-k-steps",
      "post_title": "Python3 ||  3 lines, combs, w/ explanation  ||  T/M: 96%/92%",
      "user": "warrenruud",
      "upvotes": 3,
      "views": 157,
      "problem_title": "number of ways to reach a position after exactly k steps",
      "number": 2400,
      "acceptance": 0.3229999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 32781,
      "question": "You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right.\nGiven a positive integer k, return the number of different ways to reach the position endPos starting from startPos, such that you perform exactly k steps. Since the answer may be very large, return it modulo 109 + 7.\nTwo ways are considered different if the order of the steps made is not exactly the same.\nNote that the number line includes negative integers.\n  Example 1:\nInput: startPos = 1, endPos = 2, k = 3\nOutput: 3\nExplanation: We can reach position 2 from 1 in exactly 3 steps in three ways:\n- 1 -> 2 -> 3 -> 2.\n- 1 -> 2 -> 1 -> 2.\n- 1 -> 0 -> 1 -> 2.\nIt can be proven that no other way is possible, so we return 3.\nExample 2:\nInput: startPos = 2, endPos = 5, k = 10\nOutput: 0\nExplanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.\n  Constraints:\n1 <= startPos, endPos, k <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-nice-subarray/discuss/2527285/Bit-Magic-with-Explanation-and-Complexities",
      "python_solutions": "class Solution:\n    def longestNiceSubarray(self, nums: List[int]) -> int:\n        maximum_length = 1\n        n = len(nums)\n        \n        current_group = 0\n        left = 0\n        \n        for right in range(n):\n\t\t\t# If the number at the right point is safe to include, include it in the group and update the maximum length.\n            if nums[right] & current_group == 0:\n                current_group |=nums[right]\n                maximum_length = max(maximum_length, right - left + 1)\n                continue\n                \n\t\t\t# Shrink the window until the number at the right pointer is safe to include.\n            while left < right and nums[right] & current_group != 0:    \n                current_group &= (~nums[left]) \n                left += 1\n            \n\t\t\t# Include the number at the right pointer in the group.\n            current_group |= nums[right]\n                \n        return maximum_length",
      "slug": "longest-nice-subarray",
      "post_title": "Bit Magic with Explanation and Complexities",
      "user": "wickedmishra",
      "upvotes": 19,
      "views": 488,
      "problem_title": "longest nice subarray",
      "number": 2401,
      "acceptance": 0.48,
      "difficulty": "Medium",
      "__index_level_0__": 32799,
      "question": "You are given an array nums consisting of positive integers.\nWe call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.\nReturn the length of the longest nice subarray.\nA subarray is a contiguous part of an array.\nNote that subarrays of length 1 are always considered nice.\n  Example 1:\nInput: nums = [1,3,8,48,10]\nOutput: 3\nExplanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:\n- 3 AND 8 = 0.\n- 3 AND 48 = 0.\n- 8 AND 48 = 0.\nIt can be proven that no longer nice subarray can be obtained, so we return 3.\nExample 2:\nInput: nums = [3,1,5,11,13]\nOutput: 1\nExplanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/meeting-rooms-iii/discuss/2527343/Python-or-More-heap-extravaganza",
      "python_solutions": "class Solution:\r\n    def mostBooked(self, n: int, meetings: List[List[int]]) -> int:\r\n        meetings.sort() # make sure start times are sorted!!\r\n        \r\n        meetingCount = [0 for _ in range(n)]\r\n        availableRooms = list(range(n)); heapify(availableRooms)\r\n        occupiedRooms = []\r\n        \r\n        \r\n        for start, end in meetings:\r\n            while occupiedRooms and start >= occupiedRooms[0][0]:\r\n                heappush(availableRooms, heappop(occupiedRooms)[1]) # frees room and makes it available\r\n            \r\n            if availableRooms:\r\n                roomNumber = heappop(availableRooms)  # assigns next available room\r\n            else:\r\n                freedEnd, roomNumber = heappop(occupiedRooms)  # waits until the next room that would be available gets free\r\n                end += freedEnd - start\r\n            heappush(occupiedRooms, (end,roomNumber))  # make note that the ruom is occupied and when the assigned meeting ends\r\n            meetingCount[roomNumber] += 1  # update meeting counter\r\n            \r\n        return sorted([(count, i) for i, count in enumerate(meetingCount)], key = lambda x: (-x[0], x[1]))[0][1]  # find room with most meetings",
      "slug": "meeting-rooms-iii",
      "post_title": "Python | More heap extravaganza",
      "user": "sr_vrd",
      "upvotes": 1,
      "views": 41,
      "problem_title": "meeting rooms iii",
      "number": 2402,
      "acceptance": 0.332,
      "difficulty": "Hard",
      "__index_level_0__": 32809,
      "question": "You are given an integer n. There are n rooms numbered from 0 to n - 1.\nYou are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.\nMeetings are allocated to rooms in the following manner:\nEach meeting will take place in the unused room with the lowest number.\nIf there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.\nWhen a room becomes unused, meetings that have an earlier original start time should be given the room.\nReturn the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.\nA half-closed interval [a, b) is the interval between a and b including a and not including b.\n  Example 1:\nInput: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]\nOutput: 0\nExplanation:\n- At time 0, both rooms are not being used. The first meeting starts in room 0.\n- At time 1, only room 1 is not being used. The second meeting starts in room 1.\n- At time 2, both rooms are being used. The third meeting is delayed.\n- At time 3, both rooms are being used. The fourth meeting is delayed.\n- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).\n- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).\nBoth rooms 0 and 1 held 2 meetings, so we return 0. \nExample 2:\nInput: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]\nOutput: 1\nExplanation:\n- At time 1, all three rooms are not being used. The first meeting starts in room 0.\n- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.\n- At time 3, only room 2 is not being used. The third meeting starts in room 2.\n- At time 4, all three rooms are being used. The fourth meeting is delayed.\n- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).\n- At time 6, all three rooms are being used. The fifth meeting is delayed.\n- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).\nRoom 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1. \n  Constraints:\n1 <= n <= 100\n1 <= meetings.length <= 105\nmeetings[i].length == 2\n0 <= starti < endi <= 5 * 105\nAll the values of starti are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/most-frequent-even-element/discuss/2581151/Python-3-oror-2-lines-Counter-oror-TM%3A-9586",
      "python_solutions": "class Solution:\n    def mostFrequentEven(self, nums: List[int]) -> int:\n        ctr = Counter(nums)\n        return max([c for c in ctr if not c%2], key = lambda x:(ctr[x], -x), default = -1)",
      "slug": "most-frequent-even-element",
      "post_title": "Python 3   ||  2 lines, Counter  ||   T/M: 95%/86%",
      "user": "warrenruud",
      "upvotes": 6,
      "views": 268,
      "problem_title": "most frequent even element",
      "number": 2404,
      "acceptance": 0.516,
      "difficulty": "Easy",
      "__index_level_0__": 32816,
      "question": "Given an integer array nums, return the most frequent even element.\nIf there is a tie, return the smallest one. If there is no such element, return -1.\n  Example 1:\nInput: nums = [0,1,2,2,4,4,1]\nOutput: 2\nExplanation:\nThe even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.\nWe return the smallest one, which is 2.\nExample 2:\nInput: nums = [4,4,4,9,2,4]\nOutput: 4\nExplanation: 4 is the even element appears the most.\nExample 3:\nInput: nums = [29,47,21,41,13,37,25,7]\nOutput: -1\nExplanation: There is no even element.\n  Constraints:\n1 <= nums.length <= 2000\n0 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/optimal-partition-of-string/discuss/2560044/Python3-Greedy",
      "python_solutions": "class Solution:\n    def partitionString(self, s: str) -> int:\n        cur = set()\n        res = 1\n        \n        for c in s:\n            if c in cur:\n                cur = set()\n                res += 1\n            cur.add(c)\n                \n        return res",
      "slug": "optimal-partition-of-string",
      "post_title": "[Python3] Greedy",
      "user": "0xRoxas",
      "upvotes": 9,
      "views": 547,
      "problem_title": "optimal partition of string",
      "number": 2405,
      "acceptance": 0.7440000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 32844,
      "question": "Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.\nReturn the minimum number of substrings in such a partition.\nNote that each character should belong to exactly one substring in a partition.\n  Example 1:\nInput: s = \"abacaba\"\nOutput: 4\nExplanation:\nTwo possible partitions are (\"a\",\"ba\",\"cab\",\"a\") and (\"ab\",\"a\",\"ca\",\"ba\").\nIt can be shown that 4 is the minimum number of substrings needed.\nExample 2:\nInput: s = \"ssssss\"\nOutput: 6\nExplanation:\nThe only valid partition is (\"s\",\"s\",\"s\",\"s\",\"s\",\"s\").\n  Constraints:\n1 <= s.length <= 105\ns consists of only English lowercase letters."
    },
    {
      "post_href": "https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/discuss/2560020/Min-Heap",
      "python_solutions": "class Solution:\n    def minGroups(self, intervals: List[List[int]]) -> int:\n        pq = []\n        for left, right in sorted(intervals):\n            if pq and pq[0] < left:\n                heappop(pq)\n            heappush(pq, right)\n        return len(pq)",
      "slug": "divide-intervals-into-minimum-number-of-groups",
      "post_title": "Min Heap",
      "user": "votrubac",
      "upvotes": 227,
      "views": 5600,
      "problem_title": "divide intervals into minimum number of groups",
      "number": 2406,
      "acceptance": 0.4539999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 32873,
      "question": "You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].\nYou have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.\nReturn the minimum number of groups you need to make.\nTwo intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.\n  Example 1:\nInput: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]\nOutput: 3\nExplanation: We can divide the intervals into the following groups:\n- Group 1: [1, 5], [6, 8].\n- Group 2: [2, 3], [5, 10].\n- Group 3: [1, 10].\nIt can be proven that it is not possible to divide the intervals into fewer than 3 groups.\nExample 2:\nInput: intervals = [[1,3],[5,6],[8,10],[11,13]]\nOutput: 1\nExplanation: None of the intervals overlap, so we can put all of them in one group.\n  Constraints:\n1 <= intervals.length <= 105\nintervals[i].length == 2\n1 <= lefti <= righti <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/longest-increasing-subsequence-ii/discuss/2591153/Python-runtime-O(n-logn)-memory-O(n)",
      "python_solutions": "class Solution:\n    def getmax(self, st, start, end):\n        maxi = 0\n        \n        while start < end:\n            if start%2:#odd\n                maxi = max(maxi, st[start])\n                start += 1\n            if end%2:#odd\n                end -= 1\n                maxi = max(maxi, st[end])\n            start //= 2\n            end //= 2\n        return maxi\n        \n    def update(self, st, maxi, n):\n        st[n] = maxi\n        while n > 1:\n            n //= 2\n            st[n] = max(st[2*n], st[2*n+1])\n    \n    def lengthOfLIS(self, nums: List[int], k: int) -> int:\n        ans = 1\n        length = max(nums)\n        st = [0]*length*2\n        for n in nums:\n            n -= 1\n            maxi = self.getmax(st, max(0, n-k)+length, n+length) + 1\n            self.update(st, maxi, n+length)\n            ans = max(maxi, ans)\n        return ans",
      "slug": "longest-increasing-subsequence-ii",
      "post_title": "Python, runtime O(n logn), memory O(n)",
      "user": "tsai00150",
      "upvotes": 0,
      "views": 114,
      "problem_title": "longest increasing subsequence ii",
      "number": 2407,
      "acceptance": 0.209,
      "difficulty": "Hard",
      "__index_level_0__": 32886,
      "question": "You are given an integer array nums and an integer k.\nFind the longest subsequence of nums that meets the following requirements:\nThe subsequence is strictly increasing and\nThe difference between adjacent elements in the subsequence is at most k.\nReturn the length of the longest subsequence that meets the requirements.\nA subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.\n  Example 1:\nInput: nums = [4,2,1,4,3,4,5,8,15], k = 3\nOutput: 5\nExplanation:\nThe longest subsequence that meets the requirements is [1,3,4,5,8].\nThe subsequence has a length of 5, so we return 5.\nNote that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3.\nExample 2:\nInput: nums = [7,4,5,1,8,12,4,7], k = 5\nOutput: 4\nExplanation:\nThe longest subsequence that meets the requirements is [4,5,8,12].\nThe subsequence has a length of 4, so we return 4.\nExample 3:\nInput: nums = [1,5], k = 1\nOutput: 1\nExplanation:\nThe longest subsequence that meets the requirements is [1].\nThe subsequence has a length of 1, so we return 1.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i], k <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/count-days-spent-together/discuss/2601983/Very-Easy-Question-or-Visual-Explanation-or-100",
      "python_solutions": "class Solution:\n    def countDaysTogether(self, arAl: str, lAl: str, arBo: str, lBo: str) -> int:\n        months = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n        start = max(arAl, arBo)\n        end = min(lAl, lBo)\n\n        startDay = int(start[3:])\n        startMonth = int(start[:2])\n        endDay = int(end[3:])\n        endMonth = int(end[:2])\n        \n        if start > end:\n            return 0\n        if startMonth == endMonth:\n            return endDay-startDay+1\n        elif startMonth < endMonth:\n            return months[startMonth]-startDay + endDay + 1 + sum(months[m] for m in range(startMonth+1, endMonth))",
      "slug": "count-days-spent-together",
      "post_title": "Very Easy Question | Visual Explanation | 100%",
      "user": "leet_satyam",
      "upvotes": 3,
      "views": 78,
      "problem_title": "count days spent together",
      "number": 2409,
      "acceptance": 0.428,
      "difficulty": "Easy",
      "__index_level_0__": 32888,
      "question": "Alice and Bob are traveling to Rome for separate business meetings.\nYou are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format \"MM-DD\", corresponding to the month and day of the date.\nReturn the total number of days that Alice and Bob are in Rome together.\nYou can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].\n  Example 1:\nInput: arriveAlice = \"08-15\", leaveAlice = \"08-18\", arriveBob = \"08-16\", leaveBob = \"08-19\"\nOutput: 3\nExplanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3.\nExample 2:\nInput: arriveAlice = \"10-01\", leaveAlice = \"10-31\", arriveBob = \"11-01\", leaveBob = \"12-31\"\nOutput: 0\nExplanation: There is no day when Alice and Bob are in Rome together, so we return 0.\n  Constraints:\nAll dates are provided in the format \"MM-DD\".\nAlice and Bob's arrival dates are earlier than or equal to their leaving dates.\nThe given dates are valid dates of a non-leap year."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-matching-of-players-with-trainers/discuss/2588450/Python-code-using-recursion",
      "python_solutions": "class Solution:\n    def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:\n        n = len(players)\n        m = len(trainers)\n        players.sort()\n        trainers.sort()\n        dp = {}\n        def helper(i,j):\n            if i==n or j==m:\n                return 0\n            if (i,j) in dp:\n                return dp[(i,j)]\n            if players[i]<=trainers[j]:\n                dp[(i,j)] = 1+helper(i+1,j+1)\n            else:\n                dp[(i,j)] = helper(i,j+1)\n            return dp[(i,j)]\n        return helper(0,0)",
      "slug": "maximum-matching-of-players-with-trainers",
      "post_title": "Python code using recursion",
      "user": "kamal0308",
      "upvotes": 2,
      "views": 53,
      "problem_title": "maximum matching of players with trainers",
      "number": 2410,
      "acceptance": 0.598,
      "difficulty": "Medium",
      "__index_level_0__": 32904,
      "question": "You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the training capacity of the jth trainer.\nThe ith player can match with the jth trainer if the player's ability is less than or equal to the trainer's training capacity. Additionally, the ith player can be matched with at most one trainer, and the jth trainer can be matched with at most one player.\nReturn the maximum number of matchings between players and trainers that satisfy these conditions.\n  Example 1:\nInput: players = [4,7,9], trainers = [8,2,5,8]\nOutput: 2\nExplanation:\nOne of the ways we can form two matchings is as follows:\n- players[0] can be matched with trainers[0] since 4 <= 8.\n- players[1] can be matched with trainers[3] since 7 <= 8.\nIt can be proven that 2 is the maximum number of matchings that can be formed.\nExample 2:\nInput: players = [1,1,1], trainers = [10]\nOutput: 1\nExplanation:\nThe trainer can be matched with any of the 3 players.\nEach player can only be matched with one trainer, so the maximum answer is 1.\n  Constraints:\n1 <= players.length, trainers.length <= 105\n1 <= players[i], trainers[j] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/discuss/2588110/Secret-Python-Answer-Sliding-Window-with-Double-Dictionary-of-Binary-Count",
      "python_solutions": "class Solution:\n    def smallestSubarrays(self, nums: List[int]) -> List[int]:\n\n        def create(m):\n            t = 0\n            for n in m:\n                if m[n] > 0:\n                    t = t | (1 << n)\n            return t\n        \n        def add(a,m):\n            ans = bin( a )\n            s = str(ans)[2:]\n            for i, b in enumerate( s[::-1]):\n                if b == '1':\n                    m[i] += 1\n\n        def remove(a,m):\n            ans = bin( a )\n            s = str(ans)[2:]\n            for i, b in enumerate( s[::-1]):\n                if b == '1':\n                    m[i] -= 1\n        \n        res = []\n\n        \n        n = defaultdict(int)\n        for i in nums:\n            add(i,n)\n\n        \n        m = defaultdict(int)\n        r = 0\n        c = 0\n\n        for i,v in enumerate(nums):\n            # The last check is for if nums[i] == 0, in that case we still want to add to the map\n            while r < len(nums) and (create(m) != create(n) or (c==0 and nums[i] ==0)):\n                add(nums[r],m)\n                r+=1\n                c+=1\n\n            res.append(c)\n\n            remove(nums[i],m)\n            remove(nums[i],n)\n            c-=1\n\n        return res",
      "slug": "smallest-subarrays-with-maximum-bitwise-or",
      "post_title": "[Secret Python Answer\ud83e\udd2b\ud83d\udc0d\ud83d\udc4c\ud83d\ude0d]  Sliding Window with Double Dictionary of Binary Count",
      "user": "xmky",
      "upvotes": 1,
      "views": 113,
      "problem_title": "smallest subarrays with maximum bitwise or",
      "number": 2411,
      "acceptance": 0.4029999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 32915,
      "question": "You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR.\nIn other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i <= k <= n - 1.\nThe bitwise OR of an array is the bitwise OR of all the numbers in it.\nReturn an integer array answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR.\nA subarray is a contiguous non-empty sequence of elements within an array.\n  Example 1:\nInput: nums = [1,0,2,1,3]\nOutput: [3,3,2,2,1]\nExplanation:\nThe maximum possible bitwise OR starting at any index is 3. \n- Starting at index 0, the shortest subarray that yields it is [1,0,2].\n- Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1].\n- Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1].\n- Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3].\n- Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3].\nTherefore, we return [3,3,2,2,1]. \nExample 2:\nInput: nums = [1,2]\nOutput: [2,1]\nExplanation:\nStarting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.\nStarting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.\nTherefore, we return [2,1].\n  Constraints:\nn == nums.length\n1 <= n <= 105\n0 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-money-required-before-transactions/discuss/2588620/Python3-Greedy",
      "python_solutions": "class Solution:\n    def minimumMoney(self, transactions: List[List[int]]) -> int:\n        ans = val = 0 \n        for cost, cashback in transactions: \n            ans += max(0, cost - cashback)\n            val = max(val, min(cost, cashback))\n        return ans + val",
      "slug": "minimum-money-required-before-transactions",
      "post_title": "[Python3] Greedy",
      "user": "ye15",
      "upvotes": 0,
      "views": 19,
      "problem_title": "minimum money required before transactions",
      "number": 2412,
      "acceptance": 0.391,
      "difficulty": "Hard",
      "__index_level_0__": 32925,
      "question": "You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki].\nThe array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki.\nReturn the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.\n  Example 1:\nInput: transactions = [[2,1],[5,0],[4,2]]\nOutput: 10\nExplanation:\nStarting with money = 10, the transactions can be performed in any order.\nIt can be shown that starting with money < 10 will fail to complete all transactions in some order.\nExample 2:\nInput: transactions = [[3,0],[0,3]]\nOutput: 3\nExplanation:\n- If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3.\n- If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0.\nThus, starting with money = 3, the transactions can be performed in any order.\n  Constraints:\n1 <= transactions.length <= 105\ntransactions[i].length == 2\n0 <= costi, cashbacki <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/smallest-even-multiple/discuss/2601867/LeetCode-The-Hard-Way-Explained-Line-By-Line",
      "python_solutions": "class Solution:\n    def smallestEvenMultiple(self, n: int) -> int:\n\t\t# it's just asking for LCM of 2 and n\n        return lcm(2, n)",
      "slug": "smallest-even-multiple",
      "post_title": "\ud83d\udd25 [LeetCode The Hard Way] \ud83d\udd25 Explained Line By Line",
      "user": "wingkwong",
      "upvotes": 5,
      "views": 258,
      "problem_title": "smallest even multiple",
      "number": 2413,
      "acceptance": 0.879,
      "difficulty": "Easy",
      "__index_level_0__": 32926,
      "question": "Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n.\n  Example 1:\nInput: n = 5\nOutput: 10\nExplanation: The smallest multiple of both 5 and 2 is 10.\nExample 2:\nInput: n = 6\nOutput: 6\nExplanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.\n  Constraints:\n1 <= n <= 150"
    },
    {
      "post_href": "https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/discuss/2594370/Python3-oror-Str-join-and-split-2-lines-oror-TM-375ms15.7-MB",
      "python_solutions": "class Solution:\n    def longestContinuousSubstring(self, s: str) -> int:\n\n        arr = ''.join(['1' if ord(s[i])-ord(s[i-1]) == 1 \n                       else ' ' for i in range(1,len(s))]).split()\n                       \n        return max((len(ones)+1 for ones in arr), default = 1)",
      "slug": "length-of-the-longest-alphabetical-continuous-substring",
      "post_title": "Python3    ||    Str join & split, 2 lines || T/M  375ms/15.7 MB",
      "user": "warrenruud",
      "upvotes": 3,
      "views": 38,
      "problem_title": "length of the longest alphabetical continuous substring",
      "number": 2414,
      "acceptance": 0.5579999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 32963,
      "question": "An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string \"abcdefghijklmnopqrstuvwxyz\".\nFor example, \"abc\" is an alphabetical continuous string, while \"acb\" and \"za\" are not.\nGiven a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.\n  Example 1:\nInput: s = \"abacaba\"\nOutput: 2\nExplanation: There are 4 distinct continuous substrings: \"a\", \"b\", \"c\" and \"ab\".\n\"ab\" is the longest continuous substring.\nExample 2:\nInput: s = \"abcde\"\nOutput: 5\nExplanation: \"abcde\" is the longest continuous substring.\n  Constraints:\n1 <= s.length <= 105\ns consists of only English lowercase letters."
    },
    {
      "post_href": "https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/discuss/2825833/Python-DFS",
      "python_solutions": "class Solution:\n    def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n        def dfs(n1, n2, level):\n            if not n1:\n                return\n            \n            if level % 2:\n                n1.val, n2.val = n2.val, n1.val\n                \n            dfs(n1.left,  n2.right, level + 1)\n            dfs(n1.right, n2.left,  level + 1)\n            \n        dfs(root.left, root.right, 1)       \n        return root",
      "slug": "reverse-odd-levels-of-binary-tree",
      "post_title": "Python, DFS",
      "user": "blue_sky5",
      "upvotes": 0,
      "views": 4,
      "problem_title": "reverse odd levels of binary tree",
      "number": 2415,
      "acceptance": 0.757,
      "difficulty": "Medium",
      "__index_level_0__": 32985,
      "question": "Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.\nFor example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].\nReturn the root of the reversed tree.\nA binary tree is perfect if all parent nodes have two children and all leaves are on the same level.\nThe level of a node is the number of edges along the path between it and the root node.\n  Example 1:\nInput: root = [2,3,5,8,13,21,34]\nOutput: [2,5,3,8,13,21,34]\nExplanation: \nThe tree has only one odd level.\nThe nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.\nExample 2:\nInput: root = [7,13,11]\nOutput: [7,11,13]\nExplanation: \nThe nodes at level 1 are 13, 11, which are reversed and become 11, 13.\nExample 3:\nInput: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]\nOutput: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]\nExplanation: \nThe odd levels have non-zero values.\nThe nodes at level 1 were 1, 2, and are 2, 1 after the reversal.\nThe nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.\n  Constraints:\nThe number of nodes in the tree is in the range [1, 214].\n0 <= Node.val <= 105\nroot is a perfect binary tree."
    },
    {
      "post_href": "https://leetcode.com/problems/sum-of-prefix-scores-of-strings/discuss/2590687/Python-Simple-Python-Solution-Using-Dictionary",
      "python_solutions": "class Solution:\n\tdef sumPrefixScores(self, words: List[str]) -> List[int]:\n\n\t\td = defaultdict(int)\n\n\t\tfor word in words:\n\t\t\tfor index in range(1, len(word) + 1):\n\t\t\t\td[word[:index]] += 1 \n\n\t\tresult = []\n\n\t\tfor word in words:\n\t\t\tcurrent_sum = 0\n\n\t\t\tfor index in range(1, len(word) + 1):\n\t\t\t\tcurrent_sum = current_sum + d[word[:index]]\n\n\t\t\tresult.append(current_sum)\n\n\t\treturn result",
      "slug": "sum-of-prefix-scores-of-strings",
      "post_title": "[ Python ] \u2705\u2705 Simple Python Solution Using Dictionary \ud83e\udd73\u270c\ud83d\udc4d",
      "user": "ASHOK_KUMAR_MEGHVANSHI",
      "upvotes": 1,
      "views": 70,
      "problem_title": "sum of prefix scores of strings",
      "number": 2416,
      "acceptance": 0.426,
      "difficulty": "Hard",
      "__index_level_0__": 33003,
      "question": "You are given an array words of size n consisting of non-empty strings.\nWe define the score of a string word as the number of strings words[i] such that word is a prefix of words[i].\nFor example, if words = [\"a\", \"ab\", \"abc\", \"cab\"], then the score of \"ab\" is 2, since \"ab\" is a prefix of both \"ab\" and \"abc\".\nReturn an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i].\nNote that a string is considered as a prefix of itself.\n  Example 1:\nInput: words = [\"abc\",\"ab\",\"bc\",\"b\"]\nOutput: [5,4,3,2]\nExplanation: The answer for each string is the following:\n- \"abc\" has 3 prefixes: \"a\", \"ab\", and \"abc\".\n- There are 2 strings with the prefix \"a\", 2 strings with the prefix \"ab\", and 1 string with the prefix \"abc\".\nThe total is answer[0] = 2 + 2 + 1 = 5.\n- \"ab\" has 2 prefixes: \"a\" and \"ab\".\n- There are 2 strings with the prefix \"a\", and 2 strings with the prefix \"ab\".\nThe total is answer[1] = 2 + 2 = 4.\n- \"bc\" has 2 prefixes: \"b\" and \"bc\".\n- There are 2 strings with the prefix \"b\", and 1 string with the prefix \"bc\".\nThe total is answer[2] = 2 + 1 = 3.\n- \"b\" has 1 prefix: \"b\".\n- There are 2 strings with the prefix \"b\".\nThe total is answer[3] = 2.\nExample 2:\nInput: words = [\"abcd\"]\nOutput: [4]\nExplanation:\n\"abcd\" has 4 prefixes: \"a\", \"ab\", \"abc\", and \"abcd\".\nEach prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.\n  Constraints:\n1 <= words.length <= 1000\n1 <= words[i].length <= 1000\nwords[i] consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/sort-the-people/discuss/2627285/python3-oror-2-lines-with-example-oror-TM-42ms14.3MB",
      "python_solutions": "class Solution:                   # Ex: names = [\"Larry\",\"Curly\",\"Moe\"]   heights = [130,125,155] \n\n    def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:\n\n        _,names = zip(*sorted(zip(heights,names), reverse = True))   \n                                  # zipped   --> [(130,\"Larry\"), (125,\"Curly\"), (155,\"Moe\")  ]\n                                  # sorted   --> [(155,\"Moe\"  ), (130,\"Larry\"), (125,\"Curly\")]\n                                  # unzipped --> _ = (155,130,125) , names = (\"Moe\",\"Larry\",\"Curly\")\n        \n\t\treturn  list(names)       # list(names) = [\"Moe\",\"Larry\",\"Curly\"]",
      "slug": "sort-the-people",
      "post_title": "python3    ||     2 lines with example    ||     T/M = 42ms/14.3MB",
      "user": "warrenruud",
      "upvotes": 7,
      "views": 575,
      "problem_title": "sort the people",
      "number": 2418,
      "acceptance": 0.82,
      "difficulty": "Easy",
      "__index_level_0__": 33015,
      "question": "You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.\nFor each index i, names[i] and heights[i] denote the name and height of the ith person.\nReturn names sorted in descending order by the people's heights.\n  Example 1:\nInput: names = [\"Mary\",\"John\",\"Emma\"], heights = [180,165,170]\nOutput: [\"Mary\",\"Emma\",\"John\"]\nExplanation: Mary is the tallest, followed by Emma and John.\nExample 2:\nInput: names = [\"Alice\",\"Bob\",\"Bob\"], heights = [155,185,150]\nOutput: [\"Bob\",\"Alice\",\"Bob\"]\nExplanation: The first Bob is the tallest, followed by Alice and the second Bob.\n  Constraints:\nn == names.length == heights.length\n1 <= n <= 103\n1 <= names[i].length <= 20\n1 <= heights[i] <= 105\nnames[i] consists of lower and upper case English letters.\nAll the values of heights are distinct."
    },
    {
      "post_href": "https://leetcode.com/problems/longest-subarray-with-maximum-bitwise-and/discuss/2648255/Group-By-and-One-Pass",
      "python_solutions": "class Solution:\n    def longestSubarray(self, nums: List[int]) -> int:\n        max_n = max(nums)\n        return max(len(list(it)) for n, it in groupby(nums) if n == max_n)",
      "slug": "longest-subarray-with-maximum-bitwise-and",
      "post_title": "Group By and One-Pass",
      "user": "votrubac",
      "upvotes": 7,
      "views": 63,
      "problem_title": "longest subarray with maximum bitwise and",
      "number": 2419,
      "acceptance": 0.477,
      "difficulty": "Medium",
      "__index_level_0__": 33067,
      "question": "You are given an integer array nums of size n.\nConsider a non-empty subarray from nums that has the maximum possible bitwise AND.\nIn other words, let k be the maximum value of the bitwise AND of any subarray of nums. Then, only subarrays with a bitwise AND equal to k should be considered.\nReturn the length of the longest such subarray.\nThe bitwise AND of an array is the bitwise AND of all the numbers in it.\nA subarray is a contiguous sequence of elements within an array.\n  Example 1:\nInput: nums = [1,2,3,3,2,2]\nOutput: 2\nExplanation:\nThe maximum possible bitwise AND of a subarray is 3.\nThe longest subarray with that value is [3,3], so we return 2.\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 1\nExplanation:\nThe maximum possible bitwise AND of a subarray is 4.\nThe longest subarray with that value is [4], so we return 1.\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/find-all-good-indices/discuss/2620637/Python3-Two-passes-O(n)-with-line-by-line-comments.",
      "python_solutions": "class Solution:\n    def goodIndices(self, nums: List[int], k: int) -> List[int]:\n        ### forward pass.\n        forward = [False]*len(nums) ### For the forward pass, store if index i is good or not.\n        stack = []\n        for i in range(len(nums)):\n        \t### if the leangth of stack is greater or equal to k, it means this index is good.\n            if len(stack)>=k:\n                forward[i] = True\n            ### if the stack is empty, just add the current number to it.\n            if not stack:\n                stack.append(nums[i])\n            ### check to see if the current number is smaller or equal to the last number in stack, if it is not, put this number into the stack.\n            else:\n                if nums[i]<=stack[-1]:\n                    stack.append(nums[i])\n                else:\n                    stack = [nums[i]]\n        ### backward pass\n        res = []\n        stack = []\n        for i in reversed(range(len(nums))):\n        \t### Check to see if the length of stack is greater or equal to k and also check if the forward pass at this index is Ture.\n            if len(stack)>=k and forward[i]:\n                res.append(i)\n            if not stack:\n                stack.append(nums[i])\n            else:\n                if nums[i]<=stack[-1]:\n                    stack.append(nums[i])\n                else:\n                    stack = [nums[i]]\n        return res[::-1]",
      "slug": "find-all-good-indices",
      "post_title": "[Python3] Two passes O(n) with line by line comments.",
      "user": "md2030",
      "upvotes": 34,
      "views": 1400,
      "problem_title": "find all good indices",
      "number": 2420,
      "acceptance": 0.372,
      "difficulty": "Medium",
      "__index_level_0__": 33076,
      "question": "You are given a 0-indexed integer array nums of size n and a positive integer k.\nWe call an index i in the range k <= i < n - k good if the following conditions are satisfied:\nThe k elements that are just before the index i are in non-increasing order.\nThe k elements that are just after the index i are in non-decreasing order.\nReturn an array of all good indices sorted in increasing order.\n  Example 1:\nInput: nums = [2,1,1,1,3,4,1], k = 2\nOutput: [2,3]\nExplanation: There are two good indices in the array:\n- Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order.\n- Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order.\nNote that the index 4 is not good because [4,1] is not non-decreasing.\nExample 2:\nInput: nums = [2,1,1,2], k = 2\nOutput: []\nExplanation: There are no good indices in this array.\n  Constraints:\nn == nums.length\n3 <= n <= 105\n1 <= nums[i] <= 106\n1 <= k <= n / 2"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-good-paths/discuss/2623051/Python-3Hint-solution-Heap-%2B-Union-find",
      "python_solutions": "class Solution:\n    def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:\n        n = len(vals)\n        \n        g = defaultdict(list)\n        \n        # start from node with minimum val\n        for a, b in edges:\n            heappush(g[a], (vals[b], b))\n            heappush(g[b], (vals[a], a))\n\n        \n        loc = list(range(n))\n        \n        def find(x):\n            if loc[x] != x:\n                loc[x] = find(loc[x])\n            return loc[x]\n        \n        def union(x, y):\n            a, b = find(x), find(y)\n            if a != b:\n                loc[b] = a\n        \n        # node by val\n        v = defaultdict(list)\n        for i, val in enumerate(vals):\n            v[val].append(i)\n        \n        ans = n\n        \n        \n        for k in sorted(v):\n            for node in v[k]:\n                # build graph if neighboring node <= current node val\n                while g[node] and g[node][0][0] <= k:\n                    nei_v, nei = heappop(g[node])\n                    union(node, nei)\n            \n            # Count unioned groups\n            grp = Counter([find(x) for x in v[k]])\n            \n            # for each unioned group, select two nodes (order doesn't matter)\n            ans += sum(math.comb(x, 2) for x in grp.values())            \n        \n        return ans",
      "slug": "number-of-good-paths",
      "post_title": "[Python 3]Hint solution Heap + Union find",
      "user": "chestnut890123",
      "upvotes": 0,
      "views": 57,
      "problem_title": "number of good paths",
      "number": 2421,
      "acceptance": 0.3979999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 33085,
      "question": "There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges.\nYou are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node. You are also given a 2D integer array edges where edges[i] = [ai, bi] denotes that there exists an undirected edge connecting nodes ai and bi.\nA good path is a simple path that satisfies the following conditions:\nThe starting node and the ending node have the same value.\nAll nodes between the starting node and the ending node have values less than or equal to the starting node (i.e. the starting node's value should be the maximum value along the path).\nReturn the number of distinct good paths.\nNote that a path and its reverse are counted as the same path. For example, 0 -> 1 is considered to be the same as 1 -> 0. A single node is also considered as a valid path.\n  Example 1:\nInput: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]\nOutput: 6\nExplanation: There are 5 good paths consisting of a single node.\nThere is 1 additional good path: 1 -> 0 -> 2 -> 4.\n(The reverse path 4 -> 2 -> 0 -> 1 is treated as the same as 1 -> 0 -> 2 -> 4.)\nNote that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].\nExample 2:\nInput: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]\nOutput: 7\nExplanation: There are 5 good paths consisting of a single node.\nThere are 2 additional good paths: 0 -> 1 and 2 -> 3.\nExample 3:\nInput: vals = [1], edges = []\nOutput: 1\nExplanation: The tree consists of only one node, so there is one good path.\n  Constraints:\nn == vals.length\n1 <= n <= 3 * 104\n0 <= vals[i] <= 105\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nedges represents a valid tree."
    },
    {
      "post_href": "https://leetcode.com/problems/remove-letter-to-equalize-frequency/discuss/2660629/Counter-of-Counter",
      "python_solutions": "class Solution:\n    def equalFrequency(self, word: str) -> bool:\n        cnt = Counter(Counter(word).values())\n        if (len(cnt) == 1):\n            return list(cnt.keys())[0] == 1 or list(cnt.values())[0] == 1\n        if (len(cnt) == 2):\n            f1, f2 = min(cnt.keys()), max(cnt.keys())\n            return (f1 + 1 == f2 and cnt[f2] == 1) or (f1 == 1 and cnt[f1] == 1)\n        return False",
      "slug": "remove-letter-to-equalize-frequency",
      "post_title": "Counter of Counter",
      "user": "votrubac",
      "upvotes": 9,
      "views": 336,
      "problem_title": "remove letter to equalize frequency",
      "number": 2423,
      "acceptance": 0.193,
      "difficulty": "Easy",
      "__index_level_0__": 33088,
      "question": "You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal.\nReturn true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise.\nNote:\nThe frequency of a letter x is the number of times it occurs in the string.\nYou must remove exactly one letter and cannot choose to do nothing.\n  Example 1:\nInput: word = \"abcc\"\nOutput: true\nExplanation: Select index 3 and delete it: word becomes \"abc\" and each character has a frequency of 1.\nExample 2:\nInput: word = \"aazz\"\nOutput: false\nExplanation: We must delete a character, so either the frequency of \"a\" is 1 and the frequency of \"z\" is 2, or vice versa. It is impossible to make all present letters have equal frequency.\n  Constraints:\n2 <= word.length <= 100\nword consists of lowercase English letters only."
    },
    {
      "post_href": "https://leetcode.com/problems/bitwise-xor-of-all-pairings/discuss/2646655/JavaPython-3-Bit-manipulations-analysis.",
      "python_solutions": "class Solution:\n    def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int:\n        m, n = map(len, (nums1, nums2))\n        return (m % 2 * reduce(xor, nums2)) ^ (n % 2 * reduce(xor, nums1))",
      "slug": "bitwise-xor-of-all-pairings",
      "post_title": "[Java/Python 3] Bit manipulations analysis.",
      "user": "rock",
      "upvotes": 10,
      "views": 221,
      "problem_title": "bitwise xor of all pairings",
      "number": 2425,
      "acceptance": 0.586,
      "difficulty": "Medium",
      "__index_level_0__": 33118,
      "question": "You are given two 0-indexed arrays, nums1 and nums2, consisting of non-negative integers. There exists another array, nums3, which contains the bitwise XOR of all pairings of integers between nums1 and nums2 (every integer in nums1 is paired with every integer in nums2 exactly once).\nReturn the bitwise XOR of all integers in nums3.\n  Example 1:\nInput: nums1 = [2,1,3], nums2 = [10,2,5,0]\nOutput: 13\nExplanation:\nA possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].\nThe bitwise XOR of all these numbers is 13, so we return 13.\nExample 2:\nInput: nums1 = [1,2], nums2 = [3,4]\nOutput: 0\nExplanation:\nAll possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],\nand nums1[1] ^ nums2[1].\nThus, one possible nums3 array is [2,5,1,6].\n2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.\n  Constraints:\n1 <= nums1.length, nums2.length <= 105\n0 <= nums1[i], nums2[j] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-pairs-satisfying-inequality/discuss/2647569/Python-Binary-Search-oror-Time%3A-2698-ms-(50)-Space%3A-32.5-MB-(100)",
      "python_solutions": "class Solution:\n    def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:\n        n=len(nums1)\n        for i in range(n):\n            nums1[i]=nums1[i]-nums2[i]\n        ans=0\n        arr=[]\n        for i in range(n):\n            x=bisect_right(arr,nums1[i]+diff)\n            ans+=x\n            insort(arr,nums1[i])\n        return ans",
      "slug": "number-of-pairs-satisfying-inequality",
      "post_title": "Python Binary Search || Time: 2698 ms (50%), Space: 32.5 MB (100%)",
      "user": "koder_786",
      "upvotes": 0,
      "views": 15,
      "problem_title": "number of pairs satisfying inequality",
      "number": 2426,
      "acceptance": 0.422,
      "difficulty": "Hard",
      "__index_level_0__": 33137,
      "question": "You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:\n0 <= i < j <= n - 1 and\nnums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.\nReturn the number of pairs that satisfy the conditions.\n  Example 1:\nInput: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1\nOutput: 3\nExplanation:\nThere are 3 pairs that satisfy the conditions:\n1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.\n2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.\n3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.\nTherefore, we return 3.\nExample 2:\nInput: nums1 = [3,-1], nums2 = [-2,2], diff = -1\nOutput: 0\nExplanation:\nSince there does not exist any pair that satisfies the conditions, we return 0.\n  Constraints:\nn == nums1.length == nums2.length\n2 <= n <= 105\n-104 <= nums1[i], nums2[i] <= 104\n-104 <= diff <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-common-factors/discuss/2817862/Easy-Python-Solution",
      "python_solutions": "class Solution:\n    def commonFactors(self, a: int, b: int) -> int:\n        c=0\n        mi=min(a,b)\n        for i in range(1,mi+1):\n            if a%i==0 and b%i==0:\n                c+=1\n        return c",
      "slug": "number-of-common-factors",
      "post_title": "Easy Python Solution",
      "user": "Vistrit",
      "upvotes": 3,
      "views": 62,
      "problem_title": "number of common factors",
      "number": 2427,
      "acceptance": 0.8009999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 33141,
      "question": "Given two positive integers a and b, return the number of common factors of a and b.\nAn integer x is a common factor of a and b if x divides both a and b.\n  Example 1:\nInput: a = 12, b = 6\nOutput: 4\nExplanation: The common factors of 12 and 6 are 1, 2, 3, 6.\nExample 2:\nInput: a = 25, b = 30\nOutput: 2\nExplanation: The common factors of 25 and 30 are 1, 5.\n  Constraints:\n1 <= a, b <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-sum-of-an-hourglass/discuss/2677741/Simple-Python-Solution-oror-O(MxN)-beats-83.88",
      "python_solutions": "class Solution:\n    def maxSum(self, grid: List[List[int]]) -> int:\n        res=0\n        cur=0\n        \n        for i in range(len(grid)-2):\n            for j in range(1,len(grid[0])-1):\n               \n                cur=sum(grid[i][j-1:j+2]) +grid[i+1][j] + sum(grid[i+2][j-1:j+2])\n                res = max(res,cur)\n                                                     \n        return res",
      "slug": "maximum-sum-of-an-hourglass",
      "post_title": "Simple Python Solution || O(MxN) beats 83.88%",
      "user": "Graviel77",
      "upvotes": 1,
      "views": 42,
      "problem_title": "maximum sum of an hourglass",
      "number": 2428,
      "acceptance": 0.7390000000000001,
      "difficulty": "Medium",
      "__index_level_0__": 33178,
      "question": "You are given an m x n integer matrix grid.\nWe define an hourglass as a part of the matrix with the following form:\nReturn the maximum sum of the elements of an hourglass.\nNote that an hourglass cannot be rotated and must be entirely contained within the matrix.\n  Example 1:\nInput: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]\nOutput: 30\nExplanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30.\nExample 2:\nInput: grid = [[1,2,3],[4,5,6],[7,8,9]]\nOutput: 35\nExplanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35.\n  Constraints:\nm == grid.length\nn == grid[i].length\n3 <= m, n <= 150\n0 <= grid[i][j] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/minimize-xor/discuss/2649210/O(log(n))-using-set-and-clear-bit-(examples)",
      "python_solutions": "class Solution:\n    def minimizeXor(self, num1: int, num2: int) -> int:       \n        nbit1 = 0\n        while num2>0:\n            nbit1 = nbit1 + (num2&1)\n            num2 = num2 >> 1\n        # print(nbit1)\n        \n        chk = []\n        ans = 0\n        # print(bin(num1), bin(ans))\n        for i in range(31, -1, -1):\n            biti = (num1>>i)&1\n            if biti==1 and nbit1>0:\n                num1 = num1 & ~(1<0:\n            for i in range(0, 32, 1):\n                biti = (num1>>i)&1\n                if i not in chk and nbit1>0:\n                    num1 = num1 | (1< int:\n        n = len(s)\n        if len(set(s)) == 1:\n            return n\n        dp = [1] * n\n        for i in range(n - 2, -1, -1):\n            for l in range(1, (n - i) // 2 + 1):\n                if s[i : i + l] == s[i + l : i + 2 * l]:\n                    dp[i] = max(dp[i], 1 + dp[i + l])\n        return dp[0]",
      "slug": "maximum-deletions-on-a-string",
      "post_title": "[Python3] Dynamic Programming, Clean & Concise",
      "user": "xil899",
      "upvotes": 10,
      "views": 1000,
      "problem_title": "maximum deletions on a string",
      "number": 2430,
      "acceptance": 0.322,
      "difficulty": "Hard",
      "__index_level_0__": 33229,
      "question": "You are given a string s consisting of only lowercase English letters. In one operation, you can:\nDelete the entire string s, or\nDelete the first i letters of s if the first i letters of s are equal to the following i letters in s, for any i in the range 1 <= i <= s.length / 2.\nFor example, if s = \"ababc\", then in one operation, you could delete the first two letters of s to get \"abc\", since the first two letters of s and the following two letters of s are both equal to \"ab\".\nReturn the maximum number of operations needed to delete all of s.\n  Example 1:\nInput: s = \"abcabcdabc\"\nOutput: 2\nExplanation:\n- Delete the first 3 letters (\"abc\") since the next 3 letters are equal. Now, s = \"abcdabc\".\n- Delete all the letters.\nWe used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.\nNote that in the second operation we cannot delete \"abc\" again because the next occurrence of \"abc\" does not happen in the next 3 letters.\nExample 2:\nInput: s = \"aaabaab\"\nOutput: 4\nExplanation:\n- Delete the first letter (\"a\") since the next letter is equal. Now, s = \"aabaab\".\n- Delete the first 3 letters (\"aab\") since the next 3 letters are equal. Now, s = \"aab\".\n- Delete the first letter (\"a\") since the next letter is equal. Now, s = \"ab\".\n- Delete all the letters.\nWe used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.\nExample 3:\nInput: s = \"aaaaa\"\nOutput: 5\nExplanation: In each operation, we can delete the first letter of s.\n  Constraints:\n1 <= s.length <= 4000\ns consists only of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/the-employee-that-worked-on-the-longest-task/discuss/2693491/Python-Elegant-and-Short-or-No-indexes-or-99.32-faster",
      "python_solutions": "class Solution:\n    \"\"\"\n    Time:   O(n)\n    Memory: O(1)\n    \"\"\"\n\n    def hardestWorker(self, n: int, logs: List[List[int]]) -> int:\n        best_id = best_time = start = 0\n\n        for emp_id, end in logs:\n            time = end - start\n            if time > best_time or (time == best_time and best_id > emp_id):\n                best_id = emp_id\n                best_time = time\n            start = end\n\n        return best_id",
      "slug": "the-employee-that-worked-on-the-longest-task",
      "post_title": "Python Elegant & Short | No indexes | 99.32% faster",
      "user": "Kyrylo-Ktl",
      "upvotes": 4,
      "views": 47,
      "problem_title": "the employee that worked on the longest task",
      "number": 2432,
      "acceptance": 0.489,
      "difficulty": "Easy",
      "__index_level_0__": 33243,
      "question": "There are n employees, each with a unique id from 0 to n - 1.\nYou are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:\nidi is the id of the employee that worked on the ith task, and\nleaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are unique.\nNote that the ith task starts the moment right after the (i - 1)th task ends, and the 0th task starts at time 0.\nReturn the id of the employee that worked the task with the longest time. If there is a tie between two or more employees, return the smallest id among them.\n  Example 1:\nInput: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]]\nOutput: 1\nExplanation: \nTask 0 started at 0 and ended at 3 with 3 units of times.\nTask 1 started at 3 and ended at 5 with 2 units of times.\nTask 2 started at 5 and ended at 9 with 4 units of times.\nTask 3 started at 9 and ended at 15 with 6 units of times.\nThe task with the longest time is task 3 and the employee with id 1 is the one that worked on it, so we return 1.\nExample 2:\nInput: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]]\nOutput: 3\nExplanation: \nTask 0 started at 0 and ended at 1 with 1 unit of times.\nTask 1 started at 1 and ended at 7 with 6 units of times.\nTask 2 started at 7 and ended at 12 with 5 units of times.\nTask 3 started at 12 and ended at 17 with 5 units of times.\nThe tasks with the longest time is task 1. The employee that worked on it is 3, so we return 3.\nExample 3:\nInput: n = 2, logs = [[0,10],[1,20]]\nOutput: 0\nExplanation: \nTask 0 started at 0 and ended at 10 with 10 units of times.\nTask 1 started at 10 and ended at 20 with 10 units of times.\nThe tasks with the longest time are tasks 0 and 1. The employees that worked on them are 0 and 1, so we return the smallest id 0.\n  Constraints:\n2 <= n <= 500\n1 <= logs.length <= 500\nlogs[i].length == 2\n0 <= idi <= n - 1\n1 <= leaveTimei <= 500\nidi != idi+1\nleaveTimei are sorted in a strictly increasing order."
    },
    {
      "post_href": "https://leetcode.com/problems/find-the-original-array-of-prefix-xor/discuss/2684467/Python-3-Easy-O(N)-Time-Greedy-Solution-Explained",
      "python_solutions": "class Solution:\n    def findArray(self, pref: List[int]) -> List[int]:\n        ans = [0 for i in range(len(pref))]\n        ans[0] = pref[0]\n        for i in range(1, len(pref)):\n            ans[i] = pref[i-1]^pref[i]\n        return ans",
      "slug": "find-the-original-array-of-prefix-xor",
      "post_title": "[Python 3] Easy O(N) Time Greedy Solution Explained",
      "user": "user2667O",
      "upvotes": 1,
      "views": 29,
      "problem_title": "find the original array of prefix xor",
      "number": 2433,
      "acceptance": 0.857,
      "difficulty": "Medium",
      "__index_level_0__": 33265,
      "question": "You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:\npref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].\nNote that ^ denotes the bitwise-xor operation.\nIt can be proven that the answer is unique.\n  Example 1:\nInput: pref = [5,2,0,3,1]\nOutput: [5,7,2,3,2]\nExplanation: From the array [5,7,2,3,2] we have the following:\n- pref[0] = 5.\n- pref[1] = 5 ^ 7 = 2.\n- pref[2] = 5 ^ 7 ^ 2 = 0.\n- pref[3] = 5 ^ 7 ^ 2 ^ 3 = 3.\n- pref[4] = 5 ^ 7 ^ 2 ^ 3 ^ 2 = 1.\nExample 2:\nInput: pref = [13]\nOutput: [13]\nExplanation: We have pref[0] = arr[0] = 13.\n  Constraints:\n1 <= pref.length <= 105\n0 <= pref[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/using-a-robot-to-print-the-lexicographically-smallest-string/discuss/2678810/Counter",
      "python_solutions": "class Solution:\n    def robotWithString(self, s: str) -> str:\n        cnt, lo, p, t = Counter(s), 'a', [], []\n        for ch in s:\n            t += ch\n            cnt[ch] -= 1\n            while lo < 'z' and cnt[lo] == 0:\n                lo = chr(ord(lo) + 1)\n            while t and t[-1] <= lo:\n                p += t.pop()\n        return \"\".join(p)",
      "slug": "using-a-robot-to-print-the-lexicographically-smallest-string",
      "post_title": "Counter",
      "user": "votrubac",
      "upvotes": 78,
      "views": 3600,
      "problem_title": "using a robot to print the lexicographically smallest string",
      "number": 2434,
      "acceptance": 0.381,
      "difficulty": "Medium",
      "__index_level_0__": 33297,
      "question": "You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty:\nRemove the first character of a string s and give it to the robot. The robot will append this character to the string t.\nRemove the last character of a string t and give it to the robot. The robot will write this character on paper.\nReturn the lexicographically smallest string that can be written on the paper.\n  Example 1:\nInput: s = \"zza\"\nOutput: \"azz\"\nExplanation: Let p denote the written string.\nInitially p=\"\", s=\"zza\", t=\"\".\nPerform first operation three times p=\"\", s=\"\", t=\"zza\".\nPerform second operation three times p=\"azz\", s=\"\", t=\"\".\nExample 2:\nInput: s = \"bac\"\nOutput: \"abc\"\nExplanation: Let p denote the written string.\nPerform first operation twice p=\"\", s=\"c\", t=\"ba\". \nPerform second operation twice p=\"ab\", s=\"c\", t=\"\". \nPerform first operation p=\"ab\", s=\"\", t=\"c\". \nPerform second operation p=\"abc\", s=\"\", t=\"\".\nExample 3:\nInput: s = \"bdda\"\nOutput: \"addb\"\nExplanation: Let p denote the written string.\nInitially p=\"\", s=\"bdda\", t=\"\".\nPerform first operation four times p=\"\", s=\"\", t=\"bdda\".\nPerform second operation four times p=\"addb\", s=\"\", t=\"\".\n  Constraints:\n1 <= s.length <= 105\ns consists of only English lowercase letters."
    },
    {
      "post_href": "https://leetcode.com/problems/paths-in-matrix-whose-sum-is-divisible-by-k/discuss/2702890/Python-or-3d-dynamic-programming-approach-or-O(m*n*k)",
      "python_solutions": "class Solution:\n    def numberOfPaths(self, grid: List[List[int]], k: int) -> int:\n        dp = [[[0 for i in range(k)] for _ in range(len(grid[0]))] for _ in range(len(grid))]\n        rem = grid[0][0] % k\n        dp[0][0][rem] = 1\n        for i in range(1, len(grid[0])):\n            dp[0][i][(rem + grid[0][i]) % k] = 1\n            rem = (rem + grid[0][i]) % k\n        rem = grid[0][0] % k\n        for j in range(1, len(grid)):\n            dp[j][0][(rem + grid[j][0]) % k] = 1\n            rem = (rem + grid[j][0]) % k\n        for i in range(1, len(grid)):\n            for j in range(1, len(grid[0])):\n                for rem in range(k):\n                    dp[i][j][(rem + grid[i][j]) % k] = dp[i - 1][j][rem] + dp[i][j - 1][rem]\n        return dp[-1][-1][0] % (10**9 + 7)",
      "slug": "paths-in-matrix-whose-sum-is-divisible-by-k",
      "post_title": "Python | 3d dynamic programming approach | O(m*n*k)",
      "user": "LordVader1",
      "upvotes": 1,
      "views": 16,
      "problem_title": "paths in matrix whose sum is divisible by k",
      "number": 2435,
      "acceptance": 0.41,
      "difficulty": "Hard",
      "__index_level_0__": 33315,
      "question": "You are given a 0-indexed m x n integer matrix grid and an integer k. You are currently at position (0, 0) and you want to reach position (m - 1, n - 1) moving only down or right.\nReturn the number of paths where the sum of the elements on the path is divisible by k. Since the answer may be very large, return it modulo 109 + 7.\n  Example 1:\nInput: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3\nOutput: 2\nExplanation: There are two paths where the sum of the elements on the path is divisible by k.\nThe first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.\nThe second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.\nExample 2:\nInput: grid = [[0,0]], k = 5\nOutput: 1\nExplanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.\nExample 3:\nInput: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1\nOutput: 10\nExplanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.\n  Constraints:\nm == grid.length\nn == grid[i].length\n1 <= m, n <= 5 * 104\n1 <= m * n <= 5 * 104\n0 <= grid[i][j] <= 100\n1 <= k <= 50"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-valid-clock-times/discuss/2706741/Structural-pattern-matching",
      "python_solutions": "class Solution:\n    def countTime(self, t: str) -> int:\n        mm = (6 if t[3] == '?' else 1) * (10 if t[4] == '?' else 1)\n        match [t[0], t[1]]:\n            case ('?', '?'):\n                return mm * 24\n            case ('?', ('0' | '1' | '2' | '3')):\n                return mm * 3\n            case ('?', _):\n                return mm * 2\n            case (('0' | '1'), '?'):\n                return mm * 10\n            case (_, '?'):\n                return mm * 4\n        return mm",
      "slug": "number-of-valid-clock-times",
      "post_title": "Structural pattern matching",
      "user": "votrubac",
      "upvotes": 24,
      "views": 806,
      "problem_title": "number of valid clock times",
      "number": 2437,
      "acceptance": 0.42,
      "difficulty": "Easy",
      "__index_level_0__": 33331,
      "question": "You are given a string of length 5 called time, representing the current time on a digital clock in the format \"hh:mm\". The earliest possible time is \"00:00\" and the latest possible time is \"23:59\".\nIn the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.\nReturn an integer answer, the number of valid clock times that can be created by replacing every ? with a digit from 0 to 9.\n  Example 1:\nInput: time = \"?5:00\"\nOutput: 2\nExplanation: We can replace the ? with either a 0 or 1, producing \"05:00\" or \"15:00\". Note that we cannot replace it with a 2, since the time \"25:00\" is invalid. In total, we have two choices.\nExample 2:\nInput: time = \"0?:0?\"\nOutput: 100\nExplanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.\nExample 3:\nInput: time = \"??:??\"\nOutput: 1440\nExplanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.\n  Constraints:\ntime is a valid string of length 5 in the format \"hh:mm\".\n\"00\" <= hh <= \"23\"\n\"00\" <= mm <= \"59\"\nSome of the digits might be replaced with '?' and need to be replaced with digits from 0 to 9."
    },
    {
      "post_href": "https://leetcode.com/problems/range-product-queries-of-powers/discuss/2706690/Python-or-Prefix-Product",
      "python_solutions": "class Solution:\n    def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n        MOD = (10**9)+7\n        binary = bin(n)[2:]\n        powers = []\n        result = []\n        for index, val in enumerate(binary[::-1]):\n            if val == \"1\":\n                powers.append(2**index)\n                \n        for index in range(1, len(powers)):\n            powers[index] = powers[index] * powers[index - 1]    \n        \n        for l,r in queries:\n            if l == 0:\n                result.append(powers[r]%MOD)\n            else:\n                result.append((powers[r]//powers[l-1])%MOD)\n                \n        return result",
      "slug": "range-product-queries-of-powers",
      "post_title": "Python | Prefix Product",
      "user": "Dhanush_krish",
      "upvotes": 8,
      "views": 320,
      "problem_title": "range product queries of powers",
      "number": 2438,
      "acceptance": 0.384,
      "difficulty": "Medium",
      "__index_level_0__": 33359,
      "question": "Given a positive integer n, there exists a 0-indexed array called powers, composed of the minimum number of powers of 2 that sum to n. The array is sorted in non-decreasing order, and there is only one way to form the array.\nYou are also given a 0-indexed 2D integer array queries, where queries[i] = [lefti, righti]. Each queries[i] represents a query where you have to find the product of all powers[j] with lefti <= j <= righti.\nReturn an array answers, equal in length to queries, where answers[i] is the answer to the ith query. Since the answer to the ith query may be too large, each answers[i] should be returned modulo 109 + 7.\n  Example 1:\nInput: n = 15, queries = [[0,1],[2,2],[0,3]]\nOutput: [2,4,64]\nExplanation:\nFor n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.\nAnswer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.\nAnswer to 2nd query: powers[2] = 4.\nAnswer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64.\nEach answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.\nExample 2:\nInput: n = 2, queries = [[0,0]]\nOutput: [2]\nExplanation:\nFor n = 2, powers = [2].\nThe answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.\n  Constraints:\n1 <= n <= 109\n1 <= queries.length <= 105\n0 <= starti <= endi < powers.length"
    },
    {
      "post_href": "https://leetcode.com/problems/minimize-maximum-of-array/discuss/2706472/Average",
      "python_solutions": "class Solution:\n    def minimizeArrayValue(self, nums: List[int]) -> int:\n        return max(ceil(n / (i + 1)) for i, n in enumerate(accumulate(nums)))",
      "slug": "minimize-maximum-of-array",
      "post_title": "Average",
      "user": "votrubac",
      "upvotes": 45,
      "views": 2800,
      "problem_title": "minimize maximum of array",
      "number": 2439,
      "acceptance": 0.331,
      "difficulty": "Medium",
      "__index_level_0__": 33375,
      "question": "You are given a 0-indexed array nums comprising of n non-negative integers.\nIn one operation, you must:\nChoose an integer i such that 1 <= i < n and nums[i] > 0.\nDecrease nums[i] by 1.\nIncrease nums[i - 1] by 1.\nReturn the minimum possible value of the maximum integer of nums after performing any number of operations.\n  Example 1:\nInput: nums = [3,7,1,6]\nOutput: 5\nExplanation:\nOne set of optimal operations is as follows:\n1. Choose i = 1, and nums becomes [4,6,1,6].\n2. Choose i = 3, and nums becomes [4,6,2,5].\n3. Choose i = 1, and nums becomes [5,5,2,5].\nThe maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.\nTherefore, we return 5.\nExample 2:\nInput: nums = [10,1]\nOutput: 10\nExplanation:\nIt is optimal to leave nums as is, and since 10 is the maximum value, we return 10.\n  Constraints:\nn == nums.length\n2 <= n <= 105\n0 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/create-components-with-same-value/discuss/2707304/Python3-post-order-dfs",
      "python_solutions": "class Solution:\n    def componentValue(self, nums: List[int], edges: List[List[int]]) -> int:\n        tree = [[] for _ in nums]\n        for u, v in edges: \n            tree[u].append(v)\n            tree[v].append(u)\n        \n        def fn(u, p):\n            \"\"\"Post-order dfs.\"\"\"\n            ans = nums[u]\n            for v in tree[u]: \n                if v != p: ans += fn(v, u)\n            return 0 if ans == cand else ans\n        \n        total = sum(nums)\n        for cand in range(1, total//2+1): \n            if total % cand == 0 and fn(0, -1) == 0: return total//cand-1\n        return 0",
      "slug": "create-components-with-same-value",
      "post_title": "[Python3] post-order dfs",
      "user": "ye15",
      "upvotes": 11,
      "views": 264,
      "problem_title": "create components with same value",
      "number": 2440,
      "acceptance": 0.5429999999999999,
      "difficulty": "Hard",
      "__index_level_0__": 33393,
      "question": "There is an undirected tree with n nodes labeled from 0 to n - 1.\nYou are given a 0-indexed integer array nums of length n where nums[i] represents the value of the ith node. You are also given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\nYou are allowed to delete some edges, splitting the tree into multiple connected components. Let the value of a component be the sum of all nums[i] for which node i is in the component.\nReturn the maximum number of edges you can delete, such that every connected component in the tree has the same value.\n  Example 1:\nInput: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]] \nOutput: 2 \nExplanation: The above figure shows how we can delete the edges [0,1] and [3,4]. The created components are nodes [0], [1,2,3] and [4]. The sum of the values in each component equals 6. It can be proven that no better deletion exists, so the answer is 2.\nExample 2:\nInput: nums = [2], edges = []\nOutput: 0\nExplanation: There are no edges to be deleted.\n  Constraints:\n1 <= n <= 2 * 104\nnums.length == n\n1 <= nums[i] <= 50\nedges.length == n - 1\nedges[i].length == 2\n0 <= edges[i][0], edges[i][1] <= n - 1\nedges represents a valid tree."
    },
    {
      "post_href": "https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/discuss/2774238/Easy-Python-Solution",
      "python_solutions": "class Solution:\n    def findMaxK(self, nums: List[int]) -> int:\n        nums.sort()\n        for i in nums[::-1]:\n            if -i in nums:\n                return i\n        return -1",
      "slug": "largest-positive-integer-that-exists-with-its-negative",
      "post_title": "Easy Python Solution",
      "user": "Vistrit",
      "upvotes": 3,
      "views": 64,
      "problem_title": "largest positive integer that exists with its negative",
      "number": 2441,
      "acceptance": 0.6779999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 33395,
      "question": "Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array.\nReturn the positive integer k. If there is no such integer, return -1.\n  Example 1:\nInput: nums = [-1,2,-3,3]\nOutput: 3\nExplanation: 3 is the only valid k we can find in the array.\nExample 2:\nInput: nums = [-1,10,6,7,-7,1]\nOutput: 7\nExplanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.\nExample 3:\nInput: nums = [-10,8,6,7,-2,-3]\nOutput: -1\nExplanation: There is no a single valid k, we return -1.\n  Constraints:\n1 <= nums.length <= 1000\n-1000 <= nums[i] <= 1000\nnums[i] != 0"
    },
    {
      "post_href": "https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations/discuss/2708055/One-Liner-or-Explained",
      "python_solutions": "class Solution:\n    def countDistinctIntegers(self, nums: List[int]) -> int:\n        return len(set([int(str(i)[::-1]) for i in nums] + nums))",
      "slug": "count-number-of-distinct-integers-after-reverse-operations",
      "post_title": "One Liner | Explained",
      "user": "lukewu28",
      "upvotes": 5,
      "views": 427,
      "problem_title": "count number of distinct integers after reverse operations",
      "number": 2442,
      "acceptance": 0.7879999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 33429,
      "question": "You are given an array nums consisting of positive integers.\nYou have to take each integer in the array, reverse its digits, and add it to the end of the array. You should apply this operation to the original integers in nums.\nReturn the number of distinct integers in the final array.\n  Example 1:\nInput: nums = [1,13,10,12,31]\nOutput: 6\nExplanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13].\nThe reversed integers that were added to the end of the array are underlined. Note that for the integer 10, after reversing it, it becomes 01 which is just 1.\nThe number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).\nExample 2:\nInput: nums = [2,2,2]\nOutput: 1\nExplanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2].\nThe number of distinct integers in this array is 1 (The number 2).\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/sum-of-number-and-its-reverse/discuss/2708439/Python3-O(-digits)-solution-beats-100-47ms",
      "python_solutions": "class Solution:\n    def sumOfNumberAndReverse(self, num: int) -> bool:\n        digits = []\n        while num > 0:\n            digits.append(num % 10)\n            num = num // 10\n\n        digits.reverse()\n        hi, lo = 0, len(digits) - 1\n        while hi <= lo:\n            if hi == lo:\n                if digits[hi] % 2 == 0:\n                    break\n                else:\n                    return False\n            if digits[hi] == digits[lo]:\n                hi += 1\n                lo -= 1\n            elif digits[hi] == 1 and digits[hi] != digits[lo]:\n                digits[hi] -= 1\n                digits[hi+1] += 10\n                hi += 1\n                if lo != hi:\n                    digits[lo] += 10\n                    digits[lo-1] -= 1\n                    cur = lo - 1\n                    while digits[cur] < 0:\n                        digits[cur] = 0\n                        digits[cur-1] -= 1\n                        cur -= 1\n                \n            elif digits[hi]-1 == digits[lo] and hi + 1 < lo:\n                    digits[hi]-= 1\n                    digits[hi+1] += 10\n                    hi += 1\n                    lo -= 1\n                # else:\n                #     return False\n            elif digits[hi] - 1 == digits[lo] + 10 and hi + 1 < lo:\n                digits[hi] -= 1\n                digits[hi+1] += 10\n                digits[lo-1] -= 1\n                cur = lo - 1\n                while digits[cur] < 0:\n                    digits[cur] = 0\n                    digits[cur-1] -= 1\n                    cur -= 1     \n                digits[lo] += 10\n            elif hi-1>=0 and lo+1<=len(digits)-1 and digits[hi-1] == 1 and digits[lo+1] == 1:\n                digits[hi-1] -= 1\n                digits[hi] += 10\n                digits[lo+1] += 10\n                digits[lo] -= 1\n                cur = lo\n                while digits[cur] < 0:\n                    digits[cur] = 0\n                    digits[cur-1] -= 1\n                    cur -= 1\n                lo += 1\n            else:\n                return False\n        return True",
      "slug": "sum-of-number-and-its-reverse",
      "post_title": "[Python3] O(# digits) solution beats 100% 47ms",
      "user": "jfang2021",
      "upvotes": 2,
      "views": 326,
      "problem_title": "sum of number and its reverse",
      "number": 2443,
      "acceptance": 0.4529999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 33466,
      "question": "Given a non-negative integer num, return true if num can be expressed as the sum of any non-negative integer and its reverse, or false otherwise.\n  Example 1:\nInput: num = 443\nOutput: true\nExplanation: 172 + 271 = 443 so we return true.\nExample 2:\nInput: num = 63\nOutput: false\nExplanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.\nExample 3:\nInput: num = 181\nOutput: true\nExplanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.\n  Constraints:\n0 <= num <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/count-subarrays-with-fixed-bounds/discuss/2708034/Python3-Sliding-Window-O(N)-with-Explanations",
      "python_solutions": "class Solution:\n    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:\n        if minK > maxK: return 0\n        \n        def count(l, r):\n            if l + 1 == r: return 0\n            dic = Counter([nums[l]])\n            ans, j = 0, l + 1\n            for i in range(l + 1, r):\n                dic[nums[i - 1]] -= 1\n                while not dic[minK] * dic[maxK] and j < r:\n                    dic[nums[j]] += 1\n                    j += 1\n                if dic[minK] * dic[maxK]: ans += r - j + 1\n                else: break\n            return ans\n        \n        arr = [-1] + [i for i, num in enumerate(nums) if num < minK or num > maxK] + [len(nums)]\n        return sum(count(arr[i - 1], arr[i]) for i in range(1, len(arr)))",
      "slug": "count-subarrays-with-fixed-bounds",
      "post_title": "[Python3] Sliding Window O(N) with Explanations",
      "user": "xil899",
      "upvotes": 1,
      "views": 97,
      "problem_title": "count subarrays with fixed bounds",
      "number": 2444,
      "acceptance": 0.432,
      "difficulty": "Hard",
      "__index_level_0__": 33498,
      "question": "You are given an integer array nums and two integers minK and maxK.\nA fixed-bound subarray of nums is a subarray that satisfies the following conditions:\nThe minimum value in the subarray is equal to minK.\nThe maximum value in the subarray is equal to maxK.\nReturn the number of fixed-bound subarrays.\nA subarray is a contiguous part of an array.\n  Example 1:\nInput: nums = [1,3,5,2,7,5], minK = 1, maxK = 5\nOutput: 2\nExplanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].\nExample 2:\nInput: nums = [1,1,1,1], minK = 1, maxK = 1\nOutput: 10\nExplanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.\n  Constraints:\n2 <= nums.length <= 105\n1 <= nums[i], minK, maxK <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/determine-if-two-events-have-conflict/discuss/2744018/Python-Elegant-and-Short",
      "python_solutions": "class Solution:\n    \"\"\"\n    Time:   O(1)\n    Memory: O(1)\n    \"\"\"\n\n    def haveConflict(self, a: List[str], b: List[str]) -> bool:\n        a_start, a_end = a\n        b_start, b_end = b\n        return b_start <= a_start <= b_end or \\\n               b_start <= a_end <= b_end or \\\n               a_start <= b_start <= a_end or \\\n               a_start <= b_end <= a_end",
      "slug": "determine-if-two-events-have-conflict",
      "post_title": "Python Elegant & Short",
      "user": "Kyrylo-Ktl",
      "upvotes": 3,
      "views": 79,
      "problem_title": "determine if two events have conflict",
      "number": 2446,
      "acceptance": 0.494,
      "difficulty": "Easy",
      "__index_level_0__": 33507,
      "question": "You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where:\nevent1 = [startTime1, endTime1] and\nevent2 = [startTime2, endTime2].\nEvent times are valid 24 hours format in the form of HH:MM.\nA conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events).\nReturn true if there is a conflict between two events. Otherwise, return false.\n  Example 1:\nInput: event1 = [\"01:15\",\"02:00\"], event2 = [\"02:00\",\"03:00\"]\nOutput: true\nExplanation: The two events intersect at time 2:00.\nExample 2:\nInput: event1 = [\"01:00\",\"02:00\"], event2 = [\"01:20\",\"03:00\"]\nOutput: true\nExplanation: The two events intersect starting from 01:20 to 02:00.\nExample 3:\nInput: event1 = [\"10:00\",\"11:00\"], event2 = [\"14:00\",\"15:00\"]\nOutput: false\nExplanation: The two events do not intersect.\n  Constraints:\nevent1.length == event2.length == 2\nevent1[i].length == event2[i].length == 5\nstartTime1 <= endTime1\nstartTime2 <= endTime2\nAll the event times follow the HH:MM format."
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/discuss/2734224/Python3-Brute-Force-%2B-Early-Stopping-Clean-and-Concise",
      "python_solutions": "class Solution:\n    def subarrayGCD(self, nums: List[int], k: int) -> int:\n        n = len(nums)\n        ans = 0\n        for i in range(n):\n            temp = nums[i]\n            for j in range(i, n):\n                temp = math.gcd(temp, nums[j])\n                if temp == k:\n                    ans += 1\n                elif temp < k:\n                    break\n        return ans",
      "slug": "number-of-subarrays-with-gcd-equal-to-k",
      "post_title": "[Python3] Brute Force + Early Stopping, Clean & Concise",
      "user": "xil899",
      "upvotes": 4,
      "views": 423,
      "problem_title": "number of subarrays with gcd equal to k",
      "number": 2447,
      "acceptance": 0.482,
      "difficulty": "Medium",
      "__index_level_0__": 33524,
      "question": "Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k.\nA subarray is a contiguous non-empty sequence of elements within an array.\nThe greatest common divisor of an array is the largest integer that evenly divides all the array elements.\n  Example 1:\nInput: nums = [9,3,1,2,6,3], k = 3\nOutput: 4\nExplanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:\n- [9,3,1,2,6,3]\n- [9,3,1,2,6,3]\n- [9,3,1,2,6,3]\n- [9,3,1,2,6,3]\nExample 2:\nInput: nums = [4], k = 7\nOutput: 0\nExplanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.\n  Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i], k <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-cost-to-make-array-equal/discuss/2734183/Python3-Weighted-Median-O(NlogN)-with-Explanations",
      "python_solutions": "class Solution:\n    def minCost(self, nums: List[int], cost: List[int]) -> int:\n        arr = sorted(zip(nums, cost))\n        total, cnt = sum(cost), 0\n        for num, c in arr:\n            cnt += c\n            if cnt > total // 2:\n                target = num\n                break\n        return sum(c * abs(num - target) for num, c in arr)",
      "slug": "minimum-cost-to-make-array-equal",
      "post_title": "[Python3] Weighted Median O(NlogN) with Explanations",
      "user": "xil899",
      "upvotes": 109,
      "views": 2300,
      "problem_title": "minimum cost to make array equal",
      "number": 2448,
      "acceptance": 0.346,
      "difficulty": "Hard",
      "__index_level_0__": 33535,
      "question": "You are given two 0-indexed arrays nums and cost consisting each of n positive integers.\nYou can do the following operation any number of times:\nIncrease or decrease any element of the array nums by 1.\nThe cost of doing one operation on the ith element is cost[i].\nReturn the minimum total cost such that all the elements of the array nums become equal.\n  Example 1:\nInput: nums = [1,3,5,2], cost = [2,3,1,14]\nOutput: 8\nExplanation: We can make all the elements equal to 2 in the following way:\n- Increase the 0th element one time. The cost is 2.\n- Decrease the 1st element one time. The cost is 3.\n- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.\nThe total cost is 2 + 3 + 3 = 8.\nIt can be shown that we cannot make the array equal with a smaller cost.\nExample 2:\nInput: nums = [2,2,2,2,2], cost = [4,2,8,1,3]\nOutput: 0\nExplanation: All the elements are already equal, so no operations are needed.\n  Constraints:\nn == nums.length == cost.length\n1 <= n <= 105\n1 <= nums[i], cost[i] <= 106\nTest cases are generated in a way that the output doesn't exceed 253-1"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-make-arrays-similar/discuss/2734139/Python-or-Simple-OddEven-Sorting-O(nlogn)-or-Walmart-OA-India-or-Simple-Explanation",
      "python_solutions": "class Solution:\n    def makeSimilar(self, A: List[int], B: List[int]) -> int:\n        if sum(A)!=sum(B): return 0\n        # The first intuition is that only odd numbers can be chaged to odd numbers and even to even hence separate them\n        # Now minimum steps to making the target to highest number in B is by converting max of A to max of B similarily\n        # every number in A can be paired with a number in B by index hence sorting\n        # now we need only the number of positives or number of negatives.\n        oddA,evenA=[i for i in A if i%2],[i for i in A if i%2==0]\n        oddB,evenB=[i for i in B if i%2],[i for i in B if i%2==0]        \n        oddA.sort(),evenA.sort()\n        oddB.sort(),evenB.sort()\n        res=0\n        for i,j in zip(oddA,oddB):\n            if i>=j: res+=i-j\n        \n        for i,j in zip(evenA,evenB):\n            if i>=j: res+=i-j\n        \n        return res//2",
      "slug": "minimum-number-of-operations-to-make-arrays-similar",
      "post_title": "Python | Simple Odd/Even Sorting O(nlogn) | Walmart OA India | Simple Explanation",
      "user": "tarushfx",
      "upvotes": 3,
      "views": 245,
      "problem_title": "minimum number of operations to make arrays similar",
      "number": 2449,
      "acceptance": 0.649,
      "difficulty": "Hard",
      "__index_level_0__": 33552,
      "question": "You are given two positive integer arrays nums and target, of the same length.\nIn one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:\nset nums[i] = nums[i] + 2 and\nset nums[j] = nums[j] - 2.\nTwo arrays are considered to be similar if the frequency of each element is the same.\nReturn the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.\n  Example 1:\nInput: nums = [8,12,6], target = [2,14,10]\nOutput: 2\nExplanation: It is possible to make nums similar to target in two operations:\n- Choose i = 0 and j = 2, nums = [10,12,4].\n- Choose i = 1 and j = 2, nums = [10,14,2].\nIt can be shown that 2 is the minimum number of operations needed.\nExample 2:\nInput: nums = [1,2,5], target = [4,1,3]\nOutput: 1\nExplanation: We can make nums similar to target in one operation:\n- Choose i = 1 and j = 2, nums = [1,4,3].\nExample 3:\nInput: nums = [1,1,1,1,1], target = [1,1,1,1,1]\nOutput: 0\nExplanation: The array nums is already similiar to target.\n  Constraints:\nn == nums.length == target.length\n1 <= n <= 105\n1 <= nums[i], target[i] <= 106\nIt is possible to make nums similar to target."
    },
    {
      "post_href": "https://leetcode.com/problems/odd-string-difference/discuss/2774188/Easy-to-understand-python-solution",
      "python_solutions": "class Solution:\n    def oddString(self, words: List[str]) -> str:\n        k=len(words[0])\n        arr=[]\n        for i in words:\n            l=[]\n            for j in range(1,k):\n                diff=ord(i[j])-ord(i[j-1])\n                l.append(diff)\n            arr.append(l)\n        for i in range(len(arr)):\n            if arr.count(arr[i])==1:\n                return words[i]",
      "slug": "odd-string-difference",
      "post_title": "Easy to understand python solution",
      "user": "Vistrit",
      "upvotes": 2,
      "views": 87,
      "problem_title": "odd string difference",
      "number": 2451,
      "acceptance": 0.595,
      "difficulty": "Easy",
      "__index_level_0__": 33559,
      "question": "You are given an array of equal-length strings words. Assume that the length of each string is n.\nEach string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.\nFor example, for the string \"acb\", the difference integer array is [2 - 0, 1 - 2] = [2, -1].\nAll the strings in words have the same difference integer array, except one. You should find that string.\nReturn the string in words that has different difference integer array.\n  Example 1:\nInput: words = [\"adc\",\"wzy\",\"abc\"]\nOutput: \"abc\"\nExplanation: \n- The difference integer array of \"adc\" is [3 - 0, 2 - 3] = [3, -1].\n- The difference integer array of \"wzy\" is [25 - 22, 24 - 25]= [3, -1].\n- The difference integer array of \"abc\" is [1 - 0, 2 - 1] = [1, 1]. \nThe odd array out is [1, 1], so we return the corresponding string, \"abc\".\nExample 2:\nInput: words = [\"aaa\",\"bob\",\"ccc\",\"ddd\"]\nOutput: \"bob\"\nExplanation: All the integer arrays are [0, 0] except for \"bob\", which corresponds to [13, -13].\n  Constraints:\n3 <= words.length <= 100\nn == words[i].length\n2 <= n <= 20\nwords[i] consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/words-within-two-edits-of-dictionary/discuss/2757378/Python-Simple-HashSet-solution-O((N%2BM)-*-L3)",
      "python_solutions": "class Solution:\n    def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:\n        # T: ((N + M) * L^3), S: O(M * L^3)\n        N, M, L = len(queries), len(dictionary), len(queries[0])\n        validWords = set()\n        \n        for word in dictionary:\n            for w in self.wordModifications(word):\n                validWords.add(w)\n        \n        ans = []\n        for word in queries:\n            for w in self.wordModifications(word):\n                if w in validWords:\n                    ans.append(word)\n                    break\n\n        return ans\n    \n    def wordModifications(self, word):\n        # T: O(L^3)\n        L = len(word)\n        for i in range(L):\n            yield word[:i] + \"*\" + word[i+1:]\n\n        for i, j in itertools.combinations(range(L), 2):\n            yield word[:i] + \"*\" + word[i+1:j] + \"*\" + word[j+1:]",
      "slug": "words-within-two-edits-of-dictionary",
      "post_title": "[Python] Simple HashSet solution O((N+M) * L^3)",
      "user": "rcomesan",
      "upvotes": 2,
      "views": 45,
      "problem_title": "words within two edits of dictionary",
      "number": 2452,
      "acceptance": 0.603,
      "difficulty": "Medium",
      "__index_level_0__": 33583,
      "question": "You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.\nIn one edit you can take a word from queries, and change any letter in it to any other letter. Find all words from queries that, after a maximum of two edits, equal some word from dictionary.\nReturn a list of all words from queries, that match with some word from dictionary after a maximum of two edits. Return the words in the same order they appear in queries.\n  Example 1:\nInput: queries = [\"word\",\"note\",\"ants\",\"wood\"], dictionary = [\"wood\",\"joke\",\"moat\"]\nOutput: [\"word\",\"note\",\"wood\"]\nExplanation:\n- Changing the 'r' in \"word\" to 'o' allows it to equal the dictionary word \"wood\".\n- Changing the 'n' to 'j' and the 't' to 'k' in \"note\" changes it to \"joke\".\n- It would take more than 2 edits for \"ants\" to equal a dictionary word.\n- \"wood\" can remain unchanged (0 edits) and match the corresponding dictionary word.\nThus, we return [\"word\",\"note\",\"wood\"].\nExample 2:\nInput: queries = [\"yes\"], dictionary = [\"not\"]\nOutput: []\nExplanation:\nApplying any two edits to \"yes\" cannot make it equal to \"not\". Thus, we return an empty array.\n  Constraints:\n1 <= queries.length, dictionary.length <= 100\nn == queries[i].length == dictionary[j].length\n1 <= n <= 100\nAll queries[i] and dictionary[j] are composed of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/destroy-sequential-targets/discuss/2756374/Python-or-Greedy-or-Group-or-Example",
      "python_solutions": "class Solution:\n    def destroyTargets(self, nums: List[int], space: int) -> int:\n\t\t# example:  nums = [3,7,8,1,1,5], space = 2\n        groups = defaultdict(list)\n        for num in nums:\n            groups[num % space].append(num)\n        \n        # print(groups) # defaultdict(, {1: [3, 7, 1, 1, 5], 0: [8]}) groups is [3, 7, 1, 1, 5] and [8] \n        \"\"\" min of [3, 7, 1, 1, 5] can destroy all others (greedy approach) => 1 can destory 1,3,5,7 ... \"\"\"\n        performance = defaultdict(list)\n        for group in groups.values():\n            performance[len(group)].append(min(group))\n        \n        # print(performance) # defaultdict(, {5: [1], 1: [8]})\n\t\t# nums that can destory 5 targets are [1], nums that can destory 1 target are [8] \n        return min(performance[max(performance)])",
      "slug": "destroy-sequential-targets",
      "post_title": "Python | Greedy | Group | Example",
      "user": "yzhao156",
      "upvotes": 3,
      "views": 122,
      "problem_title": "destroy sequential targets",
      "number": 2453,
      "acceptance": 0.373,
      "difficulty": "Medium",
      "__index_level_0__": 33608,
      "question": "You are given a 0-indexed array nums consisting of positive integers, representing targets on a number line. You are also given an integer space.\nYou have a machine which can destroy targets. Seeding the machine with some nums[i] allows it to destroy all targets with values that can be represented as nums[i] + c * space, where c is any non-negative integer. You want to destroy the maximum number of targets in nums.\nReturn the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.\n  Example 1:\nInput: nums = [3,7,8,1,1,5], space = 2\nOutput: 1\nExplanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,... \nIn this case, we would destroy 5 total targets (all except for nums[2]). \nIt is impossible to destroy more than 5 targets, so we return nums[3].\nExample 2:\nInput: nums = [1,3,5,2,4,6], space = 2\nOutput: 1\nExplanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets. \nIt is not possible to destroy more than 3 targets.\nSince nums[0] is the minimal integer that can destroy 3 targets, we return 1.\nExample 3:\nInput: nums = [6,2,5], space = 100\nOutput: 2\nExplanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].\n  Constraints:\n1 <= nums.length <= 105\n1 <= nums[i] <= 109\n1 <= space <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/next-greater-element-iv/discuss/2757259/Python3-intermediate-stack",
      "python_solutions": "class Solution:\n    def secondGreaterElement(self, nums: List[int]) -> List[int]:\n        ans = [-1] * len(nums)\n        s, ss = [], []\n        for i, x in enumerate(nums): \n            while ss and nums[ss[-1]] < x: ans[ss.pop()] = x\n            buff = []\n            while s and nums[s[-1]] < x: buff.append(s.pop())\n            while buff: ss.append(buff.pop())\n            s.append(i)\n        return ans",
      "slug": "next-greater-element-iv",
      "post_title": "[Python3] intermediate stack",
      "user": "ye15",
      "upvotes": 1,
      "views": 38,
      "problem_title": "next greater element iv",
      "number": 2454,
      "acceptance": 0.396,
      "difficulty": "Hard",
      "__index_level_0__": 33619,
      "question": "You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.\nThe second greater integer of nums[i] is nums[j] such that:\nj > i\nnums[j] > nums[i]\nThere exists exactly one index k such that nums[k] > nums[i] and i < k < j.\nIf there is no such nums[j], the second greater integer is considered to be -1.\nFor example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1.\nReturn an integer array answer, where answer[i] is the second greater integer of nums[i].\n  Example 1:\nInput: nums = [2,4,0,9,6]\nOutput: [9,6,6,-1,-1]\nExplanation:\n0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.\n1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.\n2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.\n3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.\n4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.\nThus, we return [9,6,6,-1,-1].\nExample 2:\nInput: nums = [3,3]\nOutput: [-1,-1]\nExplanation:\nWe return [-1,-1] since neither integer has any integer greater than it.\n  Constraints:\n1 <= nums.length <= 105\n0 <= nums[i] <= 109"
    },
    {
      "post_href": "https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three/discuss/2770799/Easy-Python-Solution",
      "python_solutions": "class Solution:\n    def averageValue(self, nums: List[int]) -> int:\n        l=[]\n        for i in nums:\n            if i%6==0:\n                l.append(i)\n        return sum(l)//len(l) if len(l)>0 else 0",
      "slug": "average-value-of-even-numbers-that-are-divisible-by-three",
      "post_title": "Easy Python Solution",
      "user": "Vistrit",
      "upvotes": 2,
      "views": 107,
      "problem_title": "average value of even numbers that are divisible by three",
      "number": 2455,
      "acceptance": 0.58,
      "difficulty": "Easy",
      "__index_level_0__": 33623,
      "question": "Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.\nNote that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.\n  Example 1:\nInput: nums = [1,3,6,10,12,15]\nOutput: 9\nExplanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.\nExample 2:\nInput: nums = [1,2,4,7,10]\nOutput: 0\nExplanation: There is no single number that satisfies the requirement, so return 0.\n  Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i] <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/most-popular-video-creator/discuss/2758104/Python-Hashmap-solution-or-No-Sorting",
      "python_solutions": "class Solution:\n    def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]:\n        memo = {}\n\t\t#tracking the max popular video count\n        overall_max_popular_video_count = -1\n        #looping over the creators\n        for i in range(len(creators)):\n            if creators[i] in memo:\n                #Step 1: update number of views for the creator\n                memo[creators[i]][0] += views[i]\n                #Step 2: update current_popular_video_view and id_of_most_popular_video_so_far\n                if memo[creators[i]][2] < views[i]:\n                    memo[creators[i]][1] = ids[i]\n                    memo[creators[i]][2] = views[i]\n                #Step 2a: finding the lexicographically smallest id as we hit the current_popularity_video_view again!\n                elif memo[creators[i]][2] == views[i]:\n                    memo[creators[i]][1] = min(memo[creators[i]][1],ids[i])\n            else:\n\t\t\t#adding new entry to our memo\n\t\t\t#new entry is of the format memo[creator[i]] = [total number current views for the creator, store the lexicographic id of the popular video, current popular view of the creator]\n                memo[creators[i]] = [views[i],ids[i],views[i]]\n\t\t\t#track the max popular video count\n            overall_max_popular_video_count = max(memo[creators[i]][0],overall_max_popular_video_count)\n        \n        result = []\n        for i in memo:\n            if memo[i][0] == overall_max_popular_video_count:\n                result.append([i,memo[i][1]])\n        return result",
      "slug": "most-popular-video-creator",
      "post_title": "Python Hashmap solution | No Sorting",
      "user": "dee7",
      "upvotes": 5,
      "views": 330,
      "problem_title": "most popular video creator",
      "number": 2456,
      "acceptance": 0.441,
      "difficulty": "Medium",
      "__index_level_0__": 33656,
      "question": "You are given two string arrays creators and ids, and an integer array views, all of length n. The ith video on a platform was created by creator[i], has an id of ids[i], and has views[i] views.\nThe popularity of a creator is the sum of the number of views on all of the creator's videos. Find the creator with the highest popularity and the id of their most viewed video.\nIf multiple creators have the highest popularity, find all of them.\nIf multiple videos have the highest view count for a creator, find the lexicographically smallest id.\nReturn a 2D array of strings answer where answer[i] = [creatori, idi] means that creatori has the highest popularity and idi is the id of their most popular video. The answer can be returned in any order.\n  Example 1:\nInput: creators = [\"alice\",\"bob\",\"alice\",\"chris\"], ids = [\"one\",\"two\",\"three\",\"four\"], views = [5,10,5,4]\nOutput: [[\"alice\",\"one\"],[\"bob\",\"two\"]]\nExplanation:\nThe popularity of alice is 5 + 5 = 10.\nThe popularity of bob is 10.\nThe popularity of chris is 4.\nalice and bob are the most popular creators.\nFor bob, the video with the highest view count is \"two\".\nFor alice, the videos with the highest view count are \"one\" and \"three\". Since \"one\" is lexicographically smaller than \"three\", it is included in the answer.\nExample 2:\nInput: creators = [\"alice\",\"alice\",\"alice\"], ids = [\"a\",\"b\",\"c\"], views = [1,2,2]\nOutput: [[\"alice\",\"b\"]]\nExplanation:\nThe videos with id \"b\" and \"c\" have the highest view count.\nSince \"b\" is lexicographically smaller than \"c\", it is included in the answer.\n  Constraints:\nn == creators.length == ids.length == views.length\n1 <= n <= 105\n1 <= creators[i].length, ids[i].length <= 5\ncreators[i] and ids[i] consist only of lowercase English letters.\n0 <= views[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-addition-to-make-integer-beautiful/discuss/2758079/Check-next-10-next-100-next-1000-and-so-on...",
      "python_solutions": "class Solution:\n    def makeIntegerBeautiful(self, n: int, target: int) -> int:\n        i=n\n        l=1\n        while i<=10**12:\n            s=0\n            for j in str(i):\n                s+=int(j)\n            if s<=target:\n                return i-n\n            i//=10**l\n            i+=1\n            i*=10**l\n            l+=1",
      "slug": "minimum-addition-to-make-integer-beautiful",
      "post_title": "Check next 10, next 100, next 1000 and so on...",
      "user": "shreyasjain0912",
      "upvotes": 2,
      "views": 97,
      "problem_title": "minimum addition to make integer beautiful",
      "number": 2457,
      "acceptance": 0.368,
      "difficulty": "Medium",
      "__index_level_0__": 33677,
      "question": "You are given two positive integers n and target.\nAn integer is considered beautiful if the sum of its digits is less than or equal to target.\nReturn the minimum non-negative integer x such that n + x is beautiful. The input will be generated such that it is always possible to make n beautiful.\n  Example 1:\nInput: n = 16, target = 6\nOutput: 4\nExplanation: Initially n is 16 and its digit sum is 1 + 6 = 7. After adding 4, n becomes 20 and digit sum becomes 2 + 0 = 2. It can be shown that we can not make n beautiful with adding non-negative integer less than 4.\nExample 2:\nInput: n = 467, target = 6\nOutput: 33\nExplanation: Initially n is 467 and its digit sum is 4 + 6 + 7 = 17. After adding 33, n becomes 500 and digit sum becomes 5 + 0 + 0 = 5. It can be shown that we can not make n beautiful with adding non-negative integer less than 33.\nExample 3:\nInput: n = 1, target = 1\nOutput: 0\nExplanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.\n  Constraints:\n1 <= n <= 1012\n1 <= target <= 150\nThe input will be generated such that it is always possible to make n beautiful."
    },
    {
      "post_href": "https://leetcode.com/problems/height-of-binary-tree-after-subtree-removal-queries/discuss/2760795/Python3-Triple-dict-depth-height-nodes_at_depth",
      "python_solutions": "class Solution:\n    def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:\n        depth = {}\n        height = {}\n        nodes_at_depth = {}\n\n        max_height = 0\n\n        def rec(n, d):\n            nonlocal max_height\n            if n is None:\n                return 0\n            height_below = max(rec(n.left, d+1), rec(n.right, d+1))\n            v = n.val\n            depth[v] = d\n            h = d + 1 + height_below\n            height[v] = h\n            max_height = max(max_height, h)\n\n            if d not in nodes_at_depth:\n                nodes_at_depth[d] = [v]\n            else:\n                nodes_at_depth[d].append(v)\n\n            return 1 + height_below\n\n\n        rec(root, -1)  # subtract one because the problem reports heights weird\n        ret = []\n\n\n        for q in queries:\n            if height[q] >= max_height:\n                d = depth[q]\n                for cousin in nodes_at_depth[depth[q]]:\n                    if cousin != q:  # don't count self, obviously\n                        d = max(d, height[cousin])\n                ret.append(d)  \n            else:\n                ret.append(max_height)\n        \n        return ret",
      "slug": "height-of-binary-tree-after-subtree-removal-queries",
      "post_title": "Python3 Triple dict depth, height, nodes_at_depth",
      "user": "godshiva",
      "upvotes": 0,
      "views": 12,
      "problem_title": "height of binary tree after subtree removal queries",
      "number": 2458,
      "acceptance": 0.354,
      "difficulty": "Hard",
      "__index_level_0__": 33696,
      "question": "You are given the root of a binary tree with n nodes. Each node is assigned a unique value from 1 to n. You are also given an array queries of size m.\nYou have to perform m independent queries on the tree where in the ith query you do the following:\nRemove the subtree rooted at the node with the value queries[i] from the tree. It is guaranteed that queries[i] will not be equal to the value of the root.\nReturn an array answer of size m where answer[i] is the height of the tree after performing the ith query.\nNote:\nThe queries are independent, so the tree returns to its initial state after each query.\nThe height of a tree is the number of edges in the longest simple path from the root to some node in the tree.\n  Example 1:\nInput: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]\nOutput: [2]\nExplanation: The diagram above shows the tree after removing the subtree rooted at node with value 4.\nThe height of the tree is 2 (The path 1 -> 3 -> 2).\nExample 2:\nInput: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]\nOutput: [3,2,3,2]\nExplanation: We have the following queries:\n- Removing the subtree rooted at node with value 3. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 4).\n- Removing the subtree rooted at node with value 2. The height of the tree becomes 2 (The path 5 -> 8 -> 1).\n- Removing the subtree rooted at node with value 4. The height of the tree becomes 3 (The path 5 -> 8 -> 2 -> 6).\n- Removing the subtree rooted at node with value 8. The height of the tree becomes 2 (The path 5 -> 9 -> 3).\n  Constraints:\nThe number of nodes in the tree is n.\n2 <= n <= 105\n1 <= Node.val <= n\nAll the values in the tree are unique.\nm == queries.length\n1 <= m <= min(n, 104)\n1 <= queries[i] <= n\nqueries[i] != root.val"
    },
    {
      "post_href": "https://leetcode.com/problems/apply-operations-to-an-array/discuss/2786435/Python-Simple-Python-Solution-89-ms",
      "python_solutions": "class Solution:\n    def applyOperations(self, nums: List[int]) -> List[int]:\n        for i in range(len(nums)-1):\n            if nums[i]==nums[i+1]:\n                nums[i]*=2\n                nums[i+1]=0                \n        temp = []\n        zeros = []\n        a=nums\n        for i in range(len(a)):\n            if a[i] !=0:\n                temp.append(a[i])\n            else:\n                zeros.append(a[i])\n        return (temp+zeros)",
      "slug": "apply-operations-to-an-array",
      "post_title": "[ Python ] \ud83d\udc0d\ud83d\udc0d Simple Python Solution \u2705\u2705 89 ms",
      "user": "sourav638",
      "upvotes": 3,
      "views": 31,
      "problem_title": "apply operations to an array",
      "number": 2460,
      "acceptance": 0.6709999999999999,
      "difficulty": "Easy",
      "__index_level_0__": 33698,
      "question": "You are given a 0-indexed array nums of size n consisting of non-negative integers.\nYou need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums:\nIf nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.\nAfter performing all the operations, shift all the 0's to the end of the array.\nFor example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0].\nReturn the resulting array.\nNote that the operations are applied sequentially, not all at once.\n  Example 1:\nInput: nums = [1,2,2,1,1,0]\nOutput: [1,4,2,0,0,0]\nExplanation: We do the following operations:\n- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.\n- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].\n- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.\n- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].\n- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].\nAfter that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].\nExample 2:\nInput: nums = [0,1]\nOutput: [1,0]\nExplanation: No operation can be applied, we just shift the 0 to the end.\n  Constraints:\n2 <= nums.length <= 2000\n0 <= nums[i] <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-sum-of-distinct-subarrays-with-length-k/discuss/2783646/Python-easy-solution-using-libraries",
      "python_solutions": "class Solution:\n    def maximumSubarraySum(self, nums: List[int], k: int) -> int:\n        \n        seen = collections.Counter(nums[:k]) #from collections import Counter (elements and their respective count are stored as a dictionary)\n        summ = sum(nums[:k])\n        \n        \n        res = 0\n        if len(seen) == k:\n            res = summ\n            \n            \n        for i in range(k, len(nums)):\n            summ += nums[i] - nums[i-k]\n            seen[nums[i]] += 1\n            seen[nums[i-k]] -= 1\n            \n            if seen[nums[i-k]] == 0:\n                del seen[nums[i-k]]\n                \n            if len(seen) == k:\n                res = max(res, summ) \n                \n        return res",
      "slug": "maximum-sum-of-distinct-subarrays-with-length-k",
      "post_title": "\u2705\u2705Python easy solution using libraries",
      "user": "Sumit6258",
      "upvotes": 4,
      "views": 224,
      "problem_title": "maximum sum of distinct subarrays with length k",
      "number": 2461,
      "acceptance": 0.344,
      "difficulty": "Medium",
      "__index_level_0__": 33748,
      "question": "You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:\nThe length of the subarray is k, and\nAll the elements of the subarray are distinct.\nReturn the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.\nA subarray is a contiguous non-empty sequence of elements within an array.\n  Example 1:\nInput: nums = [1,5,4,2,9,9,9], k = 3\nOutput: 15\nExplanation: The subarrays of nums with length 3 are:\n- [1,5,4] which meets the requirements and has a sum of 10.\n- [5,4,2] which meets the requirements and has a sum of 11.\n- [4,2,9] which meets the requirements and has a sum of 15.\n- [2,9,9] which does not meet the requirements because the element 9 is repeated.\n- [9,9,9] which does not meet the requirements because the element 9 is repeated.\nWe return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions\nExample 2:\nInput: nums = [4,4,4], k = 3\nOutput: 0\nExplanation: The subarrays of nums with length 3 are:\n- [4,4,4] which does not meet the requirements because the element 4 is repeated.\nWe return 0 because no subarrays meet the conditions.\n  Constraints:\n1 <= k <= nums.length <= 105\n1 <= nums[i] <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/total-cost-to-hire-k-workers/discuss/2783147/Python3-priority-queues",
      "python_solutions": "class Solution:\n    def totalCost(self, costs: List[int], k: int, candidates: int) -> int:\n        q = costs[:candidates]\n        qq = costs[max(candidates, len(costs)-candidates):]\n        heapify(q)\n        heapify(qq)\n        ans = 0 \n        i, ii = candidates, len(costs)-candidates-1\n        for _ in range(k): \n            if not qq or q and q[0] <= qq[0]: \n                ans += heappop(q)\n                if i <= ii: \n                    heappush(q, costs[i])\n                    i += 1\n            else: \n                ans += heappop(qq)\n                if i <= ii: \n                    heappush(qq, costs[ii])\n                    ii -= 1\n        return ans",
      "slug": "total-cost-to-hire-k-workers",
      "post_title": "[Python3] priority queues",
      "user": "ye15",
      "upvotes": 24,
      "views": 1200,
      "problem_title": "total cost to hire k workers",
      "number": 2462,
      "acceptance": 0.374,
      "difficulty": "Medium",
      "__index_level_0__": 33780,
      "question": "You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.\nYou are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:\nYou will run k sessions and hire exactly one worker in each session.\nIn each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index.\nFor example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].\nIn the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process.\nIf there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.\nA worker can only be chosen once.\nReturn the total cost to hire exactly k workers.\n  Example 1:\nInput: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4\nOutput: 11\nExplanation: We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [17,12,10,2,7,2,11,20,8]. The lowest cost is 2, and we break the tie by the smallest index, which is 3. The total cost = 0 + 2 = 2.\n- In the second hiring round we choose the worker from [17,12,10,7,2,11,20,8]. The lowest cost is 2 (index 4). The total cost = 2 + 2 = 4.\n- In the third hiring round we choose the worker from [17,12,10,7,11,20,8]. The lowest cost is 7 (index 3). The total cost = 4 + 7 = 11. Notice that the worker with index 3 was common in the first and last four workers.\nThe total hiring cost is 11.\nExample 2:\nInput: costs = [1,2,4,1], k = 3, candidates = 3\nOutput: 4\nExplanation: We hire 3 workers in total. The total cost is initially 0.\n- In the first hiring round we choose the worker from [1,2,4,1]. The lowest cost is 1, and we break the tie by the smallest index, which is 0. The total cost = 0 + 1 = 1. Notice that workers with index 1 and 2 are common in the first and last 3 workers.\n- In the second hiring round we choose the worker from [2,4,1]. The lowest cost is 1 (index 2). The total cost = 1 + 1 = 2.\n- In the third hiring round there are less than three candidates. We choose the worker from the remaining workers [2,4]. The lowest cost is 2 (index 0). The total cost = 2 + 2 = 4.\nThe total hiring cost is 4.\n  Constraints:\n1 <= costs.length <= 105 \n1 <= costs[i] <= 105\n1 <= k, candidates <= costs.length"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-total-distance-traveled/discuss/2783245/Python3-O(MN)-DP",
      "python_solutions": "class Solution:\n    def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:\n        robot.sort()\n        factory.sort()\n        m, n = len(robot), len(factory)\n        dp = [[0]*(n+1) for _ in range(m+1)] \n        for i in range(m): dp[i][-1] = inf \n        for j in range(n-1, -1, -1): \n            prefix = 0 \n            qq = deque([(m, 0)])\n            for i in range(m-1, -1, -1): \n                prefix += abs(robot[i] - factory[j][0])\n                if qq[0][0] > i+factory[j][1]: qq.popleft()\n                while qq and qq[-1][1] >= dp[i][j+1] - prefix: qq.pop()\n                qq.append((i, dp[i][j+1] - prefix))\n                dp[i][j] = qq[0][1] + prefix\n        return dp[0][0]",
      "slug": "minimum-total-distance-traveled",
      "post_title": "[Python3] O(MN) DP",
      "user": "ye15",
      "upvotes": 13,
      "views": 769,
      "problem_title": "minimum total distance traveled",
      "number": 2463,
      "acceptance": 0.397,
      "difficulty": "Hard",
      "__index_level_0__": 33799,
      "question": "There are some robots and factories on the X-axis. You are given an integer array robot where robot[i] is the position of the ith robot. You are also given a 2D integer array factory where factory[j] = [positionj, limitj] indicates that positionj is the position of the jth factory and that the jth factory can repair at most limitj robots.\nThe positions of each robot are unique. The positions of each factory are also unique. Note that a robot can be in the same position as a factory initially.\nAll the robots are initially broken; they keep moving in one direction. The direction could be the negative or the positive direction of the X-axis. When a robot reaches a factory that did not reach its limit, the factory repairs the robot, and it stops moving.\nAt any moment, you can set the initial direction of moving for some robot. Your target is to minimize the total distance traveled by all the robots.\nReturn the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.\nNote that\nAll robots move at the same speed.\nIf two robots move in the same direction, they will never collide.\nIf two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.\nIf a robot passes by a factory that reached its limits, it crosses it as if it does not exist.\nIf the robot moved from a position x to a position y, the distance it moved is |y - x|.\n  Example 1:\nInput: robot = [0,4,6], factory = [[2,2],[6,2]]\nOutput: 4\nExplanation: As shown in the figure:\n- The first robot at position 0 moves in the positive direction. It will be repaired at the first factory.\n- The second robot at position 4 moves in the negative direction. It will be repaired at the first factory.\n- The third robot at position 6 will be repaired at the second factory. It does not need to move.\nThe limit of the first factory is 2, and it fixed 2 robots.\nThe limit of the second factory is 2, and it fixed 1 robot.\nThe total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.\nExample 2:\nInput: robot = [1,-1], factory = [[-2,1],[2,1]]\nOutput: 2\nExplanation: As shown in the figure:\n- The first robot at position 1 moves in the positive direction. It will be repaired at the second factory.\n- The second robot at position -1 moves in the negative direction. It will be repaired at the first factory.\nThe limit of the first factory is 1, and it fixed 1 robot.\nThe limit of the second factory is 1, and it fixed 1 robot.\nThe total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.\n  Constraints:\n1 <= robot.length, factory.length <= 100\nfactory[j].length == 2\n-109 <= robot[i], positionj <= 109\n0 <= limitj <= robot.length\nThe input will be generated such that it is always possible to repair every robot."
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-distinct-averages/discuss/2817811/Easy-Python-Solution",
      "python_solutions": "class Solution:\n    def distinctAverages(self, nums: List[int]) -> int:\n        av=[]\n        nums.sort()\n        while nums:\n            av.append((nums[-1]+nums[0])/2)\n            nums.pop(-1)\n            nums.pop(0)\n        return len(set(av))",
      "slug": "number-of-distinct-averages",
      "post_title": "Easy Python Solution",
      "user": "Vistrit",
      "upvotes": 2,
      "views": 75,
      "problem_title": "number of distinct averages",
      "number": 2465,
      "acceptance": 0.588,
      "difficulty": "Easy",
      "__index_level_0__": 33805,
      "question": "You are given a 0-indexed integer array nums of even length.\nAs long as nums is not empty, you must repetitively:\nFind the minimum number in nums and remove it.\nFind the maximum number in nums and remove it.\nCalculate the average of the two removed numbers.\nThe average of two numbers a and b is (a + b) / 2.\nFor example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.\nReturn the number of distinct averages calculated using the above process.\nNote that when there is a tie for a minimum or maximum number, any can be removed.\n  Example 1:\nInput: nums = [4,1,4,0,3,5]\nOutput: 2\nExplanation:\n1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].\n2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].\n3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.\nSince there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.\nExample 2:\nInput: nums = [1,100]\nOutput: 1\nExplanation:\nThere is only one average to be calculated after removing 1 and 100, so we return 1.\n  Constraints:\n2 <= nums.length <= 100\nnums.length is even.\n0 <= nums[i] <= 100"
    },
    {
      "post_href": "https://leetcode.com/problems/count-ways-to-build-good-strings/discuss/2813134/Easy-solution-from-Recursion-to-memoization-oror-3-approaches-oror-PYTHON3",
      "python_solutions": "class Solution:\n    def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:\n        def recursive(s,ans):\n            if len(s)>=low and len(s)<=high:\n                ans+=[s]\n            if len(s)>high:\n                return \n            recursive(s+\"0\"*zero,ans)\n            recursive(s+\"1\"*one,ans)\n            return\n        ans=[]\n        recursive(\"\",ans)\n        return len(ans)",
      "slug": "count-ways-to-build-good-strings",
      "post_title": "Easy solution from Recursion to memoization || 3 approaches || PYTHON3",
      "user": "dabbiruhaneesh",
      "upvotes": 1,
      "views": 32,
      "problem_title": "count ways to build good strings",
      "number": 2466,
      "acceptance": 0.419,
      "difficulty": "Medium",
      "__index_level_0__": 33846,
      "question": "Given the integers zero, one, low, and high, we can construct a string by starting with an empty string, and then at each step perform either of the following:\nAppend the character '0' zero times.\nAppend the character '1' one times.\nThis can be performed any number of times.\nA good string is a string constructed by the above process having a length between low and high (inclusive).\nReturn the number of different good strings that can be constructed satisfying these properties. Since the answer can be large, return it modulo 109 + 7.\n  Example 1:\nInput: low = 3, high = 3, zero = 1, one = 1\nOutput: 8\nExplanation: \nOne possible valid good string is \"011\". \nIt can be constructed as follows: \"\" -> \"0\" -> \"01\" -> \"011\". \nAll binary strings from \"000\" to \"111\" are good strings in this example.\nExample 2:\nInput: low = 2, high = 3, zero = 1, one = 2\nOutput: 5\nExplanation: The good strings are \"00\", \"11\", \"000\", \"110\", and \"011\".\n  Constraints:\n1 <= low <= high <= 105\n1 <= zero, one <= low"
    },
    {
      "post_href": "https://leetcode.com/problems/most-profitable-path-in-a-tree/discuss/2838006/BFS-%2B-Graph-%2B-level-O(n)",
      "python_solutions": "class Solution:\n    def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:\n        path_b = set([bob])\n        lvl_b = {bob:0}\n        g = defaultdict(list)\n        for u, v in edges:\n            g[u].append(v)\n            g[v].append(u)\n        n = len(amount)\n        node_lvl = [0] * n\n        q = deque([0])\n        \n        lvl = 0\n        seen = set([0])\n        while q:\n            size = len(q)\n            for _ in range(size):\n                u = q.popleft()\n                node_lvl[u] = lvl\n                for v in g[u]:\n                    if v in seen:\n                        continue\n                    q.append(v)\n                    seen.add(v)\n            lvl += 1\n        b = bob\n        lvl = 1\n        while b != 0:\n            for v in g[b]:\n                if node_lvl[v] > node_lvl[b]:\n                    continue\n                b = v\n                cost = amount[b]\n                path_b.add(b)\n                lvl_b[b] = lvl\n                break\n            lvl += 1\n        # print(f\"lvl_b {lvl_b} path_b {path_b}  \")\n        cost_a = []\n        q = deque([(0, amount[0])])\n        seen = set([0])\n        lvl = 1\n        while q:\n            size = len(q)\n            for _ in range(size):\n                u, pre_cost = q.popleft()\n                child_cnt = 0\n                for v in g[u]:\n                    if v in seen:\n                        continue\n                    seen.add(v)\n                    child_cnt += 1\n                    cost = pre_cost\n                    inc = amount[v]\n                    if v in path_b:\n                        if lvl_b[v] == lvl:\n                            cost += inc//2\n                        elif lvl_b[v] > lvl:\n                            cost += inc\n                        else:\n                            cost += 0\n                    else:\n                        cost += amount[v]\n                    q.append((v, cost))\n                if child_cnt == 0:\n                    cost_a.append(pre_cost)\n            lvl += 1\n        ans = max(cost_a)\n        return ans",
      "slug": "most-profitable-path-in-a-tree",
      "post_title": "BFS + Graph + level, O(n)",
      "user": "goodgoodwish",
      "upvotes": 0,
      "views": 2,
      "problem_title": "most profitable path in a tree",
      "number": 2467,
      "acceptance": 0.4639999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 33859,
      "question": "There is an undirected tree with n nodes labeled from 0 to n - 1, rooted at node 0. You are given a 2D integer array edges of length n - 1 where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.\nAt every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:\nthe price needed to open the gate at node i, if amount[i] is negative, or,\nthe cash reward obtained on opening the gate at node i, otherwise.\nThe game goes on as follows:\nInitially, Alice is at node 0 and Bob is at node bob.\nAt every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.\nFor every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:\nIf the gate is already open, no price will be required, nor will there be any cash reward.\nIf Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.\nIf Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.\nReturn the maximum net income Alice can have if she travels towards the optimal leaf node.\n  Example 1:\nInput: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]\nOutput: 6\nExplanation: \nThe above diagram represents the given tree. The game goes as follows:\n- Alice is initially on node 0, Bob on node 3. They open the gates of their respective nodes.\n  Alice's net income is now -2.\n- Both Alice and Bob move to node 1. \n  Since they reach here simultaneously, they open the gate together and share the reward.\n  Alice's net income becomes -2 + (4 / 2) = 0.\n- Alice moves on to node 3. Since Bob already opened its gate, Alice's income remains unchanged.\n  Bob moves on to node 0, and stops moving.\n- Alice moves on to node 4 and opens the gate there. Her net income becomes 0 + 6 = 6.\nNow, neither Alice nor Bob can make any further moves, and the game ends.\nIt is not possible for Alice to get a higher net income.\nExample 2:\nInput: edges = [[0,1]], bob = 1, amount = [-7280,2350]\nOutput: -7280\nExplanation: \nAlice follows the path 0->1 whereas Bob follows the path 1->0.\nThus, Alice opens the gate at node 0 only. Hence, her net income is -7280. \n  Constraints:\n2 <= n <= 105\nedges.length == n - 1\nedges[i].length == 2\n0 <= ai, bi < n\nai != bi\nedges represents a valid tree.\n1 <= bob < n\namount.length == n\namount[i] is an even integer in the range [-104, 104]."
    },
    {
      "post_href": "https://leetcode.com/problems/split-message-based-on-limit/discuss/2807491/Python-Simple-dumb-O(N)-solution",
      "python_solutions": "class Solution:\n    def splitMessage(self, message: str, limit: int) -> List[str]:\n        def splitable_within(parts_limit):\n            # check the message length achievable with  parts\n            length = sum(limit - len(str(i)) - len(str(parts_limit)) - 3 for i in range(1, parts_limit + 1))\n            return length >= len(message)\n        \n        parts_limit = 9\n        if not splitable_within(parts_limit):\n            parts_limit = 99\n        if not splitable_within(parts_limit):\n            parts_limit = 999\n        if not splitable_within(parts_limit):\n            parts_limit = 9999\n        if not splitable_within(parts_limit):\n            return []\n        \n        # generate the actual message parts\n        parts = []\n        m_index = 0  # message index\n        for part_index in range(1, parts_limit + 1):\n            if m_index >= len(message): break\n            length = limit - len(str(part_index)) - len(str(parts_limit)) - 3\n            parts.append(message[m_index:m_index + length])\n            m_index += length\n        \n        return [f'{part}<{i + 1}/{len(parts)}>' for i, part in enumerate(parts)]",
      "slug": "split-message-based-on-limit",
      "post_title": "[Python] Simple dumb O(N) solution",
      "user": "vudinhhung942k",
      "upvotes": 2,
      "views": 62,
      "problem_title": "split message based on limit",
      "number": 2468,
      "acceptance": 0.483,
      "difficulty": "Hard",
      "__index_level_0__": 33868,
      "question": "You are given a string, message, and a positive integer, limit.\nYou must split message into one or more parts based on limit. Each resulting part should have the suffix \"\", where \"b\" is to be replaced with the total number of parts and \"a\" is to be replaced with the index of the part, starting from 1 and going up to b. Additionally, the length of each resulting part (including its suffix) should be equal to limit, except for the last part whose length can be at most limit.\nThe resulting parts should be formed such that when their suffixes are removed and they are all concatenated in order, they should be equal to message. Also, the result should contain as few parts as possible.\nReturn the parts message would be split into as an array of strings. If it is impossible to split message as required, return an empty array.\n  Example 1:\nInput: message = \"this is really a very awesome message\", limit = 9\nOutput: [\"thi<1/14>\",\"s i<2/14>\",\"s r<3/14>\",\"eal<4/14>\",\"ly <5/14>\",\"a v<6/14>\",\"ery<7/14>\",\" aw<8/14>\",\"eso<9/14>\",\"me<10/14>\",\" m<11/14>\",\"es<12/14>\",\"sa<13/14>\",\"ge<14/14>\"]\nExplanation:\nThe first 9 parts take 3 characters each from the beginning of message.\nThe next 5 parts take 2 characters each to finish splitting message. \nIn this example, each part, including the last, has length 9. \nIt can be shown it is not possible to split message into less than 14 parts.\nExample 2:\nInput: message = \"short message\", limit = 15\nOutput: [\"short mess<1/2>\",\"age<2/2>\"]\nExplanation:\nUnder the given constraints, the string can be split into two parts: \n- The first part comprises of the first 10 characters, and has a length 15.\n- The next part comprises of the last 3 characters, and has a length 8.\n  Constraints:\n1 <= message.length <= 104\nmessage consists only of lowercase English letters and ' '.\n1 <= limit <= 104"
    },
    {
      "post_href": "https://leetcode.com/problems/convert-the-temperature/discuss/2839560/Python-or-Easy-Solution",
      "python_solutions": "class Solution:\n    def convertTemperature(self, celsius: float) -> List[float]:\n        return [(celsius + 273.15),(celsius * 1.80 + 32.00)]",
      "slug": "convert-the-temperature",
      "post_title": "Python | Easy Solution\u2714",
      "user": "manayathgeorgejames",
      "upvotes": 4,
      "views": 127,
      "problem_title": "convert the temperature",
      "number": 2469,
      "acceptance": 0.909,
      "difficulty": "Easy",
      "__index_level_0__": 33880,
      "question": "You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.\nYou should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit].\nReturn the array ans. Answers within 10-5 of the actual answer will be accepted.\nNote that:\nKelvin = Celsius + 273.15\nFahrenheit = Celsius * 1.80 + 32.00\n  Example 1:\nInput: celsius = 36.50\nOutput: [309.65000,97.70000]\nExplanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70.\nExample 2:\nInput: celsius = 122.11\nOutput: [395.26000,251.79800]\nExplanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798.\n  Constraints:\n0 <= celsius <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-subarrays-with-lcm-equal-to-k/discuss/2808943/Beginners-Approach-%3A",
      "python_solutions": "class Solution:\n    def subarrayLCM(self, nums: List[int], k: int) -> int:\n        def find_lcm(num1, num2):\n            if(num1>num2):\n                num = num1\n                den = num2\n            else:\n                num = num2\n                den = num1\n            rem = num % den\n            while(rem != 0):\n                num = den\n                den = rem\n                rem = num % den\n            gcd = den\n            lcm = int(int(num1 * num2)/int(gcd))\n            return lcm\n        count=0\n        for i in range(len(nums)):\n            lcm=1\n            for j in range(i,len(nums)):\n                lcm=find_lcm(nums[j],lcm)\n                \n                if lcm==k:\n                    count+=1\n                if lcm>k:\n                    break\n        return count",
      "slug": "number-of-subarrays-with-lcm-equal-to-k",
      "post_title": "Beginners Approach :",
      "user": "goxy_coder",
      "upvotes": 1,
      "views": 57,
      "problem_title": "number of subarrays with lcm equal to k",
      "number": 2470,
      "acceptance": 0.3879999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 33919,
      "question": "Given an integer array nums and an integer k, return the number of subarrays of nums where the least common multiple of the subarray's elements is k.\nA subarray is a contiguous non-empty sequence of elements within an array.\nThe least common multiple of an array is the smallest positive integer that is divisible by all the array elements.\n  Example 1:\nInput: nums = [3,6,2,7,1], k = 6\nOutput: 4\nExplanation: The subarrays of nums where 6 is the least common multiple of all the subarray's elements are:\n- [3,6,2,7,1]\n- [3,6,2,7,1]\n- [3,6,2,7,1]\n- [3,6,2,7,1]\nExample 2:\nInput: nums = [3], k = 2\nOutput: 0\nExplanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.\n  Constraints:\n1 <= nums.length <= 1000\n1 <= nums[i], k <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-number-of-operations-to-sort-a-binary-tree-by-level/discuss/2808960/Python3-BFS",
      "python_solutions": "class Solution:\n    def minimumOperations(self, root: Optional[TreeNode]) -> int:\n        ans = 0 \n        queue = deque([root])\n        while queue: \n            vals = []\n            for _ in range(len(queue)): \n                node = queue.popleft()\n                vals.append(node.val)\n                if node.left: queue.append(node.left)\n                if node.right: queue.append(node.right)\n            mp = {x : i for i, x in enumerate(sorted(vals))}\n            visited = [0]*len(vals)\n            for i in range(len(vals)): \n                cnt = 0 \n                while not visited[i] and i != mp[vals[i]]: \n                    visited[i] = 1\n                    cnt += 1\n                    i = mp[vals[i]]\n                ans += max(0, cnt-1)\n        return ans",
      "slug": "minimum-number-of-operations-to-sort-a-binary-tree-by-level",
      "post_title": "[Python3] BFS",
      "user": "ye15",
      "upvotes": 6,
      "views": 567,
      "problem_title": "minimum number of operations to sort a binary tree by level",
      "number": 2471,
      "acceptance": 0.629,
      "difficulty": "Medium",
      "__index_level_0__": 33930,
      "question": "You are given the root of a binary tree with unique values.\nIn one operation, you can choose any two nodes at the same level and swap their values.\nReturn the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.\nThe level of a node is the number of edges along the path between it and the root node.\n  Example 1:\nInput: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]\nOutput: 3\nExplanation:\n- Swap 4 and 3. The 2nd level becomes [3,4].\n- Swap 7 and 5. The 3rd level becomes [5,6,8,7].\n- Swap 8 and 7. The 3rd level becomes [5,6,7,8].\nWe used 3 operations so return 3.\nIt can be proven that 3 is the minimum number of operations needed.\nExample 2:\nInput: root = [1,3,2,7,6,5,4]\nOutput: 3\nExplanation:\n- Swap 3 and 2. The 2nd level becomes [2,3].\n- Swap 7 and 4. The 3rd level becomes [4,6,5,7].\n- Swap 6 and 5. The 3rd level becomes [4,5,6,7].\nWe used 3 operations so return 3.\nIt can be proven that 3 is the minimum number of operations needed.\nExample 3:\nInput: root = [1,2,3,4,5,6]\nOutput: 0\nExplanation: Each level is already sorted in increasing order so return 0.\n  Constraints:\nThe number of nodes in the tree is in the range [1, 105].\n1 <= Node.val <= 105\nAll the values of the tree are unique."
    },
    {
      "post_href": "https://leetcode.com/problems/maximum-number-of-non-overlapping-palindrome-substrings/discuss/2808845/Python3-DP-with-Explanations-or-Only-Check-Substrings-of-Length-k-and-k-%2B-1",
      "python_solutions": "class Solution:\n    def maxPalindromes(self, s: str, k: int) -> int:\n        n = len(s)\n        dp = [0] * (n + 1)\n        for i in range(k, n + 1):\n            dp[i] = dp[i - 1]\n            for length in range(k, k + 2):\n                j = i - length\n                if j < 0:\n                    break\n                if self.isPalindrome(s, j, i):\n                    dp[i] = max(dp[i], 1 + dp[j])\n        return dp[-1]\n    \n    \n    def isPalindrome(self, s, j, i):\n        left, right = j, i - 1\n        while left < right:\n            if s[left] != s[right]:\n                return False\n            left += 1\n            right -= 1\n        return True",
      "slug": "maximum-number-of-non-overlapping-palindrome-substrings",
      "post_title": "[Python3] DP with Explanations | Only Check Substrings of Length k and k + 1",
      "user": "xil899",
      "upvotes": 11,
      "views": 542,
      "problem_title": "maximum number of non overlapping palindrome substrings",
      "number": 2472,
      "acceptance": 0.366,
      "difficulty": "Hard",
      "__index_level_0__": 33937,
      "question": "You are given a string s and a positive integer k.\nSelect a set of non-overlapping substrings from the string s that satisfy the following conditions:\nThe length of each substring is at least k.\nEach substring is a palindrome.\nReturn the maximum number of substrings in an optimal selection.\nA substring is a contiguous sequence of characters within a string.\n  Example 1:\nInput: s = \"abaccdbbd\", k = 3\nOutput: 2\nExplanation: We can select the substrings underlined in s = \"abaccdbbd\". Both \"aba\" and \"dbbd\" are palindromes and have a length of at least k = 3.\nIt can be shown that we cannot find a selection with more than two valid substrings.\nExample 2:\nInput: s = \"adbcda\", k = 2\nOutput: 0\nExplanation: There is no palindrome substring of length at least 2 in the string.\n  Constraints:\n1 <= k <= s.length <= 2000\ns consists of lowercase English letters."
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-unequal-triplets-in-array/discuss/2834169/Python-Hashmap-O(n)-with-diagrams",
      "python_solutions": "class Solution:\n    def unequalTriplets(self, nums: List[int]) -> int:\n        c = Counter(nums)\n        res = 0\n        \n        left = 0\n        right = len(nums)\n        \n        for _, freq in c.items():\n            right -= freq\n            res += left * freq * right\n            left += freq\n        \n        return res",
      "slug": "number-of-unequal-triplets-in-array",
      "post_title": "Python Hashmap O(n) with diagrams",
      "user": "cheatcode-ninja",
      "upvotes": 10,
      "views": 242,
      "problem_title": "number of unequal triplets in array",
      "number": 2475,
      "acceptance": 0.6990000000000001,
      "difficulty": "Easy",
      "__index_level_0__": 33956,
      "question": "You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions:\n0 <= i < j < k < nums.length\nnums[i], nums[j], and nums[k] are pairwise distinct.\nIn other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k].\nReturn the number of triplets that meet the conditions.\n  Example 1:\nInput: nums = [4,4,2,4,3]\nOutput: 3\nExplanation: The following triplets meet the conditions:\n- (0, 2, 4) because 4 != 2 != 3\n- (1, 2, 4) because 4 != 2 != 3\n- (2, 3, 4) because 2 != 4 != 3\nSince there are 3 triplets, we return 3.\nNote that (2, 0, 4) is not a valid triplet because 2 > 0.\nExample 2:\nInput: nums = [1,1,1,1,1]\nOutput: 0\nExplanation: No triplets meet the conditions so we return 0.\n  Constraints:\n3 <= nums.length <= 100\n1 <= nums[i] <= 1000"
    },
    {
      "post_href": "https://leetcode.com/problems/closest-nodes-queries-in-a-binary-search-tree/discuss/2831726/Binary-Search-Approach-or-Python",
      "python_solutions": "class Solution(object):\n    def closestNodes(self, root, queries):\n        def dfs(root, arr):\n            if not root: return\n            dfs(root.left, arr)\n            arr.append(root.val)\n            dfs(root.right, arr)\n        arr = []\n        dfs(root, arr)\n        ans = []\n        n = len(arr)\n        for key in queries:\n            left, right = 0, n - 1\n            while right >= left:\n                mid = (right + left) // 2\n                if arr[mid] == key:\n                    break\n                elif arr[mid] > key:\n                    right = mid - 1\n                else:\n                    left = mid + 1\n            if arr[mid] == key:\n                ans.append([arr[mid], arr[mid]])\n            elif arr[mid] > key:\n                if (mid - 1) >= 0:\n                    ans.append([arr[mid - 1], arr[mid]])\n                else:\n                    ans.append([-1, arr[mid]])\n            else:\n                if (mid + 1) < n:\n                    ans.append([arr[mid], arr[mid + 1]])\n                else:\n                    ans.append([arr[mid], -1])\n        return ans",
      "slug": "closest-nodes-queries-in-a-binary-search-tree",
      "post_title": "Binary Search Approach | Python",
      "user": "its_krish_here",
      "upvotes": 11,
      "views": 975,
      "problem_title": "closest nodes queries in a binary search tree",
      "number": 2476,
      "acceptance": 0.4039999999999999,
      "difficulty": "Medium",
      "__index_level_0__": 33977,
      "question": "You are given the root of a binary search tree and an array queries of size n consisting of positive integers.\nFind a 2D array answer of size n where answer[i] = [mini, maxi]:\nmini is the largest value in the tree that is smaller than or equal to queries[i]. If a such value does not exist, add -1 instead.\nmaxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead.\nReturn the array answer.\n  Example 1:\nInput: root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]\nOutput: [[2,2],[4,6],[15,-1]]\nExplanation: We answer the queries in the following way:\n- The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2].\n- The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6].\n- The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1].\nExample 2:\nInput: root = [4,null,9], queries = [3]\nOutput: [[-1,4]]\nExplanation: The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].\n  Constraints:\nThe number of nodes in the tree is in the range [2, 105].\n1 <= Node.val <= 106\nn == queries.length\n1 <= n <= 105\n1 <= queries[i] <= 106"
    },
    {
      "post_href": "https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/discuss/2834516/Python-DFS-Picture-explanation-O(N)",
      "python_solutions": "class Solution:\n    def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n        n = len(roads) + 1\n        graph = defaultdict(list)\n        for a, b in roads:\n            graph[a].append(b)\n            graph[b].append(a)\n        \n        def dfs(u, p):\n            cnt = 1\n            for v in graph[u]:\n                if v == p: continue\n                cnt += dfs(v, u)\n            if u != 0:\n                self.ans += math.ceil(cnt / seats)  # number of litters for `cnt` people to travel from node `u` to node `p`\n            return cnt\n                \n        self.ans = 0\n        dfs(0, -1)\n        return self.ans",
      "slug": "minimum-fuel-cost-to-report-to-the-capital",
      "post_title": "[Python] DFS - Picture explanation - O(N)",
      "user": "hiepit",
      "upvotes": 33,
      "views": 528,
      "problem_title": "minimum fuel cost to report to the capital",
      "number": 2477,
      "acceptance": 0.53,
      "difficulty": "Medium",
      "__index_level_0__": 33984,
      "question": "There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.\nThere is a meeting for the representatives of each city. The meeting is in the capital city.\nThere is a car in each city. You are given an integer seats that indicates the number of seats in each car.\nA representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.\nReturn the minimum number of liters of fuel to reach the capital city.\n  Example 1:\nInput: roads = [[0,1],[0,2],[0,3]], seats = 5\nOutput: 3\nExplanation: \n- Representative1 goes directly to the capital with 1 liter of fuel.\n- Representative2 goes directly to the capital with 1 liter of fuel.\n- Representative3 goes directly to the capital with 1 liter of fuel.\nIt costs 3 liters of fuel at minimum. \nIt can be proven that 3 is the minimum number of liters of fuel needed.\nExample 2:\nInput: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2\nOutput: 7\nExplanation: \n- Representative2 goes directly to city 3 with 1 liter of fuel.\n- Representative2 and representative3 go together to city 1 with 1 liter of fuel.\n- Representative2 and representative3 go together to the capital with 1 liter of fuel.\n- Representative1 goes directly to the capital with 1 liter of fuel.\n- Representative5 goes directly to the capital with 1 liter of fuel.\n- Representative6 goes directly to city 4 with 1 liter of fuel.\n- Representative4 and representative6 go together to the capital with 1 liter of fuel.\nIt costs 7 liters of fuel at minimum. \nIt can be proven that 7 is the minimum number of liters of fuel needed.\nExample 3:\nInput: roads = [], seats = 1\nOutput: 0\nExplanation: No representatives need to travel to the capital city.\n  Constraints:\n1 <= n <= 105\nroads.length == n - 1\nroads[i].length == 2\n0 <= ai, bi < n\nai != bi\nroads represents a valid tree.\n1 <= seats <= 105"
    },
    {
      "post_href": "https://leetcode.com/problems/number-of-beautiful-partitions/discuss/2833244/Python-Top-down-DP-Clean-and-Concise-O(N-*-K)",
      "python_solutions": "class Solution:\n    def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:\n        n = len(s)\n        MOD = 10**9 + 7\n\n        def isPrime(c):\n            return c in ['2', '3', '5', '7']\n\n        @lru_cache(None)\n        def dp(i, k):\n            if k == 0 and i <= n:\n                return 1\n            if i >= n:\n                return 0\n\n            ans = dp(i+1, k)  # Skip\n            if isPrime(s[i]) and not isPrime(s[i-1]):  # Split\n                ans += dp(i+minLength, k-1)\n            return ans % MOD\n\n        if not isPrime(s[0]) or isPrime(s[-1]): return 0\n\n        return dp(minLength, k-1)",
      "slug": "number-of-beautiful-partitions",
      "post_title": "[Python] Top down DP - Clean & Concise - O(N * K)",
      "user": "hiepit",
      "upvotes": 21,
      "views": 382,
      "problem_title": "number of beautiful partitions",
      "number": 2478,
      "acceptance": 0.294,
      "difficulty": "Hard",
      "__index_level_0__": 33997,
      "question": "You are given a string s that consists of the digits '1' to '9' and two integers k and minLength.\nA partition of s is called beautiful if:\ns is partitioned into k non-intersecting substrings.\nEach substring has a length of at least minLength.\nEach substring starts with a prime digit and ends with a non-prime digit. Prime digits are '2', '3', '5', and '7', and the rest of the digits are non-prime.\nReturn the number of beautiful partitions of s. Since the answer may be very large, return it modulo 109 + 7.\nA substring is a contiguous sequence of characters within a string.\n  Example 1:\nInput: s = \"23542185131\", k = 3, minLength = 2\nOutput: 3\nExplanation: There exists three ways to create a beautiful partition:\n\"2354 | 218 | 5131\"\n\"2354 | 21851 | 31\"\n\"2354218 | 51 | 31\"\nExample 2:\nInput: s = \"23542185131\", k = 3, minLength = 3\nOutput: 1\nExplanation: There exists one way to create a beautiful partition: \"2354 | 218 | 5131\".\nExample 3:\nInput: s = \"3312958\", k = 3, minLength = 1\nOutput: 1\nExplanation: There exists one way to create a beautiful partition: \"331 | 29 | 58\".\n  Constraints:\n1 <= k, minLength <= s.length <= 1000\ns consists of the digits '1' to '9'."
    }
  ]