diff --git "a/data.json" "b/data.json" deleted file mode 100644--- "a/data.json" +++ /dev/null @@ -1,12104 +0,0 @@ -[ - { - "number": 1, - "title": "Two Sum", - "question": "class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n \"\"\"\n Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n You may assume that each input would have exactly one solution, and you may not use the same element twice.\n You can return the answer in any order.\n Example 1:\n Input: nums = [2,7,11,15], target = 9\n Output: [0,1]\n Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].\n Example 2:\n Input: nums = [3,2,4], target = 6\n Output: [1,2]\n Example 3:\n Input: nums = [3,3], target = 6\n Output: [0,1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2, - "title": "Add Two Numbers", - "question": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n 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.\n You may assume the two numbers do not contain any leading zero, except the number 0 itself.\n Example 1:\n Input: l1 = [2,4,3], l2 = [5,6,4]\n Output: [7,0,8]\n Explanation: 342 + 465 = 807.\n Example 2:\n Input: l1 = [0], l2 = [0]\n Output: [0]\n Example 3:\n Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\n Output: [8,9,9,9,0,0,0,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 3, - "title": "Longest Substring Without Repeating Characters", - "question": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n \"\"\"\n Given a string s, find the length of the longest substring without repeating characters.\n Example 1:\n Input: s = \"abcabcbb\"\n Output: 3\n Explanation: The answer is \"abc\", with the length of 3.\n Example 2:\n Input: s = \"bbbbb\"\n Output: 1\n Explanation: The answer is \"b\", with the length of 1.\n Example 3:\n Input: s = \"pwwkew\"\n Output: 3\n Explanation: The answer is \"wke\", with the length of 3.\n Notice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 4, - "title": "Median of Two Sorted Arrays", - "question": "class Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n \"\"\"\n Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.\n The overall run time complexity should be O(log (m+n)).\n Example 1:\n Input: nums1 = [1,3], nums2 = [2]\n Output: 2.00000\n Explanation: merged array = [1,2,3] and median is 2.\n Example 2:\n Input: nums1 = [1,2], nums2 = [3,4]\n Output: 2.50000\n Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 5, - "title": "Longest Palindromic Substring", - "question": "class Solution:\n def longestPalindrome(self, s: str) -> str:\n \"\"\"\n Given a string s, return the longest palindromic substring in s.\n Example 1:\n Input: s = \"babad\"\n Output: \"bab\"\n Explanation: \"aba\" is also a valid answer.\n Example 2:\n Input: s = \"cbbd\"\n Output: \"bb\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 6, - "title": "Zigzag Conversion", - "question": "class Solution:\n def convert(self, s: str, numRows: int) -> str:\n \"\"\"\n 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)\n P A H N\n A P L S I I G\n Y I R\n And then read line by line: \"PAHNAPLSIIGYIR\"\n Write the code that will take a string and make this conversion given a number of rows:\n string convert(string s, int numRows);\n Example 1:\n Input: s = \"PAYPALISHIRING\", numRows = 3\n Output: \"PAHNAPLSIIGYIR\"\n Example 2:\n Input: s = \"PAYPALISHIRING\", numRows = 4\n Output: \"PINALSIGYAHRPI\"\n Explanation:\n P I N\n A L S I G\n Y A H R\n P I\n Example 3:\n Input: s = \"A\", numRows = 1\n Output: \"A\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 7, - "title": "Reverse Integer", - "question": "class Solution:\n def reverse(self, x: int) -> int:\n \"\"\"\n 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.\n Assume the environment does not allow you to store 64-bit integers (signed or unsigned).\n Example 1:\n Input: x = 123\n Output: 321\n Example 2:\n Input: x = -123\n Output: -321\n Example 3:\n Input: x = 120\n Output: 21\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 8, - "title": "String to Integer (atoi)", - "question": "class Solution:\n def myAtoi(self, s: str) -> int:\n \"\"\"\n Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi function).\n The algorithm for myAtoi(string s) is as follows:\n Read in and ignore any leading whitespace.\n Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.\n Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.\n Convert these digits into an integer (i.e. \"123\" -> 123, \"0032\" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).\n If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.\n Return the integer as the final result.\n Note:\n Only the space character ' ' is considered a whitespace character.\n Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.\n Example 1:\n Input: s = \"42\"\n Output: 42\n Explanation: The underlined characters are what is read in, the caret is the current reader position.\n Step 1: \"42\" (no characters read because there is no leading whitespace)\n ^\n Step 2: \"42\" (no characters read because there is neither a '-' nor '+')\n ^\n Step 3: \"42\" (\"42\" is read in)\n ^\n The parsed integer is 42.\n Since 42 is in the range [-231, 231 - 1], the final result is 42.\n Example 2:\n Input: s = \" -42\"\n Output: -42\n Explanation:\n Step 1: \" -42\" (leading whitespace is read and ignored)\n ^\n Step 2: \" -42\" ('-' is read, so the result should be negative)\n ^\n Step 3: \" -42\" (\"42\" is read in)\n ^\n The parsed integer is -42.\n Since -42 is in the range [-231, 231 - 1], the final result is -42.\n Example 3:\n Input: s = \"4193 with words\"\n Output: 4193\n Explanation:\n Step 1: \"4193 with words\" (no characters read because there is no leading whitespace)\n ^\n Step 2: \"4193 with words\" (no characters read because there is neither a '-' nor '+')\n ^\n Step 3: \"4193 with words\" (\"4193\" is read in; reading stops because the next character is a non-digit)\n ^\n The parsed integer is 4193.\n Since 4193 is in the range [-231, 231 - 1], the final result is 4193.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 9, - "title": "Palindrome Number", - "question": "class Solution:\n def isPalindrome(self, x: int) -> bool:\n \"\"\"\n Given an integer x, return true if x is a palindrome, and false otherwise.\n Example 1:\n Input: x = 121\n Output: true\n Explanation: 121 reads as 121 from left to right and from right to left.\n Example 2:\n Input: x = -121\n Output: false\n Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.\n Example 3:\n Input: x = 10\n Output: false\n Explanation: Reads 01 from right to left. Therefore it is not a palindrome.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 10, - "title": "Regular Expression Matching", - "question": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n \"\"\"\n Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:\n '.' Matches any single character.\u200b\u200b\u200b\u200b\n '*' Matches zero or more of the preceding element.\n The matching should cover the entire input string (not partial).\n Example 1:\n Input: s = \"aa\", p = \"a\"\n Output: false\n Explanation: \"a\" does not match the entire string \"aa\".\n Example 2:\n Input: s = \"aa\", p = \"a*\"\n Output: true\n Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes \"aa\".\n Example 3:\n Input: s = \"ab\", p = \".*\"\n Output: true\n Explanation: \".*\" means \"zero or more (*) of any character (.)\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 11, - "title": "Container With Most Water", - "question": "class Solution:\n def maxArea(self, height: List[int]) -> int:\n \"\"\"\n 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]).\n Find two lines that together with the x-axis form a container, such that the container contains the most water.\n Return the maximum amount of water a container can store.\n Notice that you may not slant the container.\n Example 1:\n Input: height = [1,8,6,2,5,4,8,3,7]\n Output: 49\n Explanation: 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.\n Example 2:\n Input: height = [1,1]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 12, - "title": "Integer to Roman", - "question": "class Solution:\n def intToRoman(self, num: int) -> str:\n \"\"\"\n Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.\n Symbol Value\n I 1\n V 5\n X 10\n L 50\n C 100\n D 500\n M 1000\n For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.\n Roman 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:\n I can be placed before V (5) and X (10) to make 4 and 9. \n X can be placed before L (50) and C (100) to make 40 and 90. \n C can be placed before D (500) and M (1000) to make 400 and 900.\n Given an integer, convert it to a roman numeral.\n Example 1:\n Input: num = 3\n Output: \"III\"\n Explanation: 3 is represented as 3 ones.\n Example 2:\n Input: num = 58\n Output: \"LVIII\"\n Explanation: L = 50, V = 5, III = 3.\n Example 3:\n Input: num = 1994\n Output: \"MCMXCIV\"\n Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 13, - "title": "Roman to Integer", - "question": "class Solution:\n def romanToInt(self, s: str) -> int:\n \"\"\"\n Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.\n Symbol Value\n I 1\n V 5\n X 10\n L 50\n C 100\n D 500\n M 1000\n For 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.\n Roman 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:\n I can be placed before V (5) and X (10) to make 4 and 9. \n X can be placed before L (50) and C (100) to make 40 and 90. \n C can be placed before D (500) and M (1000) to make 400 and 900.\n Given a roman numeral, convert it to an integer.\n Example 1:\n Input: s = \"III\"\n Output: 3\n Explanation: III = 3.\n Example 2:\n Input: s = \"LVIII\"\n Output: 58\n Explanation: L = 50, V= 5, III = 3.\n Example 3:\n Input: s = \"MCMXCIV\"\n Output: 1994\n Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 14, - "title": "Longest Common Prefix", - "question": "class Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n \"\"\"\n Write a function to find the longest common prefix string amongst an array of strings.\n If there is no common prefix, return an empty string \"\".\n Example 1:\n Input: strs = [\"flower\",\"flow\",\"flight\"]\n Output: \"fl\"\n Example 2:\n Input: strs = [\"dog\",\"racecar\",\"car\"]\n Output: \"\"\n Explanation: There is no common prefix among the input strings.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 15, - "title": "3Sum", - "question": "class Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n \"\"\"\n Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.\n Notice that the solution set must not contain duplicate triplets.\n Example 1:\n Input: nums = [-1,0,1,2,-1,-4]\n Output: [[-1,-1,2],[-1,0,1]]\n Explanation: \n nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.\n nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.\n nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.\n The distinct triplets are [-1,0,1] and [-1,-1,2].\n Notice that the order of the output and the order of the triplets does not matter.\n Example 2:\n Input: nums = [0,1,1]\n Output: []\n Explanation: The only possible triplet does not sum up to 0.\n Example 3:\n Input: nums = [0,0,0]\n Output: [[0,0,0]]\n Explanation: The only possible triplet sums up to 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 16, - "title": "3Sum Closest", - "question": "class Solution:\n def threeSumClosest(self, nums: List[int], target: int) -> int:\n \"\"\"\n Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.\n Return the sum of the three integers.\n You may assume that each input would have exactly one solution.\n Example 1:\n Input: nums = [-1,2,1,-4], target = 1\n Output: 2\n Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).\n Example 2:\n Input: nums = [0,0,0], target = 1\n Output: 0\n Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 17, - "title": "Letter Combinations of a Phone Number", - "question": "class Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n \"\"\"\n Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.\n A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.\n Example 1:\n Input: digits = \"23\"\n Output: [\"ad\",\"ae\",\"af\",\"bd\",\"be\",\"bf\",\"cd\",\"ce\",\"cf\"]\n Example 2:\n Input: digits = \"\"\n Output: []\n Example 3:\n Input: digits = \"2\"\n Output: [\"a\",\"b\",\"c\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 18, - "title": "4Sum", - "question": "class Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n \"\"\"\n Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:\n 0 <= a, b, c, d < n\n a, b, c, and d are distinct.\n nums[a] + nums[b] + nums[c] + nums[d] == target\n You may return the answer in any order.\n Example 1:\n Input: nums = [1,0,-1,0,-2,2], target = 0\n Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]\n Example 2:\n Input: nums = [2,2,2,2,2], target = 8\n Output: [[2,2,2,2]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 19, - "title": "Remove Nth Node From End of List", - "question": "class Solution:\n def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list, remove the nth node from the end of the list and return its head.\n Example 1:\n Input: head = [1,2,3,4,5], n = 2\n Output: [1,2,3,5]\n Example 2:\n Input: head = [1], n = 1\n Output: []\n Example 3:\n Input: head = [1,2], n = 1\n Output: [1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 20, - "title": "Valid Parentheses", - "question": "class Solution:\n def isValid(self, s: str) -> bool:\n \"\"\"\n Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n An input string is valid if:\n Open brackets must be closed by the same type of brackets.\n Open brackets must be closed in the correct order.\n Every close bracket has a corresponding open bracket of the same type.\n Example 1:\n Input: s = \"()\"\n Output: true\n Example 2:\n Input: s = \"()[]{}\"\n Output: true\n Example 3:\n Input: s = \"(]\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 21, - "title": "Merge Two Sorted Lists", - "question": "class Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n You are given the heads of two sorted linked lists list1 and list2.\n Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.\n Return the head of the merged linked list.\n Example 1:\n Input: list1 = [1,2,4], list2 = [1,3,4]\n Output: [1,1,2,3,4,4]\n Example 2:\n Input: list1 = [], list2 = []\n Output: []\n Example 3:\n Input: list1 = [], list2 = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 22, - "title": "Generate Parentheses", - "question": "class Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n \"\"\"\n Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.\n Example 1:\n Input: n = 3\n Output: [\"((()))\",\"(()())\",\"(())()\",\"()(())\",\"()()()\"]\n Example 2:\n Input: n = 1\n Output: [\"()\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 23, - "title": "Merge k Sorted Lists", - "question": "class Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n \"\"\"\n You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.\n Merge all the linked-lists into one sorted linked-list and return it.\n Example 1:\n Input: lists = [[1,4,5],[1,3,4],[2,6]]\n Output: [1,1,2,3,4,4,5,6]\n Explanation: The linked-lists are:\n [\n 1->4->5,\n 1->3->4,\n 2->6\n ]\n merging them into one sorted list:\n 1->1->2->3->4->4->5->6\n Example 2:\n Input: lists = []\n Output: []\n Example 3:\n Input: lists = [[]]\n Output: []\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 24, - "title": "Swap Nodes in Pairs", - "question": "class Solution:\n def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)\n Example 1:\n Input: head = [1,2,3,4]\n Output: [2,1,4,3]\n Example 2:\n Input: head = []\n Output: []\n Example 3:\n Input: head = [1]\n Output: [1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 25, - "title": "Reverse Nodes in k-Group", - "question": "class Solution:\n def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.\n k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.\n You may not alter the values in the list's nodes, only nodes themselves may be changed.\n Example 1:\n Input: head = [1,2,3,4,5], k = 2\n Output: [2,1,4,3,5]\n Example 2:\n Input: head = [1,2,3,4,5], k = 3\n Output: [3,2,1,4,5]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 26, - "title": "Remove Duplicates from Sorted Array", - "question": "class Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.\n Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.\n Return k after placing the final result in the first k slots of nums.\n Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.\n Custom Judge:\n The judge will test your solution with the following code:\n int[] nums = [...]; // Input array\n int[] expectedNums = [...]; // The expected answer with correct length\n int k = removeDuplicates(nums); // Calls your implementation\n assert k == expectedNums.length;\n for (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n }\n If all assertions pass, then your solution will be accepted.\n Example 1:\n Input: nums = [1,1,2]\n Output: 2, nums = [1,2,_]\n Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.\n It does not matter what you leave beyond the returned k (hence they are underscores).\n Example 2:\n Input: nums = [0,0,1,1,1,2,2,3,3,4]\n Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]\n Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.\n It does not matter what you leave beyond the returned k (hence they are underscores).\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 27, - "title": "Remove Element", - "question": "class Solution:\n def removeElement(self, nums: List[int], val: int) -> int:\n \"\"\"\n Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.\n Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.\n Return k after placing the final result in the first k slots of nums.\n Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.\n Custom Judge:\n The judge will test your solution with the following code:\n int[] nums = [...]; // Input array\n int val = ...; // Value to remove\n int[] expectedNums = [...]; // The expected answer with correct length.\n // It is sorted with no values equaling val.\n int k = removeElement(nums, val); // Calls your implementation\n assert k == expectedNums.length;\n sort(nums, 0, k); // Sort the first k elements of nums\n for (int i = 0; i < actualLength; i++) {\n assert nums[i] == expectedNums[i];\n }\n If all assertions pass, then your solution will be accepted.\n Example 1:\n Input: nums = [3,2,2,3], val = 3\n Output: 2, nums = [2,2,_,_]\n Explanation: Your function should return k = 2, with the first two elements of nums being 2.\n It does not matter what you leave beyond the returned k (hence they are underscores).\n Example 2:\n Input: nums = [0,1,2,2,3,0,4,2], val = 2\n Output: 5, nums = [0,1,4,0,3,_,_,_]\n Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.\n Note that the five elements can be returned in any order.\n It does not matter what you leave beyond the returned k (hence they are underscores).\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 28, - "title": "Find the Index of the First Occurrence in a String", - "question": "class Solution:\n def strStr(self, haystack: str, needle: str) -> int:\n \"\"\"\n Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n Example 1:\n Input: haystack = \"sadbutsad\", needle = \"sad\"\n Output: 0\n Explanation: \"sad\" occurs at index 0 and 6.\n The first occurrence is at index 0, so we return 0.\n Example 2:\n Input: haystack = \"leetcode\", needle = \"leeto\"\n Output: -1\n Explanation: \"leeto\" did not occur in \"leetcode\", so we return -1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 29, - "title": "Divide Two Integers", - "question": "class Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n \"\"\"\n Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.\n The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2.\n Return the quotient after dividing dividend by divisor.\n Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [\u2212231, 231 \u2212 1]. For this problem, if the quotient is strictly greater than 231 - 1, then return 231 - 1, and if the quotient is strictly less than -231, then return -231.\n Example 1:\n Input: dividend = 10, divisor = 3\n Output: 3\n Explanation: 10/3 = 3.33333.. which is truncated to 3.\n Example 2:\n Input: dividend = 7, divisor = -3\n Output: -2\n Explanation: 7/-3 = -2.33333.. which is truncated to -2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 30, - "title": "Substring with Concatenation of All Words", - "question": "class Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n \"\"\"\n You are given a string s and an array of strings words. All the strings of words are of the same length.\n A concatenated substring in s is a substring that contains all the strings of any permutation of words concatenated.\n For example, if words = [\"ab\",\"cd\",\"ef\"], then \"abcdef\", \"abefcd\", \"cdabef\", \"cdefab\", \"efabcd\", and \"efcdab\" are all concatenated strings. \"acdbef\" is not a concatenated substring because it is not the concatenation of any permutation of words.\n Return the starting indices of all the concatenated substrings in s. You can return the answer in any order.\n Example 1:\n Input: s = \"barfoothefoobarman\", words = [\"foo\",\"bar\"]\n Output: [0,9]\n Explanation: Since words.length == 2 and words[i].length == 3, the concatenated substring has to be of length 6.\n The substring starting at 0 is \"barfoo\". It is the concatenation of [\"bar\",\"foo\"] which is a permutation of words.\n The substring starting at 9 is \"foobar\". It is the concatenation of [\"foo\",\"bar\"] which is a permutation of words.\n The output order does not matter. Returning [9,0] is fine too.\n Example 2:\n Input: s = \"wordgoodgoodgoodbestword\", words = [\"word\",\"good\",\"best\",\"word\"]\n Output: []\n Explanation: Since words.length == 4 and words[i].length == 4, the concatenated substring has to be of length 16.\n There is no substring of length 16 is s that is equal to the concatenation of any permutation of words.\n We return an empty array.\n Example 3:\n Input: s = \"barfoofoobarthefoobarman\", words = [\"bar\",\"foo\",\"the\"]\n Output: [6,9,12]\n Explanation: Since words.length == 3 and words[i].length == 3, the concatenated substring has to be of length 9.\n The substring starting at 6 is \"foobarthe\". It is the concatenation of [\"foo\",\"bar\",\"the\"] which is a permutation of words.\n The substring starting at 9 is \"barthefoo\". It is the concatenation of [\"bar\",\"the\",\"foo\"] which is a permutation of words.\n The substring starting at 12 is \"thefoobar\". It is the concatenation of [\"the\",\"foo\",\"bar\"] which is a permutation of words.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 31, - "title": "Next Permutation", - "question": "class Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n A permutation of an array of integers is an arrangement of its members into a sequence or linear order.\n For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].\n The next permutation of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).\n For example, the next permutation of arr = [1,2,3] is [1,3,2].\n Similarly, the next permutation of arr = [2,3,1] is [3,1,2].\n While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement.\n Given an array of integers nums, find the next permutation of nums.\n The replacement must be in place and use only constant extra memory.\n Example 1:\n Input: nums = [1,2,3]\n Output: [1,3,2]\n Example 2:\n Input: nums = [3,2,1]\n Output: [1,2,3]\n Example 3:\n Input: nums = [1,1,5]\n Output: [1,5,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 32, - "title": "Longest Valid Parentheses", - "question": "class Solution:\n def longestValidParentheses(self, s: str) -> int:\n \"\"\"\n Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring.\n Example 1:\n Input: s = \"(()\"\n Output: 2\n Explanation: The longest valid parentheses substring is \"()\".\n Example 2:\n Input: s = \")()())\"\n Output: 4\n Explanation: The longest valid parentheses substring is \"()()\".\n Example 3:\n Input: s = \"\"\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 33, - "title": "Search in Rotated Sorted Array", - "question": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n \"\"\"\n There is an integer array nums sorted in ascending order (with distinct values).\n Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].\n Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.\n You must write an algorithm with O(log n) runtime complexity.\n Example 1:\n Input: nums = [4,5,6,7,0,1,2], target = 0\n Output: 4\n Example 2:\n Input: nums = [4,5,6,7,0,1,2], target = 3\n Output: -1\n Example 3:\n Input: nums = [1], target = 0\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 34, - "title": "Find First and Last Position of Element in Sorted Array", - "question": "class Solution:\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n \"\"\"\n Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.\n If target is not found in the array, return [-1, -1].\n You must write an algorithm with O(log n) runtime complexity.\n Example 1:\n Input: nums = [5,7,7,8,8,10], target = 8\n Output: [3,4]\n Example 2:\n Input: nums = [5,7,7,8,8,10], target = 6\n Output: [-1,-1]\n Example 3:\n Input: nums = [], target = 0\n Output: [-1,-1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 35, - "title": "Search Insert Position", - "question": "class Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n \"\"\"\n Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n You must write an algorithm with O(log n) runtime complexity.\n Example 1:\n Input: nums = [1,3,5,6], target = 5\n Output: 2\n Example 2:\n Input: nums = [1,3,5,6], target = 2\n Output: 1\n Example 3:\n Input: nums = [1,3,5,6], target = 7\n Output: 4\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 36, - "title": "Valid Sudoku", - "question": "class Solution:\n def isValidSudoku(self, board: List[List[str]]) -> bool:\n \"\"\"\n Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:\n Each row must contain the digits 1-9 without repetition.\n Each column must contain the digits 1-9 without repetition.\n Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.\n Note:\n A Sudoku board (partially filled) could be valid but is not necessarily solvable.\n Only the filled cells need to be validated according to the mentioned rules.\n Example 1:\n Input: board = \n [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n ,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n ,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n ,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n ,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n ,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n ,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n ,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n ,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\n Output: true\n Example 2:\n Input: board = \n [[\"8\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"]\n ,[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"]\n ,[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"]\n ,[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"]\n ,[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"]\n ,[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"]\n ,[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"]\n ,[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"]\n ,[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\n Output: false\n Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 37, - "title": "Sudoku Solver", - "question": "class Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n Write a program to solve a Sudoku puzzle by filling the empty cells.\n A sudoku solution must satisfy all of the following rules:\n Each of the digits 1-9 must occur exactly once in each row.\n Each of the digits 1-9 must occur exactly once in each column.\n Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.\n The '.' character indicates empty cells.\n Example 1:\n Input: board = [[\"5\",\"3\",\".\",\".\",\"7\",\".\",\".\",\".\",\".\"],[\"6\",\".\",\".\",\"1\",\"9\",\"5\",\".\",\".\",\".\"],[\".\",\"9\",\"8\",\".\",\".\",\".\",\".\",\"6\",\".\"],[\"8\",\".\",\".\",\".\",\"6\",\".\",\".\",\".\",\"3\"],[\"4\",\".\",\".\",\"8\",\".\",\"3\",\".\",\".\",\"1\"],[\"7\",\".\",\".\",\".\",\"2\",\".\",\".\",\".\",\"6\"],[\".\",\"6\",\".\",\".\",\".\",\".\",\"2\",\"8\",\".\"],[\".\",\".\",\".\",\"4\",\"1\",\"9\",\".\",\".\",\"5\"],[\".\",\".\",\".\",\".\",\"8\",\".\",\".\",\"7\",\"9\"]]\n Output: [[\"5\",\"3\",\"4\",\"6\",\"7\",\"8\",\"9\",\"1\",\"2\"],[\"6\",\"7\",\"2\",\"1\",\"9\",\"5\",\"3\",\"4\",\"8\"],[\"1\",\"9\",\"8\",\"3\",\"4\",\"2\",\"5\",\"6\",\"7\"],[\"8\",\"5\",\"9\",\"7\",\"6\",\"1\",\"4\",\"2\",\"3\"],[\"4\",\"2\",\"6\",\"8\",\"5\",\"3\",\"7\",\"9\",\"1\"],[\"7\",\"1\",\"3\",\"9\",\"2\",\"4\",\"8\",\"5\",\"6\"],[\"9\",\"6\",\"1\",\"5\",\"3\",\"7\",\"2\",\"8\",\"4\"],[\"2\",\"8\",\"7\",\"4\",\"1\",\"9\",\"6\",\"3\",\"5\"],[\"3\",\"4\",\"5\",\"2\",\"8\",\"6\",\"1\",\"7\",\"9\"]]\n Explanation: The input board is shown above and the only valid solution is shown below:\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 38, - "title": "Count and Say", - "question": "class Solution:\n def countAndSay(self, n: int) -> str:\n \"\"\"\n The count-and-say sequence is a sequence of digit strings defined by the recursive formula:\n countAndSay(1) = \"1\"\n countAndSay(n) is the way you would \"say\" the digit string from countAndSay(n-1), which is then converted into a different digit string.\n To determine how you \"say\" a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.\n For example, the saying and conversion for digit string \"3322251\":\n Given a positive integer n, return the nth term of the count-and-say sequence.\n Example 1:\n Input: n = 1\n Output: \"1\"\n Explanation: This is the base case.\n Example 2:\n Input: n = 4\n Output: \"1211\"\n Explanation:\n countAndSay(1) = \"1\"\n countAndSay(2) = say \"1\" = one 1 = \"11\"\n countAndSay(3) = say \"11\" = two 1's = \"21\"\n countAndSay(4) = say \"21\" = one 2 + one 1 = \"12\" + \"11\" = \"1211\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 39, - "title": "Combination Sum", - "question": "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n \"\"\"\n Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.\n The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.\n The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.\n Example 1:\n Input: candidates = [2,3,6,7], target = 7\n Output: [[2,2,3],[7]]\n Explanation:\n 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.\n 7 is a candidate, and 7 = 7.\n These are the only two combinations.\n Example 2:\n Input: candidates = [2,3,5], target = 8\n Output: [[2,2,2,2],[2,3,3],[3,5]]\n Example 3:\n Input: candidates = [2], target = 1\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 40, - "title": "Combination Sum II", - "question": "class Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n \"\"\"\n Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.\n Each number in candidates may only be used once in the combination.\n Note: The solution set must not contain duplicate combinations.\n Example 1:\n Input: candidates = [10,1,2,7,6,1,5], target = 8\n Output: \n [\n [1,1,6],\n [1,2,5],\n [1,7],\n [2,6]\n ]\n Example 2:\n Input: candidates = [2,5,2,1,2], target = 5\n Output: \n [\n [1,2,2],\n [5]\n ]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 41, - "title": "First Missing Positive", - "question": "class Solution:\n def firstMissingPositive(self, nums: List[int]) -> int:\n \"\"\"\n Given an unsorted integer array nums, return the smallest missing positive integer.\n You must implement an algorithm that runs in O(n) time and uses constant extra space.\n Example 1:\n Input: nums = [1,2,0]\n Output: 3\n Explanation: The numbers in the range [1,2] are all in the array.\n Example 2:\n Input: nums = [3,4,-1,1]\n Output: 2\n Explanation: 1 is in the array but 2 is missing.\n Example 3:\n Input: nums = [7,8,9,11,12]\n Output: 1\n Explanation: The smallest positive integer 1 is missing.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 42, - "title": "Trapping Rain Water", - "question": "class Solution:\n def trap(self, height: List[int]) -> int:\n \"\"\"\n Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.\n Example 1:\n Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]\n Output: 6\n Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.\n Example 2:\n Input: height = [4,2,0,3,2,5]\n Output: 9\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 43, - "title": "Multiply Strings", - "question": "class Solution:\n def multiply(self, num1: str, num2: str) -> str:\n \"\"\"\n Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.\n Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.\n Example 1:\n Input: num1 = \"2\", num2 = \"3\"\n Output: \"6\"\n Example 2:\n Input: num1 = \"123\", num2 = \"456\"\n Output: \"56088\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 44, - "title": "Wildcard Matching", - "question": "class Solution:\n def isMatch(self, s: str, p: str) -> bool:\n \"\"\"\n Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:\n '?' Matches any single character.\n '*' Matches any sequence of characters (including the empty sequence).\n The matching should cover the entire input string (not partial).\n Example 1:\n Input: s = \"aa\", p = \"a\"\n Output: false\n Explanation: \"a\" does not match the entire string \"aa\".\n Example 2:\n Input: s = \"aa\", p = \"*\"\n Output: true\n Explanation: '*' matches any sequence.\n Example 3:\n Input: s = \"cb\", p = \"?a\"\n Output: false\n Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 45, - "title": "Jump Game II", - "question": "class Solution:\n def jump(self, nums: List[int]) -> int:\n \"\"\"\n You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].\n Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:\n 0 <= j <= nums[i] and\n i + j < n\n Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].\n Example 1:\n Input: nums = [2,3,1,1,4]\n Output: 2\n Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.\n Example 2:\n Input: nums = [2,3,0,1,4]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 46, - "title": "Permutations", - "question": "class Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n \"\"\"\n Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.\n Example 1:\n Input: nums = [1,2,3]\n Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n Example 2:\n Input: nums = [0,1]\n Output: [[0,1],[1,0]]\n Example 3:\n Input: nums = [1]\n Output: [[1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 47, - "title": "Permutations II", - "question": "class Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n \"\"\"\n Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.\n Example 1:\n Input: nums = [1,1,2]\n Output:\n [[1,1,2],\n [1,2,1],\n [2,1,1]]\n Example 2:\n Input: nums = [1,2,3]\n Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 48, - "title": "Rotate Image", - "question": "class Solution:\n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).\n You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.\n Example 1:\n Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]\n Output: [[7,4,1],[8,5,2],[9,6,3]]\n Example 2:\n Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]\n Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 49, - "title": "Group Anagrams", - "question": "class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n \"\"\"\n Given an array of strings strs, group the anagrams together. You can return the answer in any order.\n An 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:\n Input: strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"]\n Output: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]]\n Example 2:\n Input: strs = [\"\"]\n Output: [[\"\"]]\n Example 3:\n Input: strs = [\"a\"]\n Output: [[\"a\"]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 50, - "title": "Pow(x, n)", - "question": "class Solution:\n def myPow(self, x: float, n: int) -> float:\n \"\"\"\n Implement pow(x, n), which calculates x raised to the power n (i.e., xn).\n Example 1:\n Input: x = 2.00000, n = 10\n Output: 1024.00000\n Example 2:\n Input: x = 2.10000, n = 3\n Output: 9.26100\n Example 3:\n Input: x = 2.00000, n = -2\n Output: 0.25000\n Explanation: 2-2 = 1/22 = 1/4 = 0.25\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 51, - "title": "N-Queens", - "question": "class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n \"\"\"\n The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.\n Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.\n Example 1:\n Input: n = 4\n Output: [[\".Q..\",\"...Q\",\"Q...\",\"..Q.\"],[\"..Q.\",\"Q...\",\"...Q\",\".Q..\"]]\n Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above\n Example 2:\n Input: n = 1\n Output: [[\"Q\"]]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 52, - "title": "N-Queens II", - "question": "class Solution:\n def totalNQueens(self, n: int) -> int:\n \"\"\"\n The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.\n Given an integer n, return the number of distinct solutions to the n-queens puzzle.\n Example 1:\n Input: n = 4\n Output: 2\n Explanation: There are two distinct solutions to the 4-queens puzzle as shown.\n Example 2:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 53, - "title": "Maximum Subarray", - "question": "class Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, find the subarray with the largest sum, and return its sum.\n Example 1:\n Input: nums = [-2,1,-3,4,-1,2,1,-5,4]\n Output: 6\n Explanation: The subarray [4,-1,2,1] has the largest sum 6.\n Example 2:\n Input: nums = [1]\n Output: 1\n Explanation: The subarray [1] has the largest sum 1.\n Example 3:\n Input: nums = [5,4,-1,7,8]\n Output: 23\n Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 54, - "title": "Spiral Matrix", - "question": "class Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n \"\"\"\n Given an m x n matrix, return all elements of the matrix in spiral order.\n Example 1:\n Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]\n Output: [1,2,3,6,9,8,7,4,5]\n Example 2:\n Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n Output: [1,2,3,4,8,12,11,10,9,5,6,7]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 55, - "title": "Jump Game", - "question": "class Solution:\n def canJump(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.\n Return true if you can reach the last index, or false otherwise.\n Example 1:\n Input: nums = [2,3,1,1,4]\n Output: true\n Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.\n Example 2:\n Input: nums = [3,2,1,0,4]\n Output: false\n Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 56, - "title": "Merge Intervals", - "question": "class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.\n Example 1:\n Input: intervals = [[1,3],[2,6],[8,10],[15,18]]\n Output: [[1,6],[8,10],[15,18]]\n Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].\n Example 2:\n Input: intervals = [[1,4],[4,5]]\n Output: [[1,5]]\n Explanation: Intervals [1,4] and [4,5] are considered overlapping.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 57, - "title": "Insert Interval", - "question": "class Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n \"\"\"\n You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.\n Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).\n Return intervals after the insertion.\n Example 1:\n Input: intervals = [[1,3],[6,9]], newInterval = [2,5]\n Output: [[1,5],[6,9]]\n Example 2:\n Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]\n Output: [[1,2],[3,10],[12,16]]\n Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 58, - "title": "Length of Last Word", - "question": "class Solution:\n def lengthOfLastWord(self, s: str) -> int:\n \"\"\"\n Given a string s consisting of words and spaces, return the length of the last word in the string.\n A word is a maximal substring consisting of non-space characters only.\n Example 1:\n Input: s = \"Hello World\"\n Output: 5\n Explanation: The last word is \"World\" with length 5.\n Example 2:\n Input: s = \" fly me to the moon \"\n Output: 4\n Explanation: The last word is \"moon\" with length 4.\n Example 3:\n Input: s = \"luffy is still joyboy\"\n Output: 6\n Explanation: The last word is \"joyboy\" with length 6.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 59, - "title": "Spiral Matrix II", - "question": "class Solution:\n def generateMatrix(self, n: int) -> List[List[int]]:\n \"\"\"\n Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.\n Example 1:\n Input: n = 3\n Output: [[1,2,3],[8,9,4],[7,6,5]]\n Example 2:\n Input: n = 1\n Output: [[1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 60, - "title": "Permutation Sequence", - "question": "class Solution:\n def getPermutation(self, n: int, k: int) -> str:\n \"\"\"\n The set [1, 2, 3, ..., n] contains a total of n! unique permutations.\n By listing and labeling all of the permutations in order, we get the following sequence for n = 3:\n \"123\"\n \"132\"\n \"213\"\n \"231\"\n \"312\"\n \"321\"\n Given n and k, return the kth permutation sequence.\n Example 1:\n Input: n = 3, k = 3\n Output: \"213\"\n Example 2:\n Input: n = 4, k = 9\n Output: \"2314\"\n Example 3:\n Input: n = 3, k = 1\n Output: \"123\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 61, - "title": "Rotate List", - "question": "class Solution:\n def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list, rotate the list to the right by k places.\n Example 1:\n Input: head = [1,2,3,4,5], k = 2\n Output: [4,5,1,2,3]\n Example 2:\n Input: head = [0,1,2], k = 4\n Output: [2,0,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 62, - "title": "Unique Paths", - "question": "class Solution:\n def uniquePaths(self, m: int, n: int) -> int:\n \"\"\"\n There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.\n Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.\n The test cases are generated so that the answer will be less than or equal to 2 * 109.\n Example 1:\n Input: m = 3, n = 7\n Output: 28\n Example 2:\n Input: m = 3, n = 2\n Output: 3\n Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:\n 1. Right -> Down -> Down\n 2. Down -> Down -> Right\n 3. Down -> Right -> Down\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 63, - "title": "Unique Paths II", - "question": "class Solution:\n def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n integer array grid. There is a robot initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.\n An obstacle and space are marked as 1 or 0 respectively in grid. A path that the robot takes cannot include any square that is an obstacle.\n Return the number of possible unique paths that the robot can take to reach the bottom-right corner.\n The testcases are generated so that the answer will be less than or equal to 2 * 109.\n Example 1:\n Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]\n Output: 2\n Explanation: There is one obstacle in the middle of the 3x3 grid above.\n There are two ways to reach the bottom-right corner:\n 1. Right -> Right -> Down -> Down\n 2. Down -> Down -> Right -> Right\n Example 2:\n Input: obstacleGrid = [[0,1],[0,0]]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 64, - "title": "Minimum Path Sum", - "question": "class Solution:\n def minPathSum(self, grid: List[List[int]]) -> int:\n \"\"\"\n Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.\n Note: You can only move either down or right at any point in time.\n Example 1:\n Input: grid = [[1,3,1],[1,5,1],[4,2,1]]\n Output: 7\n Explanation: Because the path 1 \u2192 3 \u2192 1 \u2192 1 \u2192 1 minimizes the sum.\n Example 2:\n Input: grid = [[1,2,3],[4,5,6]]\n Output: 12\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 65, - "title": "Valid Number", - "question": "class Solution:\n def isNumber(self, s: str) -> bool:\n \"\"\"\n A valid number can be split up into these components (in order):\n A decimal number or an integer.\n (Optional) An 'e' or 'E', followed by an integer.\n A decimal number can be split up into these components (in order):\n (Optional) A sign character (either '+' or '-').\n One of the following formats:\n One or more digits, followed by a dot '.'.\n One or more digits, followed by a dot '.', followed by one or more digits.\n A dot '.', followed by one or more digits.\n An integer can be split up into these components (in order):\n (Optional) A sign character (either '+' or '-').\n One or more digits.\n For example, all the following are valid numbers: [\"2\", \"0089\", \"-0.1\", \"+3.14\", \"4.\", \"-.9\", \"2e10\", \"-90E3\", \"3e+7\", \"+6e-1\", \"53.5e93\", \"-123.456e789\"], while the following are not valid numbers: [\"abc\", \"1a\", \"1e\", \"e3\", \"99e2.5\", \"--6\", \"-+3\", \"95a54e53\"].\n Given a string s, return true if s is a valid number.\n Example 1:\n Input: s = \"0\"\n Output: true\n Example 2:\n Input: s = \"e\"\n Output: false\n Example 3:\n Input: s = \".\"\n Output: false\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 66, - "title": "Plus One", - "question": "class Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n \"\"\"\n You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.\n Increment the large integer by one and return the resulting array of digits.\n Example 1:\n Input: digits = [1,2,3]\n Output: [1,2,4]\n Explanation: The array represents the integer 123.\n Incrementing by one gives 123 + 1 = 124.\n Thus, the result should be [1,2,4].\n Example 2:\n Input: digits = [4,3,2,1]\n Output: [4,3,2,2]\n Explanation: The array represents the integer 4321.\n Incrementing by one gives 4321 + 1 = 4322.\n Thus, the result should be [4,3,2,2].\n Example 3:\n Input: digits = [9]\n Output: [1,0]\n Explanation: The array represents the integer 9.\n Incrementing by one gives 9 + 1 = 10.\n Thus, the result should be [1,0].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 67, - "title": "Add Binary", - "question": "class Solution:\n def addBinary(self, a: str, b: str) -> str:\n \"\"\"\n Given two binary strings a and b, return their sum as a binary string.\n Example 1:\n Input: a = \"11\", b = \"1\"\n Output: \"100\"\n Example 2:\n Input: a = \"1010\", b = \"1011\"\n Output: \"10101\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 68, - "title": "Text Justification", - "question": "class Solution:\n def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:\n \"\"\"\n Given an array of strings words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.\n You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.\n Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.\n For the last line of text, it should be left-justified, and no extra space is inserted between words.\n Note:\n A word is defined as a character sequence consisting of non-space characters only.\n Each word's length is guaranteed to be greater than 0 and not exceed maxWidth.\n The input array words contains at least one word.\n Example 1:\n Input: words = [\"This\", \"is\", \"an\", \"example\", \"of\", \"text\", \"justification.\"], maxWidth = 16\n Output:\n [\n \"This is an\",\n \"example of text\",\n \"justification. \"\n ]\n Example 2:\n Input: words = [\"What\",\"must\",\"be\",\"acknowledgment\",\"shall\",\"be\"], maxWidth = 16\n Output:\n [\n \"What must be\",\n \"acknowledgment \",\n \"shall be \"\n ]\n Explanation: Note that the last line is \"shall be \" instead of \"shall be\", because the last line must be left-justified instead of fully-justified.\n Note that the second line is also left-justified because it contains only one word.\n Example 3:\n Input: words = [\"Science\",\"is\",\"what\",\"we\",\"understand\",\"well\",\"enough\",\"to\",\"explain\",\"to\",\"a\",\"computer.\",\"Art\",\"is\",\"everything\",\"else\",\"we\",\"do\"], maxWidth = 20\n Output:\n [\n \"Science is what we\",\n \"understand well\",\n \"enough to explain to\",\n \"a computer. Art is\",\n \"everything else we\",\n \"do \"\n ]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 69, - "title": "Sqrt(x)", - "question": "class Solution:\n def mySqrt(self, x: int) -> int:\n \"\"\"\n Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.\n You must not use any built-in exponent function or operator.\n For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.\n Example 1:\n Input: x = 4\n Output: 2\n Explanation: The square root of 4 is 2, so we return 2.\n Example 2:\n Input: x = 8\n Output: 2\n Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 70, - "title": "Climbing Stairs", - "question": "class Solution:\n def climbStairs(self, n: int) -> int:\n \"\"\"\n You are climbing a staircase. It takes n steps to reach the top.\n Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?\n Example 1:\n Input: n = 2\n Output: 2\n Explanation: There are two ways to climb to the top.\n 1. 1 step + 1 step\n 2. 2 steps\n Example 2:\n Input: n = 3\n Output: 3\n Explanation: There are three ways to climb to the top.\n 1. 1 step + 1 step + 1 step\n 2. 1 step + 2 steps\n 3. 2 steps + 1 step\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 71, - "title": "Simplify Path", - "question": "class Solution:\n def simplifyPath(self, path: str) -> str:\n \"\"\"\n Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.\n In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.\n The canonical path should have the following format:\n The path starts with a single slash '/'.\n Any two directories are separated by a single slash '/'.\n The path does not end with a trailing '/'.\n The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')\n Return the simplified canonical path.\n Example 1:\n Input: path = \"/home/\"\n Output: \"/home\"\n Explanation: Note that there is no trailing slash after the last directory name.\n Example 2:\n Input: path = \"/../\"\n Output: \"/\"\n Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.\n Example 3:\n Input: path = \"/home//foo/\"\n Output: \"/home/foo\"\n Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 72, - "title": "Edit Distance", - "question": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n \"\"\"\n Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.\n You have the following three operations permitted on a word:\n Insert a character\n Delete a character\n Replace a character\n Example 1:\n Input: word1 = \"horse\", word2 = \"ros\"\n Output: 3\n Explanation: \n horse -> rorse (replace 'h' with 'r')\n rorse -> rose (remove 'r')\n rose -> ros (remove 'e')\n Example 2:\n Input: word1 = \"intention\", word2 = \"execution\"\n Output: 5\n Explanation: \n intention -> inention (remove 't')\n inention -> enention (replace 'i' with 'e')\n enention -> exention (replace 'n' with 'x')\n exention -> exection (replace 'n' with 'c')\n exection -> execution (insert 'u')\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 73, - "title": "Set Matrix Zeroes", - "question": "class Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.\n You must do it in place.\n Example 1:\n Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]\n Output: [[1,0,1],[0,0,0],[1,0,1]]\n Example 2:\n Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\n Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 74, - "title": "Search a 2D Matrix", - "question": "class Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n \"\"\"\n You are given an m x n integer matrix matrix with the following two properties:\n Each row is sorted in non-decreasing order.\n The first integer of each row is greater than the last integer of the previous row.\n Given an integer target, return true if target is in matrix or false otherwise.\n You must write a solution in O(log(m * n)) time complexity.\n Example 1:\n Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3\n Output: true\n Example 2:\n Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 75, - "title": "Sort Colors", - "question": "class Solution:\n def sortColors(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.\n We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.\n You must solve this problem without using the library's sort function.\n Example 1:\n Input: nums = [2,0,2,1,1,0]\n Output: [0,0,1,1,2,2]\n Example 2:\n Input: nums = [2,0,1]\n Output: [0,1,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 76, - "title": "Minimum Window Substring", - "question": "class Solution:\n def minWindow(self, s: str, t: str) -> str:\n \"\"\"\n Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string \"\".\n The testcases will be generated such that the answer is unique.\n Example 1:\n Input: s = \"ADOBECODEBANC\", t = \"ABC\"\n Output: \"BANC\"\n Explanation: The minimum window substring \"BANC\" includes 'A', 'B', and 'C' from string t.\n Example 2:\n Input: s = \"a\", t = \"a\"\n Output: \"a\"\n Explanation: The entire string s is the minimum window.\n Example 3:\n Input: s = \"a\", t = \"aa\"\n Output: \"\"\n Explanation: Both 'a's from t must be included in the window.\n Since the largest window of s only has one 'a', return empty string.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 77, - "title": "Combinations", - "question": "class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n \"\"\"\n Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].\n You may return the answer in any order.\n Example 1:\n Input: n = 4, k = 2\n Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\n Explanation: There are 4 choose 2 = 6 total combinations.\n Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.\n Example 2:\n Input: n = 1, k = 1\n Output: [[1]]\n Explanation: There is 1 choose 1 = 1 total combination.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 78, - "title": "Subsets", - "question": "class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n \"\"\"\n Given an integer array nums of unique elements, return all possible subsets (the power set).\n The solution set must not contain duplicate subsets. Return the solution in any order.\n Example 1:\n Input: nums = [1,2,3]\n Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\n Example 2:\n Input: nums = [0]\n Output: [[],[0]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 79, - "title": "Word Search", - "question": "class Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n \"\"\"\n Given an m x n grid of characters board and a string word, return true if word exists in the grid.\n The word can 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.\n Example 1:\n Input: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCCED\"\n Output: true\n Example 2:\n Input: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"SEE\"\n Output: true\n Example 3:\n Input: board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"ABCB\"\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 80, - "title": "Remove Duplicates from Sorted Array II", - "question": "class Solution:\n def removeDuplicates(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same.\n Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.\n Return k after placing the final result in the first k slots of nums.\n Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.\n Custom Judge:\n The judge will test your solution with the following code:\n int[] nums = [...]; // Input array\n int[] expectedNums = [...]; // The expected answer with correct length\n int k = removeDuplicates(nums); // Calls your implementation\n assert k == expectedNums.length;\n for (int i = 0; i < k; i++) {\n assert nums[i] == expectedNums[i];\n }\n If all assertions pass, then your solution will be accepted.\n Example 1:\n Input: nums = [1,1,1,2,2,3]\n Output: 5, nums = [1,1,2,2,3,_]\n Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.\n It does not matter what you leave beyond the returned k (hence they are underscores).\n Example 2:\n Input: nums = [0,0,1,1,1,1,2,3,3]\n Output: 7, nums = [0,0,1,1,2,3,3,_,_]\n Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.\n It does not matter what you leave beyond the returned k (hence they are underscores).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 81, - "title": "Search in Rotated Sorted Array II", - "question": "class Solution:\n def search(self, nums: List[int], target: int) -> bool:\n \"\"\"\n There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).\n Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].\n Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.\n You must decrease the overall operation steps as much as possible.\n Example 1:\n Input: nums = [2,5,6,0,0,1,2], target = 0\n Output: true\n Example 2:\n Input: nums = [2,5,6,0,0,1,2], target = 3\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 82, - "title": "Remove Duplicates from Sorted List II", - "question": "class Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.\n Example 1:\n Input: head = [1,2,3,3,4,4,5]\n Output: [1,2,5]\n Example 2:\n Input: head = [1,1,1,2,3]\n Output: [2,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 83, - "title": "Remove Duplicates from Sorted List", - "question": "class Solution:\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.\n Example 1:\n Input: head = [1,1,2]\n Output: [1,2]\n Example 2:\n Input: head = [1,1,2,3,3]\n Output: [1,2,3]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 84, - "title": "Largest Rectangle in Histogram", - "question": "class Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n \"\"\"\n Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.\n Example 1:\n Input: heights = [2,1,5,6,2,3]\n Output: 10\n Explanation: The above is a histogram where width of each bar is 1.\n The largest rectangle is shown in the red area, which has an area = 10 units.\n Example 2:\n Input: heights = [2,4]\n Output: 4\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 85, - "title": "Maximal Rectangle", - "question": "class Solution:\n def maximalRectangle(self, matrix: List[List[str]]) -> int:\n \"\"\"\n Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.\n Example 1:\n Input: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\n Output: 6\n Explanation: The maximal rectangle is shown in the above picture.\n Example 2:\n Input: matrix = [[\"0\"]]\n Output: 0\n Example 3:\n Input: matrix = [[\"1\"]]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 86, - "title": "Partition List", - "question": "class Solution:\n def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.\n You should preserve the original relative order of the nodes in each of the two partitions.\n Example 1:\n Input: head = [1,4,3,2,5,2], x = 3\n Output: [1,2,2,4,3,5]\n Example 2:\n Input: head = [2,1], x = 2\n Output: [1,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 87, - "title": "Scramble String", - "question": "class Solution:\n def isScramble(self, s1: str, s2: str) -> bool:\n \"\"\"\n We can scramble a string s to get a string t using the following algorithm:\n If the length of the string is 1, stop.\n If the length of the string is > 1, do the following:\n Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.\n Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.\n Apply step 1 recursively on each of the two substrings x and y.\n Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.\n Example 1:\n Input: s1 = \"great\", s2 = \"rgeat\"\n Output: true\n Explanation: One possible scenario applied on s1 is:\n \"great\" --> \"gr/eat\" // divide at random index.\n \"gr/eat\" --> \"gr/eat\" // random decision is not to swap the two substrings and keep them in order.\n \"gr/eat\" --> \"g/r / e/at\" // apply the same algorithm recursively on both substrings. divide at random index each of them.\n \"g/r / e/at\" --> \"r/g / e/at\" // random decision was to swap the first substring and to keep the second substring in the same order.\n \"r/g / e/at\" --> \"r/g / e/ a/t\" // again apply the algorithm recursively, divide \"at\" to \"a/t\".\n \"r/g / e/ a/t\" --> \"r/g / e/ a/t\" // random decision is to keep both substrings in the same order.\n The algorithm stops now, and the result string is \"rgeat\" which is s2.\n As one possible scenario led s1 to be scrambled to s2, we return true.\n Example 2:\n Input: s1 = \"abcde\", s2 = \"caebd\"\n Output: false\n Example 3:\n Input: s1 = \"a\", s2 = \"a\"\n Output: true\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 88, - "title": "Merge Sorted Array", - "question": "class Solution:\n def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:\n \"\"\"\n Do not return anything, modify nums1 in-place instead.\n You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.\n Merge nums1 and nums2 into a single array sorted in non-decreasing order.\n The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.\n Example 1:\n Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3\n Output: [1,2,2,3,5,6]\n Explanation: The arrays we are merging are [1,2,3] and [2,5,6].\n The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.\n Example 2:\n Input: nums1 = [1], m = 1, nums2 = [], n = 0\n Output: [1]\n Explanation: The arrays we are merging are [1] and [].\n The result of the merge is [1].\n Example 3:\n Input: nums1 = [0], m = 0, nums2 = [1], n = 1\n Output: [1]\n Explanation: The arrays we are merging are [] and [1].\n The result of the merge is [1].\n Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 89, - "title": "Gray Code", - "question": "class Solution:\n def grayCode(self, n: int) -> List[int]:\n \"\"\"\n An n-bit gray code sequence is a sequence of 2n integers where:\n Every integer is in the inclusive range [0, 2n - 1],\n The first integer is 0,\n An integer appears no more than once in the sequence,\n The binary representation of every pair of adjacent integers differs by exactly one bit, and\n The binary representation of the first and last integers differs by exactly one bit.\n Given an integer n, return any valid n-bit gray code sequence.\n Example 1:\n Input: n = 2\n Output: [0,1,3,2]\n Explanation:\n The binary representation of [0,1,3,2] is [00,01,11,10].\n - 00 and 01 differ by one bit\n - 01 and 11 differ by one bit\n - 11 and 10 differ by one bit\n - 10 and 00 differ by one bit\n [0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].\n - 00 and 10 differ by one bit\n - 10 and 11 differ by one bit\n - 11 and 01 differ by one bit\n - 01 and 00 differ by one bit\n Example 2:\n Input: n = 1\n Output: [0,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 90, - "title": "Subsets II", - "question": "class Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n \"\"\"\n Given an integer array nums that may contain duplicates, return all possible subsets (the power set).\n The solution set must not contain duplicate subsets. Return the solution in any order.\n Example 1:\n Input: nums = [1,2,2]\n Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]\n Example 2:\n Input: nums = [0]\n Output: [[],[0]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 91, - "title": "Decode Ways", - "question": "class Solution:\n def numDecodings(self, s: str) -> int:\n \"\"\"\n 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\"\n To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\n \"AAJF\" with the grouping (1 1 10 6)\n \"KJF\" with the grouping (11 10 6)\n Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\n Given a string s containing only digits, return the number of ways to decode it.\n The test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\n Input: s = \"12\"\n Output: 2\n Explanation: \"12\" could be decoded as \"AB\" (1 2) or \"L\" (12).\n Example 2:\n Input: s = \"226\"\n Output: 3\n Explanation: \"226\" could be decoded as \"BZ\" (2 26), \"VF\" (22 6), or \"BBF\" (2 2 6).\n Example 3:\n Input: s = \"06\"\n Output: 0\n Explanation: \"06\" cannot be mapped to \"F\" because of the leading zero (\"6\" is different from \"06\").\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 92, - "title": "Reverse Linked List II", - "question": "class Solution:\n def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:\n \"\"\"\n Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.\n Example 1:\n Input: head = [1,2,3,4,5], left = 2, right = 4\n Output: [1,4,3,2,5]\n Example 2:\n Input: head = [5], left = 1, right = 1\n Output: [5]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 93, - "title": "Restore IP Addresses", - "question": "class Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n \"\"\"\n A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.\n For example, \"0.1.2.201\" and \"192.168.1.1\" are valid IP addresses, but \"0.011.255.245\", \"192.168.1.312\" and \"192.168@1.1\" are invalid IP addresses.\n Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.\n Example 1:\n Input: s = \"25525511135\"\n Output: [\"255.255.11.135\",\"255.255.111.35\"]\n Example 2:\n Input: s = \"0000\"\n Output: [\"0.0.0.0\"]\n Example 3:\n Input: s = \"101023\"\n Output: [\"1.0.10.23\",\"1.0.102.3\",\"10.1.0.23\",\"10.10.2.3\",\"101.0.2.3\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 94, - "title": "Binary Tree Inorder Traversal", - "question": "class Solution:\n def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n Given the root of a binary tree, return the inorder traversal of its nodes' values.\n Example 1:\n Input: root = [1,null,2,3]\n Output: [1,3,2]\n Example 2:\n Input: root = []\n Output: []\n Example 3:\n Input: root = [1]\n Output: [1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 95, - "title": "Unique Binary Search Trees II", - "question": "class Solution:\n def generateTrees(self, n: int) -> List[Optional[TreeNode]]:\n \"\"\"\n Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.\n Example 1:\n Input: n = 3\n Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]\n Example 2:\n Input: n = 1\n Output: [[1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 96, - "title": "Unique Binary Search Trees", - "question": "class Solution:\n def numTrees(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.\n Example 1:\n Input: n = 3\n Output: 5\n Example 2:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 97, - "title": "Interleaving String", - "question": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n \"\"\"\n Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2.\n An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that:\n s = s1 + s2 + ... + sn\n t = t1 + t2 + ... + tm\n |n - m| <= 1\n The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...\n Note: a + b is the concatenation of strings a and b.\n Example 1:\n Input: s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbcbcac\"\n Output: true\n Explanation: One way to obtain s3 is:\n Split s1 into s1 = \"aa\" + \"bc\" + \"c\", and s2 into s2 = \"dbbc\" + \"a\".\n Interleaving the two splits, we get \"aa\" + \"dbbc\" + \"bc\" + \"a\" + \"c\" = \"aadbbcbcac\".\n Since s3 can be obtained by interleaving s1 and s2, we return true.\n Example 2:\n Input: s1 = \"aabcc\", s2 = \"dbbca\", s3 = \"aadbbbaccc\"\n Output: false\n Explanation: Notice how it is impossible to interleave s2 with any other string to obtain s3.\n Example 3:\n Input: s1 = \"\", s2 = \"\", s3 = \"\"\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 98, - "title": "Validate Binary Search Tree", - "question": "class Solution:\n def isValidBST(self, root: Optional[TreeNode]) -> bool:\n \"\"\"\n Given the root of a binary tree, determine if it is a valid binary search tree (BST).\n A valid BST is defined as follows:\n The left subtree of a node contains only nodes with keys less than the node's key.\n The right subtree of a node contains only nodes with keys greater than the node's key.\n Both the left and right subtrees must also be binary search trees.\n Example 1:\n Input: root = [2,1,3]\n Output: true\n Example 2:\n Input: root = [5,1,4,null,null,3,6]\n Output: false\n Explanation: The root node's value is 5 but its right child's value is 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 99, - "title": "Recover Binary Search Tree", - "question": "class Solution:\n def recoverTree(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure.\n Example 1:\n Input: root = [1,3,null,null,2]\n Output: [3,1,null,null,2]\n Explanation: 3 cannot be a left child of 1 because 3 > 1. Swapping 1 and 3 makes the BST valid.\n Example 2:\n Input: root = [3,1,4,null,null,2]\n Output: [2,1,4,null,null,3]\n Explanation: 2 cannot be in the right subtree of 3 because 2 < 3. Swapping 2 and 3 makes the BST valid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 100, - "title": "Same Tree", - "question": "class Solution:\n def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:\n \"\"\"\n Given the roots of two binary trees p and q, write a function to check if they are the same or not.\n Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.\n Example 1:\n Input: p = [1,2,3], q = [1,2,3]\n Output: true\n Example 2:\n Input: p = [1,2], q = [1,null,2]\n Output: false\n Example 3:\n Input: p = [1,2,1], q = [1,1,2]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 101, - "title": "Symmetric Tree", - "question": "class Solution:\n def isSymmetric(self, root: Optional[TreeNode]) -> bool:\n \"\"\"\n Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).\n Example 1:\n Input: root = [1,2,2,3,4,4,3]\n Output: true\n Example 2:\n Input: root = [1,2,2,null,3,null,3]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 102, - "title": "Binary Tree Level Order Traversal", - "question": "class Solution:\n def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n \"\"\"\n 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:\n Input: root = [3,9,20,null,null,15,7]\n Output: [[3],[9,20],[15,7]]\n Example 2:\n Input: root = [1]\n Output: [[1]]\n Example 3:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 103, - "title": "Binary Tree Zigzag Level Order Traversal", - "question": "class Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n \"\"\"\n 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:\n Input: root = [3,9,20,null,null,15,7]\n Output: [[3],[20,9],[15,7]]\n Example 2:\n Input: root = [1]\n Output: [[1]]\n Example 3:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 104, - "title": "Maximum Depth of Binary Tree", - "question": "class Solution:\n def maxDepth(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return its maximum depth.\n A 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:\n Input: root = [3,9,20,null,null,15,7]\n Output: 3\n Example 2:\n Input: root = [1,null,2]\n Output: 2\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 105, - "title": "Construct Binary Tree from Preorder and Inorder Traversal", - "question": "class Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:\n \"\"\"\n 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:\n Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]\n Output: [3,9,20,null,null,15,7]\n Example 2:\n Input: preorder = [-1], inorder = [-1]\n Output: [-1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 106, - "title": "Construct Binary Tree from Inorder and Postorder Traversal", - "question": "class Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n \"\"\"\n 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:\n Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]\n Output: [3,9,20,null,null,15,7]\n Example 2:\n Input: inorder = [-1], postorder = [-1]\n Output: [-1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 107, - "title": "Binary Tree Level Order Traversal II", - "question": "class Solution:\n def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:\n \"\"\"\n 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:\n Input: root = [3,9,20,null,null,15,7]\n Output: [[15,7],[9,20],[3]]\n Example 2:\n Input: root = [1]\n Output: [[1]]\n Example 3:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 108, - "title": "Convert Sorted Array to Binary Search Tree", - "question": "class Solution:\n def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:\n \"\"\"\n Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.\n Example 1:\n Input: nums = [-10,-3,0,5,9]\n Output: [0,-3,9,-10,null,5]\n Explanation: [0,-10,5,null,-3,null,9] is also accepted:\n Example 2:\n Input: nums = [1,3]\n Output: [3,1]\n Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 109, - "title": "Convert Sorted List to Binary Search Tree", - "question": "class Solution:\n def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:\n \"\"\"\n Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.\n Example 1:\n Input: head = [-10,-3,0,5,9]\n Output: [0,-3,9,-10,null,5]\n Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.\n Example 2:\n Input: head = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 110, - "title": "Balanced Binary Tree", - "question": "class Solution:\n def isBalanced(self, root: Optional[TreeNode]) -> bool:\n \"\"\"\n Given a binary tree, determine if it is height-balanced.\n Example 1:\n Input: root = [3,9,20,null,null,15,7]\n Output: true\n Example 2:\n Input: root = [1,2,2,3,3,null,null,4,4]\n Output: false\n Example 3:\n Input: root = []\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 111, - "title": "Minimum Depth of Binary Tree", - "question": "class Solution:\n def minDepth(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given a binary tree, find its minimum depth.\n The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.\n Note: A leaf is a node with no children.\n Example 1:\n Input: root = [3,9,20,null,null,15,7]\n Output: 2\n Example 2:\n Input: root = [2,null,3,null,4,null,5,null,6]\n Output: 5\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 112, - "title": "Path Sum", - "question": "class Solution:\n def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:\n \"\"\"\n 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.\n A leaf is a node with no children.\n Example 1:\n Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22\n Output: true\n Explanation: The root-to-leaf path with the target sum is shown.\n Example 2:\n Input: root = [1,2,3], targetSum = 5\n Output: false\n Explanation: There two root-to-leaf paths in the tree:\n (1 --> 2): The sum is 3.\n (1 --> 3): The sum is 4.\n There is no root-to-leaf path with sum = 5.\n Example 3:\n Input: root = [], targetSum = 0\n Output: false\n Explanation: Since the tree is empty, there are no root-to-leaf paths.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 113, - "title": "Path Sum II", - "question": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:\n \"\"\"\n 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.\n A 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:\n Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n Output: [[5,4,11,2],[5,8,4,5]]\n Explanation: There are two paths whose sum equals targetSum:\n 5 + 4 + 11 + 2 = 22\n 5 + 8 + 4 + 5 = 22\n Example 2:\n Input: root = [1,2,3], targetSum = 5\n Output: []\n Example 3:\n Input: root = [1,2], targetSum = 0\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 114, - "title": "Flatten Binary Tree to Linked List", - "question": "class Solution:\n def flatten(self, root: Optional[TreeNode]) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n Given the root of a binary tree, flatten the tree into a \"linked list\":\n The \"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.\n The \"linked list\" should be in the same order as a pre-order traversal of the binary tree.\n Example 1:\n Input: root = [1,2,5,3,4,null,6]\n Output: [1,null,2,null,3,null,4,null,5,null,6]\n Example 2:\n Input: root = []\n Output: []\n Example 3:\n Input: root = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 115, - "title": "Distinct Subsequences", - "question": "class Solution:\n def numDistinct(self, s: str, t: str) -> int:\n \"\"\"\n Given two strings s and t, return the number of distinct subsequences of s which equals t.\n The test cases are generated so that the answer fits on a 32-bit signed integer.\n Example 1:\n Input: s = \"rabbbit\", t = \"rabbit\"\n Output: 3\n Explanation:\n As shown below, there are 3 ways you can generate \"rabbit\" from s.\n rabbbit\n rabbbit\n rabbbit\n Example 2:\n Input: s = \"babgbag\", t = \"bag\"\n Output: 5\n Explanation:\n As shown below, there are 5 ways you can generate \"bag\" from s.\n babgbag\n babgbag\n babgbag\n babgbag\n babgbag\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 116, - "title": "Populating Next Right Pointers in Each Node", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n 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:\n struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n }\n Populate 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.\n Initially, all next pointers are set to NULL.\n Example 1:\n Input: root = [1,2,3,4,5,6,7]\n Output: [1,#,2,3,#,4,5,6,7,#]\n Explanation: 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.\n Example 2:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 117, - "title": "Populating Next Right Pointers in Each Node II", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):\n self.val = val\n self.left = left\n self.right = right\n self.next = next\n Given a binary tree\n struct Node {\n int val;\n Node *left;\n Node *right;\n Node *next;\n }\n Populate 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.\n Initially, all next pointers are set to NULL.\n Example 1:\n Input: root = [1,2,3,4,5,null,7]\n Output: [1,#,2,3,#,4,5,7,#]\n Explanation: 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.\n Example 2:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 118, - "title": "Pascal\"s Triangle", - "question": "class Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n \"\"\"\n Given an integer numRows, return the first numRows of Pascal's triangle.\n In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n Example 1:\n Input: numRows = 5\n Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]\n Example 2:\n Input: numRows = 1\n Output: [[1]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 119, - "title": "Pascal\"s Triangle II", - "question": "class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n \"\"\"\n Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.\n In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:\n Example 1:\n Input: rowIndex = 3\n Output: [1,3,3,1]\n Example 2:\n Input: rowIndex = 0\n Output: [1]\n Example 3:\n Input: rowIndex = 1\n Output: [1,1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 120, - "title": "Triangle", - "question": "class Solution:\n def minimumTotal(self, triangle: List[List[int]]) -> int:\n \"\"\"\n Given a triangle array, return the minimum path sum from top to bottom.\n For 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:\n Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]\n Output: 11\n Explanation: The triangle looks like:\n 2\n 3 4\n 6 5 7\n 4 1 8 3\n The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).\n Example 2:\n Input: triangle = [[-10]]\n Output: -10\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 121, - "title": "Best Time to Buy and Sell Stock", - "question": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \"\"\"\n You are given an array prices where prices[i] is the price of a given stock on the ith day.\n You 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.\n Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.\n Example 1:\n Input: prices = [7,1,5,3,6,4]\n Output: 5\n Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.\n Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.\n Example 2:\n Input: prices = [7,6,4,3,1]\n Output: 0\n Explanation: In this case, no transactions are done and the max profit = 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 122, - "title": "Best Time to Buy and Sell Stock II", - "question": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \"\"\"\n You are given an integer array prices where prices[i] is the price of a given stock on the ith day.\n On 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.\n Find and return the maximum profit you can achieve.\n Example 1:\n Input: prices = [7,1,5,3,6,4]\n Output: 7\n Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\n Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\n Total profit is 4 + 3 = 7.\n Example 2:\n Input: prices = [1,2,3,4,5]\n Output: 4\n Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n Total profit is 4.\n Example 3:\n Input: prices = [7,6,4,3,1]\n Output: 0\n Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 123, - "title": "Best Time to Buy and Sell Stock III", - "question": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \"\"\"\n You are given an array prices where prices[i] is the price of a given stock on the ith day.\n Find the maximum profit you can achieve. You may complete at most two transactions.\n Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\n Input: prices = [3,3,5,0,0,3,1,4]\n Output: 6\n Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.\n Example 2:\n Input: prices = [1,2,3,4,5]\n Output: 4\n Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.\n Example 3:\n Input: prices = [7,6,4,3,1]\n Output: 0\n Explanation: In this case, no transaction is done, i.e. max profit = 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 124, - "title": "Binary Tree Maximum Path Sum", - "question": "class Solution:\n def maxPathSum(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n The path sum of a path is the sum of the node's values in the path.\n Given the root of a binary tree, return the maximum path sum of any non-empty path.\n Example 1:\n Input: root = [1,2,3]\n Output: 6\n Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.\n Example 2:\n Input: root = [-10,9,20,null,null,15,7]\n Output: 42\n Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 125, - "title": "Valid Palindrome", - "question": "class Solution:\n def isPalindrome(self, s: str) -> bool:\n \"\"\"\n 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.\n Given a string s, return true if it is a palindrome, or false otherwise.\n Example 1:\n Input: s = \"A man, a plan, a canal: Panama\"\n Output: true\n Explanation: \"amanaplanacanalpanama\" is a palindrome.\n Example 2:\n Input: s = \"race a car\"\n Output: false\n Explanation: \"raceacar\" is not a palindrome.\n Example 3:\n Input: s = \" \"\n Output: true\n Explanation: s is an empty string \"\" after removing non-alphanumeric characters.\n Since an empty string reads the same forward and backward, it is a palindrome.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 126, - "title": "Word Ladder II", - "question": "class Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n \"\"\"\n A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:\n Every adjacent pair of words differs by a single letter.\n Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.\n sk == endWord\n Given two words, beginWord and endWord, and a dictionary wordList, return all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].\n Example 1:\n Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n Output: [[\"hit\",\"hot\",\"dot\",\"dog\",\"cog\"],[\"hit\",\"hot\",\"lot\",\"log\",\"cog\"]]\n Explanation: There are 2 shortest transformation sequences:\n \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> \"cog\"\n \"hit\" -> \"hot\" -> \"lot\" -> \"log\" -> \"cog\"\n Example 2:\n Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n Output: []\n Explanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 127, - "title": "Word Ladder", - "question": "class Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n \"\"\"\n A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:\n Every adjacent pair of words differs by a single letter.\n Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.\n sk == endWord\n Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.\n Example 1:\n Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n Output: 5\n Explanation: One shortest transformation sequence is \"hit\" -> \"hot\" -> \"dot\" -> \"dog\" -> cog\", which is 5 words long.\n Example 2:\n Input: beginWord = \"hit\", endWord = \"cog\", wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\"]\n Output: 0\n Explanation: The endWord \"cog\" is not in wordList, therefore there is no valid transformation sequence.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 128, - "title": "Longest Consecutive Sequence", - "question": "class Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n \"\"\"\n Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.\n You must write an algorithm that runs in O(n) time.\n Example 1:\n Input: nums = [100,4,200,1,3,2]\n Output: 4\n Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.\n Example 2:\n Input: nums = [0,3,7,2,5,8,4,6,0,1]\n Output: 9\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 129, - "title": "Sum Root to Leaf Numbers", - "question": "class Solution:\n def sumNumbers(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n You are given the root of a binary tree containing digits from 0 to 9 only.\n Each root-to-leaf path in the tree represents a number.\n For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.\n Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer.\n A leaf node is a node with no children.\n Example 1:\n Input: root = [1,2,3]\n Output: 25\n Explanation:\n The root-to-leaf path 1->2 represents the number 12.\n The root-to-leaf path 1->3 represents the number 13.\n Therefore, sum = 12 + 13 = 25.\n Example 2:\n Input: root = [4,9,0,5,1]\n Output: 1026\n Explanation:\n The root-to-leaf path 4->9->5 represents the number 495.\n The root-to-leaf path 4->9->1 represents the number 491.\n The root-to-leaf path 4->0 represents the number 40.\n Therefore, sum = 495 + 491 + 40 = 1026.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 130, - "title": "Surrounded Regions", - "question": "class Solution:\n def solve(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.\n A region is captured by flipping all 'O's into 'X's in that surrounded region.\n Example 1:\n Input: board = [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"O\",\"X\"],[\"X\",\"X\",\"O\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\n Output: [[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"X\",\"X\",\"X\"],[\"X\",\"O\",\"X\",\"X\"]]\n Explanation: 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.\n The bottom 'O' is on the border, so it is not flipped.\n The other three 'O' form a surrounded region, so they are flipped.\n Example 2:\n Input: board = [[\"X\"]]\n Output: [[\"X\"]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 131, - "title": "Palindrome Partitioning", - "question": "class Solution:\n def partition(self, s: str) -> List[List[str]]:\n \"\"\"\n Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.\n Example 1:\n Input: s = \"aab\"\n Output: [[\"a\",\"a\",\"b\"],[\"aa\",\"b\"]]\n Example 2:\n Input: s = \"a\"\n Output: [[\"a\"]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 132, - "title": "Palindrome Partitioning II", - "question": "class Solution:\n def minCut(self, s: str) -> int:\n \"\"\"\n Given a string s, partition s such that every substring of the partition is a palindrome.\n Return the minimum cuts needed for a palindrome partitioning of s.\n Example 1:\n Input: s = \"aab\"\n Output: 1\n Explanation: The palindrome partitioning [\"aa\",\"b\"] could be produced using 1 cut.\n Example 2:\n Input: s = \"a\"\n Output: 0\n Example 3:\n Input: s = \"ab\"\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 133, - "title": "Clone Graph", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n Given a reference of a node in a connected undirected graph.\n Return a deep copy (clone) of the graph.\n Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.\n class Node {\n public int val;\n public List neighbors;\n }\n Test case format:\n For 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.\n An 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.\n The 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:\n Input: adjList = [[2,4],[1,3],[2,4],[1,3]]\n Output: [[2,4],[1,3],[2,4],[1,3]]\n Explanation: There are 4 nodes in the graph.\n 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n Example 2:\n Input: adjList = [[]]\n Output: [[]]\n Explanation: 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.\n Example 3:\n Input: adjList = []\n Output: []\n Explanation: This an empty graph, it does not have any nodes.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 134, - "title": "Gas Station", - "question": "class Solution:\n def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:\n \"\"\"\n There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].\n You 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.\n Given 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:\n Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]\n Output: 3\n Explanation:\n Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\n Travel to station 4. Your tank = 4 - 1 + 5 = 8\n Travel to station 0. Your tank = 8 - 2 + 1 = 7\n Travel to station 1. Your tank = 7 - 3 + 2 = 6\n Travel to station 2. Your tank = 6 - 4 + 3 = 5\n Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.\n Therefore, return 3 as the starting index.\n Example 2:\n Input: gas = [2,3,4], cost = [3,4,3]\n Output: -1\n Explanation:\n You can't start at station 0 or 1, as there is not enough gas to travel to the next station.\n Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4\n Travel to station 0. Your tank = 4 - 3 + 2 = 3\n Travel to station 1. Your tank = 3 - 3 + 3 = 3\n You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.\n Therefore, you can't travel around the circuit once no matter where you start.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 135, - "title": "Candy", - "question": "class Solution:\n def candy(self, ratings: List[int]) -> int:\n \"\"\"\n There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings.\n You are giving candies to these children subjected to the following requirements:\n Each child must have at least one candy.\n Children with a higher rating get more candies than their neighbors.\n Return the minimum number of candies you need to have to distribute the candies to the children.\n Example 1:\n Input: ratings = [1,0,2]\n Output: 5\n Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.\n Example 2:\n Input: ratings = [1,2,2]\n Output: 4\n Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.\n The third child gets 1 candy because it satisfies the above two conditions.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 136, - "title": "Single Number", - "question": "class Solution:\n def singleNumber(self, nums: List[int]) -> int:\n \"\"\"\n Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.\n You must implement a solution with a linear runtime complexity and use only constant extra space.\n Example 1:\n Input: nums = [2,2,1]\n Output: 1\n Example 2:\n Input: nums = [4,1,2,1,2]\n Output: 4\n Example 3:\n Input: nums = [1]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 137, - "title": "Single Number II", - "question": "class Solution:\n def singleNumber(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n You must implement a solution with a linear runtime complexity and use only constant extra space.\n Example 1:\n Input: nums = [2,2,3,2]\n Output: 3\n Example 2:\n Input: nums = [0,1,0,1,0,1,99]\n Output: 99\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 138, - "title": "Copy List with Random Pointer", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n 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.\n Construct 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.\n For 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.\n Return the head of the copied linked list.\n The 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:\n val: an integer representing Node.val\n random_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.\n Your code will only be given the head of the original linked list.\n Example 1:\n Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]\n Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]\n Example 2:\n Input: head = [[1,1],[2,1]]\n Output: [[1,1],[2,1]]\n Example 3:\n Input: head = [[3,null],[3,0],[3,null]]\n Output: [[3,null],[3,0],[3,null]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 139, - "title": "Word Break", - "question": "class Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n \"\"\"\n 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.\n Note that the same word in the dictionary may be reused multiple times in the segmentation.\n Example 1:\n Input: s = \"leetcode\", wordDict = [\"leet\",\"code\"]\n Output: true\n Explanation: Return true because \"leetcode\" can be segmented as \"leet code\".\n Example 2:\n Input: s = \"applepenapple\", wordDict = [\"apple\",\"pen\"]\n Output: true\n Explanation: Return true because \"applepenapple\" can be segmented as \"apple pen apple\".\n Note that you are allowed to reuse a dictionary word.\n Example 3:\n Input: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 140, - "title": "Word Break II", - "question": "class Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n \"\"\"\n Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.\n Note that the same word in the dictionary may be reused multiple times in the segmentation.\n Example 1:\n Input: s = \"catsanddog\", wordDict = [\"cat\",\"cats\",\"and\",\"sand\",\"dog\"]\n Output: [\"cats and dog\",\"cat sand dog\"]\n Example 2:\n Input: s = \"pineapplepenapple\", wordDict = [\"apple\",\"pen\",\"applepen\",\"pine\",\"pineapple\"]\n Output: [\"pine apple pen apple\",\"pineapple pen apple\",\"pine applepen apple\"]\n Explanation: Note that you are allowed to reuse a dictionary word.\n Example 3:\n Input: s = \"catsandog\", wordDict = [\"cats\",\"dog\",\"sand\",\"and\",\"cat\"]\n Output: []\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 141, - "title": "Linked List Cycle", - "question": "class Solution:\n def hasCycle(self, head: Optional[ListNode]) -> bool:\n \"\"\"\n Given head, the head of a linked list, determine if the linked list has a cycle in it.\n There 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.\n Return true if there is a cycle in the linked list. Otherwise, return false.\n Example 1:\n Input: head = [3,2,0,-4], pos = 1\n Output: true\n Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).\n Example 2:\n Input: head = [1,2], pos = 0\n Output: true\n Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.\n Example 3:\n Input: head = [1], pos = -1\n Output: false\n Explanation: There is no cycle in the linked list.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 142, - "title": "Linked List Cycle II", - "question": "class Solution:\n def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.\n There 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.\n Do not modify the linked list.\n Example 1:\n Input: head = [3,2,0,-4], pos = 1\n Output: tail connects to node index 1\n Explanation: There is a cycle in the linked list, where tail connects to the second node.\n Example 2:\n Input: head = [1,2], pos = 0\n Output: tail connects to node index 0\n Explanation: There is a cycle in the linked list, where tail connects to the first node.\n Example 3:\n Input: head = [1], pos = -1\n Output: no cycle\n Explanation: There is no cycle in the linked list.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 143, - "title": "Reorder List", - "question": "class Solution:\n def reorderList(self, head: Optional[ListNode]) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n You are given the head of a singly linked-list. The list can be represented as:\n L0 \u2192 L1 \u2192 \u2026 \u2192 Ln - 1 \u2192 Ln\n Reorder the list to be on the following form:\n L0 \u2192 Ln \u2192 L1 \u2192 Ln - 1 \u2192 L2 \u2192 Ln - 2 \u2192 \u2026\n You may not modify the values in the list's nodes. Only nodes themselves may be changed.\n Example 1:\n Input: head = [1,2,3,4]\n Output: [1,4,2,3]\n Example 2:\n Input: head = [1,2,3,4,5]\n Output: [1,5,2,4,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 144, - "title": "Binary Tree Preorder Traversal", - "question": "class Solution:\n def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n Given the root of a binary tree, return the preorder traversal of its nodes' values.\n Example 1:\n Input: root = [1,null,2,3]\n Output: [1,2,3]\n Example 2:\n Input: root = []\n Output: []\n Example 3:\n Input: root = [1]\n Output: [1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 145, - "title": "Binary Tree Postorder Traversal", - "question": "class Solution:\n def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n Given the root of a binary tree, return the postorder traversal of its nodes' values.\n Example 1:\n Input: root = [1,null,2,3]\n Output: [3,2,1]\n Example 2:\n Input: root = []\n Output: []\n Example 3:\n Input: root = [1]\n Output: [1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 146, - "title": "LRU Cache", - "question": "class LRUCache:\n def __init__(self, capacity: int):\n def get(self, key: int) -> int:\n def put(self, key: int, value: int) -> None:\n \"\"\"\n Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.\n Implement the LRUCache class:\n LRUCache(int capacity) Initialize the LRU cache with positive size capacity.\n int get(int key) Return the value of the key if the key exists, otherwise return -1.\n void 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.\n The functions get and put must each run in O(1) average time complexity.\n Example 1:\n Input\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]]\n Output\n [null, null, null, 1, null, -1, null, -1, 3, 4]\n Explanation\n LRUCache lRUCache = new LRUCache(2);\n lRUCache.put(1, 1); // cache is {1=1}\n lRUCache.put(2, 2); // cache is {1=1, 2=2}\n lRUCache.get(1); // return 1\n lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}\n lRUCache.get(2); // returns -1 (not found)\n lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}\n lRUCache.get(1); // return -1 (not found)\n lRUCache.get(3); // return 3\n lRUCache.get(4); // return 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 147, - "title": "Insertion Sort List", - "question": "class Solution:\n def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.\n The steps of the insertion sort algorithm:\n Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.\n At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.\n It repeats until no input elements remain.\n The 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:\n Input: head = [4,2,1,3]\n Output: [1,2,3,4]\n Example 2:\n Input: head = [-1,5,3,4,0]\n Output: [-1,0,3,4,5]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 148, - "title": "Sort List", - "question": "class Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list, return the list after sorting it in ascending order.\n Example 1:\n Input: head = [4,2,1,3]\n Output: [1,2,3,4]\n Example 2:\n Input: head = [-1,5,3,4,0]\n Output: [-1,0,3,4,5]\n Example 3:\n Input: head = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 149, - "title": "Max Points on a Line", - "question": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n \"\"\"\n 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:\n Input: points = [[1,1],[2,2],[3,3]]\n Output: 3\n Example 2:\n Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]\n Output: 4\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 150, - "title": "Evaluate Reverse Polish Notation", - "question": "class Solution:\n def evalRPN(self, tokens: List[str]) -> int:\n \"\"\"\n You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.\n Evaluate the expression. Return an integer that represents the value of the expression.\n Note that:\n The valid operators are '+', '-', '*', and '/'.\n Each operand may be an integer or another expression.\n The division between two integers always truncates toward zero.\n There will not be any division by zero.\n The input represents a valid arithmetic expression in a reverse polish notation.\n The answer and all the intermediate calculations can be represented in a 32-bit integer.\n Example 1:\n Input: tokens = [\"2\",\"1\",\"+\",\"3\",\"*\"]\n Output: 9\n Explanation: ((2 + 1) * 3) = 9\n Example 2:\n Input: tokens = [\"4\",\"13\",\"5\",\"/\",\"+\"]\n Output: 6\n Explanation: (4 + (13 / 5)) = 6\n Example 3:\n Input: tokens = [\"10\",\"6\",\"9\",\"3\",\"+\",\"-11\",\"*\",\"/\",\"*\",\"17\",\"+\",\"5\",\"+\"]\n Output: 22\n Explanation: ((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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 151, - "title": "Reverse Words in a String", - "question": "class Solution:\n def reverseWords(self, s: str) -> str:\n \"\"\"\n Given an input string s, reverse the order of the words.\n A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.\n Return a string of the words in reverse order concatenated by a single space.\n Note 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:\n Input: s = \"the sky is blue\"\n Output: \"blue is sky the\"\n Example 2:\n Input: s = \" hello world \"\n Output: \"world hello\"\n Explanation: Your reversed string should not contain leading or trailing spaces.\n Example 3:\n Input: s = \"a good example\"\n Output: \"example good a\"\n Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 152, - "title": "Maximum Product Subarray", - "question": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, find a subarray that has the largest product, and return the product.\n The test cases are generated so that the answer will fit in a 32-bit integer.\n Example 1:\n Input: nums = [2,3,-2,4]\n Output: 6\n Explanation: [2,3] has the largest product 6.\n Example 2:\n Input: nums = [-2,0,-1]\n Output: 0\n Explanation: The result cannot be 2, because [-2,-1] is not a subarray.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 153, - "title": "Find Minimum in Rotated Sorted Array", - "question": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].\n Given the sorted rotated array nums of unique elements, return the minimum element of this array.\n You must write an algorithm that runs in O(log n) time.\n Example 1:\n Input: nums = [3,4,5,1,2]\n Output: 1\n Explanation: The original array was [1,2,3,4,5] rotated 3 times.\n Example 2:\n Input: nums = [4,5,6,7,0,1,2]\n Output: 0\n Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.\n Example 3:\n Input: nums = [11,13,15,17]\n Output: 11\n Explanation: The original array was [11,13,15,17] and it was rotated 4 times. \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 154, - "title": "Find Minimum in Rotated Sorted Array II", - "question": "class Solution:\n def findMin(self, nums: List[int]) -> int:\n \"\"\"\n Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:\n [4,5,6,7,0,1,4] if it was rotated 4 times.\n [0,1,4,4,5,6,7] if it was rotated 7 times.\n Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].\n Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.\n You must decrease the overall operation steps as much as possible.\n Example 1:\n Input: nums = [1,3,5]\n Output: 1\n Example 2:\n Input: nums = [2,2,2,0,1]\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 155, - "title": "Min Stack", - "question": "class MinStack:\n def __init__(self):\n def push(self, val: int) -> None:\n def pop(self) -> None:\n def top(self) -> int:\n def getMin(self) -> int:\n \"\"\"\n Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.\n Implement the MinStack class:\n MinStack() initializes the stack object.\n void push(int val) pushes the element val onto the stack.\n void pop() removes the element on the top of the stack.\n int top() gets the top element of the stack.\n int getMin() retrieves the minimum element in the stack.\n You must implement a solution with O(1) time complexity for each function.\n Example 1:\n Input\n [\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n [[],[-2],[0],[-3],[],[],[],[]]\n Output\n [null,null,null,null,-3,null,0,-2]\n Explanation\n MinStack minStack = new MinStack();\n minStack.push(-2);\n minStack.push(0);\n minStack.push(-3);\n minStack.getMin(); // return -3\n minStack.pop();\n minStack.top(); // return 0\n minStack.getMin(); // return -2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 160, - "title": "Intersection of Two Linked Lists", - "question": "class Solution:\n def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:\n \"\"\"\n 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.\n For example, the following two linked lists begin to intersect at node c1:\n The test cases are generated such that there are no cycles anywhere in the entire linked structure.\n Note that the linked lists must retain their original structure after the function returns.\n Custom Judge:\n The inputs to the judge are given as follows (your program is not given these inputs):\n intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node.\n listA - The first linked list.\n listB - The second linked list.\n skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node.\n skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node.\n The 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:\n Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3\n Output: Intersected at '8'\n Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).\n From 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.\n Example 2:\n Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1\n Output: Intersected at '2'\n Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).\n From 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.\n Example 3:\n Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2\n Output: No intersection\n Explanation: 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.\n Explanation: The two lists do not intersect, so return null.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 162, - "title": "Find Peak Element", - "question": "class Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n \"\"\"\n A peak element is an element that is strictly greater than its neighbors.\n Given 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.\n You 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.\n You must write an algorithm that runs in O(log n) time.\n Example 1:\n Input: nums = [1,2,3,1]\n Output: 2\n Explanation: 3 is a peak element and your function should return the index number 2.\n Example 2:\n Input: nums = [1,2,1,3,5,6,4]\n Output: 5\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 164, - "title": "Maximum Gap", - "question": "class Solution:\n def maximumGap(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.\n You must write an algorithm that runs in linear time and uses linear extra space.\n Example 1:\n Input: nums = [3,6,9,1]\n Output: 3\n Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.\n Example 2:\n Input: nums = [10]\n Output: 0\n Explanation: The array contains less than 2 elements, therefore return 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 165, - "title": "Compare Version Numbers", - "question": "class Solution:\n def compareVersion(self, version1: str, version2: str) -> int:\n \"\"\"\n Given two version numbers, version1 and version2, compare them.\n Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.\n To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.\n Return the following:\n If version1 < version2, return -1.\n If version1 > version2, return 1.\n Otherwise, return 0.\n Example 1:\n Input: version1 = \"1.01\", version2 = \"1.001\"\n Output: 0\n Explanation: Ignoring leading zeroes, both \"01\" and \"001\" represent the same integer \"1\".\n Example 2:\n Input: version1 = \"1.0\", version2 = \"1.0.0\"\n Output: 0\n Explanation: version1 does not specify revision 2, which means it is treated as \"0\".\n Example 3:\n Input: version1 = \"0.1\", version2 = \"1.1\"\n Output: -1\n Explanation: version1's revision 0 is \"0\", while version2's revision 0 is \"1\". 0 < 1, so version1 < version2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 166, - "title": "Fraction to Recurring Decimal", - "question": "class Solution:\n def fractionToDecimal(self, numerator: int, denominator: int) -> str:\n \"\"\"\n Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.\n If the fractional part is repeating, enclose the repeating part in parentheses.\n If multiple answers are possible, return any of them.\n It is guaranteed that the length of the answer string is less than 104 for all the given inputs.\n Example 1:\n Input: numerator = 1, denominator = 2\n Output: \"0.5\"\n Example 2:\n Input: numerator = 2, denominator = 1\n Output: \"2\"\n Example 3:\n Input: numerator = 4, denominator = 333\n Output: \"0.(012)\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 167, - "title": "Two Sum II - Input Array Is Sorted", - "question": "class Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \"\"\"\n 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.\n Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.\n The tests are generated such that there is exactly one solution. You may not use the same element twice.\n Your solution must use only constant extra space.\n Example 1:\n Input: numbers = [2,7,11,15], target = 9\n Output: [1,2]\n Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].\n Example 2:\n Input: numbers = [2,3,4], target = 6\n Output: [1,3]\n Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].\n Example 3:\n Input: numbers = [-1,0], target = -1\n Output: [1,2]\n Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 168, - "title": "Excel Sheet Column Title", - "question": "class Solution:\n def convertToTitle(self, columnNumber: int) -> str:\n \"\"\"\n Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.\n For example:\n A -> 1\n B -> 2\n C -> 3\n ...\n Z -> 26\n AA -> 27\n AB -> 28 \n ...\n Example 1:\n Input: columnNumber = 1\n Output: \"A\"\n Example 2:\n Input: columnNumber = 28\n Output: \"AB\"\n Example 3:\n Input: columnNumber = 701\n Output: \"ZY\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 169, - "title": "Majority Element", - "question": "class Solution:\n def majorityElement(self, nums: List[int]) -> int:\n \"\"\"\n Given an array nums of size n, return the majority element.\n The 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:\n Input: nums = [3,2,3]\n Output: 3\n Example 2:\n Input: nums = [2,2,1,1,1,2,2]\n Output: 2\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 171, - "title": "Excel Sheet Column Number", - "question": "class Solution:\n def titleToNumber(self, columnTitle: str) -> int:\n \"\"\"\n Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.\n For example:\n A -> 1\n B -> 2\n C -> 3\n ...\n Z -> 26\n AA -> 27\n AB -> 28 \n ...\n Example 1:\n Input: columnTitle = \"A\"\n Output: 1\n Example 2:\n Input: columnTitle = \"AB\"\n Output: 28\n Example 3:\n Input: columnTitle = \"ZY\"\n Output: 701\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 172, - "title": "Factorial Trailing Zeroes", - "question": "class Solution:\n def trailingZeroes(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the number of trailing zeroes in n!.\n Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.\n Example 1:\n Input: n = 3\n Output: 0\n Explanation: 3! = 6, no trailing zero.\n Example 2:\n Input: n = 5\n Output: 1\n Explanation: 5! = 120, one trailing zero.\n Example 3:\n Input: n = 0\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 173, - "title": "Binary Search Tree Iterator", - "question": "class BSTIterator:\n def __init__(self, root: Optional[TreeNode]):\n def next(self) -> int:\n def hasNext(self) -> bool:\n \"\"\"\n Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):\n BSTIterator(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.\n boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.\n int next() Moves the pointer to the right, then returns the number at the pointer.\n Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.\n You 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:\n Input\n [\"BSTIterator\", \"next\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n [[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]\n Output\n [null, 3, 7, true, 9, true, 15, true, 20, false]\n Explanation\n BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);\n bSTIterator.next(); // return 3\n bSTIterator.next(); // return 7\n bSTIterator.hasNext(); // return True\n bSTIterator.next(); // return 9\n bSTIterator.hasNext(); // return True\n bSTIterator.next(); // return 15\n bSTIterator.hasNext(); // return True\n bSTIterator.next(); // return 20\n bSTIterator.hasNext(); // return False\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 174, - "title": "Dungeon Game", - "question": "class Solution:\n def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:\n \"\"\"\n The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.\n The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.\n Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).\n To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.\n Return the knight's minimum initial health so that he can rescue the princess.\n Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.\n Example 1:\n Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]\n Output: 7\n Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.\n Example 2:\n Input: dungeon = [[0]]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 179, - "title": "Largest Number", - "question": "class Solution:\n def largestNumber(self, nums: List[int]) -> str:\n \"\"\"\n Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.\n Since the result may be very large, so you need to return a string instead of an integer.\n Example 1:\n Input: nums = [10,2]\n Output: \"210\"\n Example 2:\n Input: nums = [3,30,34,5,9]\n Output: \"9534330\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 187, - "title": "Repeated DNA Sequences", - "question": "class Solution:\n def findRepeatedDnaSequences(self, s: str) -> List[str]:\n \"\"\"\n The DNA sequence is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T'.\n For example, \"ACGAATTCCG\" is a DNA sequence.\n When studying DNA, it is useful to identify repeated sequences within the DNA.\n Given 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:\n Input: s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\n Output: [\"AAAAACCCCC\",\"CCCCCAAAAA\"]\n Example 2:\n Input: s = \"AAAAAAAAAAAAA\"\n Output: [\"AAAAAAAAAA\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 188, - "title": "Best Time to Buy and Sell Stock IV", - "question": "class Solution:\n def maxProfit(self, k: int, prices: List[int]) -> int:\n \"\"\"\n You are given an integer array prices where prices[i] is the price of a given stock on the ith day, and an integer k.\n Find the maximum profit you can achieve. You may complete at most k transactions.\n Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\n Input: k = 2, prices = [2,4,1]\n Output: 2\n Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.\n Example 2:\n Input: k = 2, prices = [3,2,6,5,0,3]\n Output: 7\n Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 189, - "title": "Rotate Array", - "question": "class Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.\n Example 1:\n Input: nums = [1,2,3,4,5,6,7], k = 3\n Output: [5,6,7,1,2,3,4]\n Explanation:\n rotate 1 steps to the right: [7,1,2,3,4,5,6]\n rotate 2 steps to the right: [6,7,1,2,3,4,5]\n rotate 3 steps to the right: [5,6,7,1,2,3,4]\n Example 2:\n Input: nums = [-1,-100,3,99], k = 2\n Output: [3,99,-1,-100]\n Explanation: \n rotate 1 steps to the right: [99,-1,-100,3]\n rotate 2 steps to the right: [3,99,-1,-100]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 190, - "title": "Reverse Bits", - "question": "class Solution:\n def reverseBits(self, n: int) -> int:\n \"\"\"\n Reverse bits of a given 32 bits unsigned integer.\n Note:\n Note 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.\n In 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:\n Input: n = 00000010100101000001111010011100\n Output: 964176192 (00111001011110000010100101000000)\n Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.\n Example 2:\n Input: n = 11111111111111111111111111111101\n Output: 3221225471 (10111111111111111111111111111111)\n Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 191, - "title": "Number of 1 Bits", - "question": "class Solution:\n def hammingWeight(self, n: int) -> int:\n \"\"\"\n Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).\n Note:\n Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.\n In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.\n Example 1:\n Input: n = 00000000000000000000000000001011\n Output: 3\n Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.\n Example 2:\n Input: n = 00000000000000000000000010000000\n Output: 1\n Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.\n Example 3:\n Input: n = 11111111111111111111111111111101\n Output: 31\n Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 198, - "title": "House Robber", - "question": "class Solution:\n def rob(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Given 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:\n Input: nums = [1,2,3,1]\n Output: 4\n Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n Total amount you can rob = 1 + 3 = 4.\n Example 2:\n Input: nums = [2,7,9,3,1]\n Output: 12\n Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\n Total amount you can rob = 2 + 9 + 1 = 12.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 199, - "title": "Binary Tree Right Side View", - "question": "class Solution:\n def rightSideView(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n 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:\n Input: root = [1,2,3,null,5,null,4]\n Output: [1,3,4]\n Example 2:\n Input: root = [1,null,3]\n Output: [1,3]\n Example 3:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 200, - "title": "Number of Islands", - "question": "class Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n \"\"\"\n 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.\n An 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:\n Input: 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 ]\n Output: 1\n Example 2:\n Input: 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 ]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 201, - "title": "Bitwise AND of Numbers Range", - "question": "class Solution:\n def rangeBitwiseAnd(self, left: int, right: int) -> int:\n \"\"\"\n 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:\n Input: left = 5, right = 7\n Output: 4\n Example 2:\n Input: left = 0, right = 0\n Output: 0\n Example 3:\n Input: left = 1, right = 2147483647\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 202, - "title": "Happy Number", - "question": "class Solution:\n def isHappy(self, n: int) -> bool:\n \"\"\"\n Write an algorithm to determine if a number n is happy.\n A happy number is a number defined by the following process:\n Starting with any positive integer, replace the number by the sum of the squares of its digits.\n Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.\n Those numbers for which this process ends in 1 are happy.\n Return true if n is a happy number, and false if not.\n Example 1:\n Input: n = 19\n Output: true\n Explanation:\n 12 + 92 = 82\n 82 + 22 = 68\n 62 + 82 = 100\n 12 + 02 + 02 = 1\n Example 2:\n Input: n = 2\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 203, - "title": "Remove Linked List Elements", - "question": "class Solution:\n def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:\n \"\"\"\n 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:\n Input: head = [1,2,6,3,4,5,6], val = 6\n Output: [1,2,3,4,5]\n Example 2:\n Input: head = [], val = 1\n Output: []\n Example 3:\n Input: head = [7,7,7,7], val = 7\n Output: []\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 204, - "title": "Count Primes", - "question": "class Solution:\n def countPrimes(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the number of prime numbers that are strictly less than n.\n Example 1:\n Input: n = 10\n Output: 4\n Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.\n Example 2:\n Input: n = 0\n Output: 0\n Example 3:\n Input: n = 1\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 205, - "title": "Isomorphic Strings", - "question": "class Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n \"\"\"\n Given two strings s and t, determine if they are isomorphic.\n Two strings s and t are isomorphic if the characters in s can be replaced to get t.\n All 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:\n Input: s = \"egg\", t = \"add\"\n Output: true\n Example 2:\n Input: s = \"foo\", t = \"bar\"\n Output: false\n Example 3:\n Input: s = \"paper\", t = \"title\"\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 206, - "title": "Reverse Linked List", - "question": "class Solution:\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a singly linked list, reverse the list, and return the reversed list.\n Example 1:\n Input: head = [1,2,3,4,5]\n Output: [5,4,3,2,1]\n Example 2:\n Input: head = [1,2]\n Output: [2,1]\n Example 3:\n Input: head = []\n Output: []\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 207, - "title": "Course Schedule", - "question": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n \"\"\"\n 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.\n For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\n Return true if you can finish all courses. Otherwise, return false.\n Example 1:\n Input: numCourses = 2, prerequisites = [[1,0]]\n Output: true\n Explanation: There are a total of 2 courses to take. \n To take course 1 you should have finished course 0. So it is possible.\n Example 2:\n Input: numCourses = 2, prerequisites = [[1,0],[0,1]]\n Output: false\n Explanation: There are a total of 2 courses to take. \n To 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 208, - "title": "Implement Trie (Prefix Tree)", - "question": "class Trie:\n def __init__(self):\n def insert(self, word: str) -> None:\n def search(self, word: str) -> bool:\n def startsWith(self, prefix: str) -> bool:\n \"\"\"\n A trie (pronounced as \"try\") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.\n Implement the Trie class:\n Trie() Initializes the trie object.\n void insert(String word) Inserts the string word into the trie.\n boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.\n boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.\n Example 1:\n Input\n [\"Trie\", \"insert\", \"search\", \"search\", \"startsWith\", \"insert\", \"search\"]\n [[], [\"apple\"], [\"apple\"], [\"app\"], [\"app\"], [\"app\"], [\"app\"]]\n Output\n [null, null, true, false, true, null, true]\n Explanation\n Trie trie = new Trie();\n trie.insert(\"apple\");\n trie.search(\"apple\"); // return True\n trie.search(\"app\"); // return False\n trie.startsWith(\"app\"); // return True\n trie.insert(\"app\");\n trie.search(\"app\"); // return True\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 209, - "title": "Minimum Size Subarray Sum", - "question": "class Solution:\n def minSubArrayLen(self, target: int, nums: List[int]) -> int:\n \"\"\"\n Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.\n Example 1:\n Input: target = 7, nums = [2,3,1,2,4,3]\n Output: 2\n Explanation: The subarray [4,3] has the minimal length under the problem constraint.\n Example 2:\n Input: target = 4, nums = [1,4,4]\n Output: 1\n Example 3:\n Input: target = 11, nums = [1,1,1,1,1,1,1,1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 210, - "title": "Course Schedule II", - "question": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.\n Return 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:\n Input: numCourses = 2, prerequisites = [[1,0]]\n Output: [0,1]\n Explanation: 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].\n Example 2:\n Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]\n Output: [0,2,1,3]\n Explanation: 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.\n So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].\n Example 3:\n Input: numCourses = 1, prerequisites = []\n Output: [0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 211, - "title": "Design Add and Search Words Data Structure", - "question": "class WordDictionary:\n def __init__(self):\n def addWord(self, word: str) -> None:\n def search(self, word: str) -> bool:\n \"\"\"\n Design a data structure that supports adding new words and finding if a string matches any previously added string.\n Implement the WordDictionary class:\n WordDictionary() Initializes the object.\n void addWord(word) Adds word to the data structure, it can be matched later.\n bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.\n Example:\n Input\n [\"WordDictionary\",\"addWord\",\"addWord\",\"addWord\",\"search\",\"search\",\"search\",\"search\"]\n [[],[\"bad\"],[\"dad\"],[\"mad\"],[\"pad\"],[\"bad\"],[\".ad\"],[\"b..\"]]\n Output\n [null,null,null,null,false,true,true,true]\n Explanation\n WordDictionary wordDictionary = new WordDictionary();\n wordDictionary.addWord(\"bad\");\n wordDictionary.addWord(\"dad\");\n wordDictionary.addWord(\"mad\");\n wordDictionary.search(\"pad\"); // return False\n wordDictionary.search(\"bad\"); // return True\n wordDictionary.search(\".ad\"); // return True\n wordDictionary.search(\"b..\"); // return True\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 212, - "title": "Word Search II", - "question": "class Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n \"\"\"\n Given an m x n board of characters and a list of strings words, return all words on the board.\n Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.\n Example 1:\n Input: board = [[\"o\",\"a\",\"a\",\"n\"],[\"e\",\"t\",\"a\",\"e\"],[\"i\",\"h\",\"k\",\"r\"],[\"i\",\"f\",\"l\",\"v\"]], words = [\"oath\",\"pea\",\"eat\",\"rain\"]\n Output: [\"eat\",\"oath\"]\n Example 2:\n Input: board = [[\"a\",\"b\"],[\"c\",\"d\"]], words = [\"abcb\"]\n Output: []\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 213, - "title": "House Robber II", - "question": "class Solution:\n def rob(self, nums: List[int]) -> int:\n \"\"\"\n You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.\n Given 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:\n Input: nums = [2,3,2]\n Output: 3\n Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.\n Example 2:\n Input: nums = [1,2,3,1]\n Output: 4\n Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n Total amount you can rob = 1 + 3 = 4.\n Example 3:\n Input: nums = [1,2,3]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 214, - "title": "Shortest Palindrome", - "question": "class Solution:\n def shortestPalindrome(self, s: str) -> str:\n \"\"\"\n You are given a string s. You can convert s to a palindrome by adding characters in front of it.\n Return the shortest palindrome you can find by performing this transformation.\n Example 1:\n Input: s = \"aacecaaa\"\n Output: \"aaacecaaa\"\n Example 2:\n Input: s = \"abcd\"\n Output: \"dcbabcd\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 215, - "title": "Kth Largest Element in an Array", - "question": "class Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an integer array nums and an integer k, return the kth largest element in the array.\n Note that it is the kth largest element in the sorted order, not the kth distinct element.\n You must solve it in O(n) time complexity.\n Example 1:\n Input: nums = [3,2,1,5,6,4], k = 2\n Output: 5\n Example 2:\n Input: nums = [3,2,3,1,2,4,5,5,6], k = 4\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 216, - "title": "Combination Sum III", - "question": "class Solution:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n \"\"\"\n Find all valid combinations of k numbers that sum up to n such that the following conditions are true:\n Only numbers 1 through 9 are used.\n Each number is used at most once.\n Return 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:\n Input: k = 3, n = 7\n Output: [[1,2,4]]\n Explanation:\n 1 + 2 + 4 = 7\n There are no other valid combinations.\n Example 2:\n Input: k = 3, n = 9\n Output: [[1,2,6],[1,3,5],[2,3,4]]\n Explanation:\n 1 + 2 + 6 = 9\n 1 + 3 + 5 = 9\n 2 + 3 + 4 = 9\n There are no other valid combinations.\n Example 3:\n Input: k = 4, n = 1\n Output: []\n Explanation: There are no valid combinations.\n Using 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 217, - "title": "Contains Duplicate", - "question": "class Solution:\n def containsDuplicate(self, nums: List[int]) -> bool:\n \"\"\"\n 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:\n Input: nums = [1,2,3,1]\n Output: true\n Example 2:\n Input: nums = [1,2,3,4]\n Output: false\n Example 3:\n Input: nums = [1,1,1,3,3,4,3,2,4,2]\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 218, - "title": "The Skyline Problem", - "question": "class Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n \"\"\"\n A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively.\n The geometric information of each building is given in the array buildings where buildings[i] = [lefti, righti, heighti]:\n lefti is the x coordinate of the left edge of the ith building.\n righti is the x coordinate of the right edge of the ith building.\n heighti is the height of the ith building.\n You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.\n The skyline should be represented as a list of \"key points\" sorted by their x-coordinate in the form [[x1,y1],[x2,y2],...]. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate 0 and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour.\n Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...,[2 3],[4 5],[7 5],[11 5],[12 7],...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...,[2 3],[4 5],[12 7],...]\n Example 1:\n Input: buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n Output: [[2,10],[3,15],[7,12],[12,0],[15,10],[20,8],[24,0]]\n Explanation:\n Figure A shows the buildings of the input.\n Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list.\n Example 2:\n Input: buildings = [[0,2,3],[2,5,3]]\n Output: [[0,3],[5,0]]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 219, - "title": "Contains Duplicate II", - "question": "class Solution:\n def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:\n \"\"\"\n 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:\n Input: nums = [1,2,3,1], k = 3\n Output: true\n Example 2:\n Input: nums = [1,0,1,1], k = 1\n Output: true\n Example 3:\n Input: nums = [1,2,3,1,2,3], k = 2\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 220, - "title": "Contains Duplicate III", - "question": "class Solution:\n def containsNearbyAlmostDuplicate(self, nums: List[int], indexDiff: int, valueDiff: int) -> bool:\n \"\"\"\n You are given an integer array nums and two integers indexDiff and valueDiff.\n Find a pair of indices (i, j) such that:\n i != j,\n abs(i - j) <= indexDiff.\n abs(nums[i] - nums[j]) <= valueDiff, and\n Return true if such pair exists or false otherwise.\n Example 1:\n Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0\n Output: true\n Explanation: We can choose (i, j) = (0, 3).\n We satisfy the three conditions:\n i != j --> 0 != 3\n abs(i - j) <= indexDiff --> abs(0 - 3) <= 3\n abs(nums[i] - nums[j]) <= valueDiff --> abs(1 - 1) <= 0\n Example 2:\n Input: nums = [1,5,9,1,5,9], indexDiff = 2, valueDiff = 3\n Output: false\n Explanation: After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 221, - "title": "Maximal Square", - "question": "class Solution:\n def maximalSquare(self, matrix: List[List[str]]) -> int:\n \"\"\"\n 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:\n Input: matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]\n Output: 4\n Example 2:\n Input: matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]\n Output: 1\n Example 3:\n Input: matrix = [[\"0\"]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 222, - "title": "Count Complete Tree Nodes", - "question": "class Solution:\n def countNodes(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a complete binary tree, return the number of the nodes in the tree.\n According 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.\n Design an algorithm that runs in less than O(n) time complexity.\n Example 1:\n Input: root = [1,2,3,4,5,6]\n Output: 6\n Example 2:\n Input: root = []\n Output: 0\n Example 3:\n Input: root = [1]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 223, - "title": "Rectangle Area", - "question": "class Solution:\n def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:\n \"\"\"\n Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.\n The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).\n The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).\n Example 1:\n Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2\n Output: 45\n Example 2:\n Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2\n Output: 16\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 224, - "title": "Basic Calculator", - "question": "class Solution:\n def calculate(self, s: str) -> int:\n \"\"\"\n Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.\n Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n Example 1:\n Input: s = \"1 + 1\"\n Output: 2\n Example 2:\n Input: s = \" 2-1 + 2 \"\n Output: 3\n Example 3:\n Input: s = \"(1+(4+5+2)-3)+(6+8)\"\n Output: 23\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 225, - "title": "Implement Stack using Queues", - "question": "class MyStack:\n def __init__(self):\n def push(self, x: int) -> None:\n def pop(self) -> int:\n def top(self) -> int:\n def empty(self) -> bool:\n \"\"\"\n Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).\n Implement the MyStack class:\n void push(int x) Pushes element x to the top of the stack.\n int pop() Removes the element on the top of the stack and returns it.\n int top() Returns the element on the top of the stack.\n boolean empty() Returns true if the stack is empty, false otherwise.\n Notes:\n You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.\n Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.\n Example 1:\n Input\n [\"MyStack\", \"push\", \"push\", \"top\", \"pop\", \"empty\"]\n [[], [1], [2], [], [], []]\n Output\n [null, null, null, 2, 2, false]\n Explanation\n MyStack myStack = new MyStack();\n myStack.push(1);\n myStack.push(2);\n myStack.top(); // return 2\n myStack.pop(); // return 2\n myStack.empty(); // return False\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 226, - "title": "Invert Binary Tree", - "question": "class Solution:\n def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \"\"\"\n Given the root of a binary tree, invert the tree, and return its root.\n Example 1:\n Input: root = [4,2,7,1,3,6,9]\n Output: [4,7,2,9,6,3,1]\n Example 2:\n Input: root = [2,1,3]\n Output: [2,3,1]\n Example 3:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 227, - "title": "Basic Calculator II", - "question": "class Solution:\n def calculate(self, s: str) -> int:\n \"\"\"\n Given a string s which represents an expression, evaluate this expression and return its value. \n The integer division should truncate toward zero.\n You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].\n Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().\n Example 1:\n Input: s = \"3+2*2\"\n Output: 7\n Example 2:\n Input: s = \" 3/2 \"\n Output: 1\n Example 3:\n Input: s = \" 3+5 / 2 \"\n Output: 5\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 228, - "title": "Summary Ranges", - "question": "class Solution:\n def summaryRanges(self, nums: List[int]) -> List[str]:\n \"\"\"\n You are given a sorted unique integer array nums.\n A range [a,b] is the set of all integers from a to b (inclusive).\n Return 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.\n Each range [a,b] in the list should be output as:\n \"a->b\" if a != b\n \"a\" if a == b\n Example 1:\n Input: nums = [0,1,2,4,5,7]\n Output: [\"0->2\",\"4->5\",\"7\"]\n Explanation: The ranges are:\n [0,2] --> \"0->2\"\n [4,5] --> \"4->5\"\n [7,7] --> \"7\"\n Example 2:\n Input: nums = [0,2,3,4,6,8,9]\n Output: [\"0\",\"2->4\",\"6\",\"8->9\"]\n Explanation: The ranges are:\n [0,0] --> \"0\"\n [2,4] --> \"2->4\"\n [6,6] --> \"6\"\n [8,9] --> \"8->9\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 229, - "title": "Majority Element II", - "question": "class Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n \"\"\"\n Given an integer array of size n, find all elements that appear more than \u230a n/3 \u230b times.\n Example 1:\n Input: nums = [3,2,3]\n Output: [3]\n Example 2:\n Input: nums = [1]\n Output: [1]\n Example 3:\n Input: nums = [1,2]\n Output: [1,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 230, - "title": "Kth Smallest Element in a BST", - "question": "class Solution:\n def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:\n \"\"\"\n 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:\n Input: root = [3,1,4,null,2], k = 1\n Output: 1\n Example 2:\n Input: root = [5,3,6,2,4,null,null,1], k = 3\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 231, - "title": "Power of Two", - "question": "class Solution:\n def isPowerOfTwo(self, n: int) -> bool:\n \"\"\"\n Given an integer n, return true if it is a power of two. Otherwise, return false.\n An integer n is a power of two, if there exists an integer x such that n == 2x.\n Example 1:\n Input: n = 1\n Output: true\n Explanation: 20 = 1\n Example 2:\n Input: n = 16\n Output: true\n Explanation: 24 = 16\n Example 3:\n Input: n = 3\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 232, - "title": "Implement Queue using Stacks", - "question": "class MyQueue:\n def __init__(self):\n def push(self, x: int) -> None:\n def pop(self) -> int:\n def peek(self) -> int:\n def empty(self) -> bool:\n \"\"\"\n Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).\n Implement the MyQueue class:\n void push(int x) Pushes element x to the back of the queue.\n int pop() Removes the element from the front of the queue and returns it.\n int peek() Returns the element at the front of the queue.\n boolean empty() Returns true if the queue is empty, false otherwise.\n Notes:\n You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.\n Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.\n Example 1:\n Input\n [\"MyQueue\", \"push\", \"push\", \"peek\", \"pop\", \"empty\"]\n [[], [1], [2], [], [], []]\n Output\n [null, null, null, 1, 1, false]\n Explanation\n MyQueue myQueue = new MyQueue();\n myQueue.push(1); // queue is: [1]\n myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)\n myQueue.peek(); // return 1\n myQueue.pop(); // return 1, queue is [2]\n myQueue.empty(); // return false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 233, - "title": "Number of Digit One", - "question": "class Solution:\n def countDigitOne(self, n: int) -> int:\n \"\"\"\n 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:\n Input: n = 13\n Output: 6\n Example 2:\n Input: n = 0\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 234, - "title": "Palindrome Linked List", - "question": "class Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n \"\"\"\n Given the head of a singly linked list, return true if it is a palindrome or false otherwise.\n Example 1:\n Input: head = [1,2,2,1]\n Output: true\n Example 2:\n Input: head = [1,2]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 235, - "title": "Lowest Common Ancestor of a Binary Search Tree", - "question": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n \"\"\"\n Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.\n According 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:\n Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8\n Output: 6\n Explanation: The LCA of nodes 2 and 8 is 6.\n Example 2:\n Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4\n Output: 2\n Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.\n Example 3:\n Input: root = [2,1], p = 2, q = 1\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 236, - "title": "Lowest Common Ancestor of a Binary Tree", - "question": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n \"\"\"\n Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.\n According 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:\n Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n Output: 3\n Explanation: The LCA of nodes 5 and 1 is 3.\n Example 2:\n Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n Output: 5\n Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n Example 3:\n Input: root = [1,2], p = 1, q = 2\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 237, - "title": "Delete Node in a Linked List", - "question": "class Solution:\n def deleteNode(self, node):\n \"\"\"\n :type node: ListNode\n :rtype: void Do not return anything, modify node in-place instead.\n There is a singly-linked list head and we want to delete a node node in it.\n You are given the node to be deleted node. You will not be given access to the first node of head.\n All 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.\n Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:\n The value of the given node should not exist in the linked list.\n The number of nodes in the linked list should decrease by one.\n All the values before node should be in the same order.\n All the values after node should be in the same order.\n Custom testing:\n For 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.\n We will build the linked list and pass the node to your function.\n The output will be the entire list after calling your function.\n Example 1:\n Input: head = [4,5,1,9], node = 5\n Output: [4,1,9]\n Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.\n Example 2:\n Input: head = [4,5,1,9], node = 1\n Output: [4,5,9]\n Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 238, - "title": "Product of Array Except Self", - "question": "class Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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].\n The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.\n You must write an algorithm that runs in O(n) time and without using the division operation.\n Example 1:\n Input: nums = [1,2,3,4]\n Output: [24,12,8,6]\n Example 2:\n Input: nums = [-1,1,0,-3,3]\n Output: [0,0,9,0,0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 239, - "title": "Sliding Window Maximum", - "question": "class Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n \"\"\"\n You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.\n Return the max sliding window.\n Example 1:\n Input: nums = [1,3,-1,-3,5,3,6,7], k = 3\n Output: [3,3,5,5,6,7]\n Explanation: \n Window position Max\n --------------- -----\n [1 3 -1] -3 5 3 6 7 3\n 1 [3 -1 -3] 5 3 6 7 3\n 1 3 [-1 -3 5] 3 6 7 5\n 1 3 -1 [-3 5 3] 6 7 5\n 1 3 -1 -3 [5 3 6] 7 6\n 1 3 -1 -3 5 [3 6 7] 7\n Example 2:\n Input: nums = [1], k = 1\n Output: [1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 240, - "title": "Search a 2D Matrix II", - "question": "class Solution:\n def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:\n \"\"\"\n Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:\n Integers in each row are sorted in ascending from left to right.\n Integers in each column are sorted in ascending from top to bottom.\n Example 1:\n Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5\n Output: true\n Example 2:\n Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 241, - "title": "Different Ways to Add Parentheses", - "question": "class Solution:\n def diffWaysToCompute(self, expression: str) -> List[int]:\n \"\"\"\n Given a string expression of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. You may return the answer in any order.\n The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed 104.\n Example 1:\n Input: expression = \"2-1-1\"\n Output: [0,2]\n Explanation:\n ((2-1)-1) = 0 \n (2-(1-1)) = 2\n Example 2:\n Input: expression = \"2*3-4*5\"\n Output: [-34,-14,-10,-10,10]\n Explanation:\n (2*(3-(4*5))) = -34 \n ((2*3)-(4*5)) = -14 \n ((2*(3-4))*5) = -10 \n (2*((3-4)*5)) = -10 \n (((2*3)-4)*5) = 10\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 242, - "title": "Valid Anagram", - "question": "class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n \"\"\"\n Given two strings s and t, return true if t is an anagram of s, and false otherwise.\n An 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:\n Input: s = \"anagram\", t = \"nagaram\"\n Output: true\n Example 2:\n Input: s = \"rat\", t = \"car\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 257, - "title": "Binary Tree Paths", - "question": "class Solution:\n def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:\n \"\"\"\n Given the root of a binary tree, return all root-to-leaf paths in any order.\n A leaf is a node with no children.\n Example 1:\n Input: root = [1,2,3,null,5]\n Output: [\"1->2->5\",\"1->3\"]\n Example 2:\n Input: root = [1]\n Output: [\"1\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 258, - "title": "Add Digits", - "question": "class Solution:\n def addDigits(self, num: int) -> int:\n \"\"\"\n Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.\n Example 1:\n Input: num = 38\n Output: 2\n Explanation: The process is\n 38 --> 3 + 8 --> 11\n 11 --> 1 + 1 --> 2 \n Since 2 has only one digit, return it.\n Example 2:\n Input: num = 0\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 260, - "title": "Single Number III", - "question": "class Solution:\n def singleNumber(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.\n Example 1:\n Input: nums = [1,2,1,3,2,5]\n Output: [3,5]\n Explanation: [5, 3] is also a valid answer.\n Example 2:\n Input: nums = [-1,0]\n Output: [-1,0]\n Example 3:\n Input: nums = [0,1]\n Output: [1,0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 263, - "title": "Ugly Number", - "question": "class Solution:\n def isUgly(self, n: int) -> bool:\n \"\"\"\n An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\n Given an integer n, return true if n is an ugly number.\n Example 1:\n Input: n = 6\n Output: true\n Explanation: 6 = 2 \u00d7 3\n Example 2:\n Input: n = 1\n Output: true\n Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n Example 3:\n Input: n = 14\n Output: false\n Explanation: 14 is not ugly since it includes the prime factor 7.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 264, - "title": "Ugly Number II", - "question": "class Solution:\n def nthUglyNumber(self, n: int) -> int:\n \"\"\"\n An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.\n Given an integer n, return the nth ugly number.\n Example 1:\n Input: n = 10\n Output: 12\n Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.\n Example 2:\n Input: n = 1\n Output: 1\n Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 268, - "title": "Missing Number", - "question": "class Solution:\n def missingNumber(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [3,0,1]\n Output: 2\n Explanation: 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.\n Example 2:\n Input: nums = [0,1]\n Output: 2\n Explanation: 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.\n Example 3:\n Input: nums = [9,6,4,2,3,5,7,0,1]\n Output: 8\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 273, - "title": "Integer to English Words", - "question": "class Solution:\n def numberToWords(self, num: int) -> str:\n \"\"\"\n Convert a non-negative integer num to its English words representation.\n Example 1:\n Input: num = 123\n Output: \"One Hundred Twenty Three\"\n Example 2:\n Input: num = 12345\n Output: \"Twelve Thousand Three Hundred Forty Five\"\n Example 3:\n Input: num = 1234567\n Output: \"One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 274, - "title": "H-Index", - "question": "class Solution:\n def hIndex(self, citations: List[int]) -> int:\n \"\"\"\n Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index.\n According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n \u2212 h papers have no more than h citations each.\n If there are several possible values for h, the maximum one is taken as the h-index.\n Example 1:\n Input: citations = [3,0,6,1,5]\n Output: 3\n Explanation: [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.\n Since 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.\n Example 2:\n Input: citations = [1,3,1]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 275, - "title": "H-Index II", - "question": "class Solution:\n def hIndex(self, citations: List[int]) -> int:\n \"\"\"\n 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 an ascending order, return compute the researcher's h-index.\n According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n \u2212 h papers have no more than h citations each.\n If there are several possible values for h, the maximum one is taken as the h-index.\n You must write an algorithm that runs in logarithmic time.\n Example 1:\n Input: citations = [0,1,3,5,6]\n Output: 3\n Explanation: [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.\n Since 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.\n Example 2:\n Input: citations = [1,2,100]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 278, - "title": "First Bad Version", - "question": "class Solution:\n def firstBadVersion(self, n: int) -> int:\n \"\"\"\n 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.\n Suppose 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.\n You 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:\n Input: n = 5, bad = 4\n Output: 4\n Explanation:\n call isBadVersion(3) -> false\n call isBadVersion(5) -> true\n call isBadVersion(4) -> true\n Then 4 is the first bad version.\n Example 2:\n Input: n = 1, bad = 1\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 279, - "title": "Perfect Squares", - "question": "class Solution:\n def numSquares(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the least number of perfect square numbers that sum to n.\n A 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:\n Input: n = 12\n Output: 3\n Explanation: 12 = 4 + 4 + 4.\n Example 2:\n Input: n = 13\n Output: 2\n Explanation: 13 = 4 + 9.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 282, - "title": "Expression Add Operators", - "question": "class Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n \"\"\"\n 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.\n Note that operands in the returned expressions should not contain leading zeros.\n Example 1:\n Input: num = \"123\", target = 6\n Output: [\"1*2*3\",\"1+2+3\"]\n Explanation: Both \"1*2*3\" and \"1+2+3\" evaluate to 6.\n Example 2:\n Input: num = \"232\", target = 8\n Output: [\"2*3+2\",\"2+3*2\"]\n Explanation: Both \"2*3+2\" and \"2+3*2\" evaluate to 8.\n Example 3:\n Input: num = \"3456237490\", target = 9191\n Output: []\n Explanation: There are no expressions that can be created from \"3456237490\" to evaluate to 9191.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 283, - "title": "Move Zeroes", - "question": "class Solution:\n def moveZeroes(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.\n Note that you must do this in-place without making a copy of the array.\n Example 1:\n Input: nums = [0,1,0,3,12]\n Output: [1,3,12,0,0]\n Example 2:\n Input: nums = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 284, - "title": "Peeking Iterator", - "question": " \"\"\"\n Design an iterator that supports the peek operation on an existing iterator in addition to the hasNext and the next operations.\n Implement the PeekingIterator class:\n PeekingIterator(Iterator nums) Initializes the object with the given integer iterator iterator.\n int next() Returns the next element in the array and moves the pointer to the next element.\n boolean hasNext() Returns true if there are still elements in the array.\n int peek() Returns the next element in the array without moving the pointer.\n Note: Each language may have a different implementation of the constructor and Iterator, but they all support the int next() and boolean hasNext() functions.\n Example 1:\n Input\n [\"PeekingIterator\", \"next\", \"peek\", \"next\", \"next\", \"hasNext\"]\n [[[1, 2, 3]], [], [], [], [], []]\n Output\n [null, 1, 2, 2, 3, false]\n Explanation\n PeekingIterator peekingIterator = new PeekingIterator([1, 2, 3]); // [1,2,3]\n peekingIterator.next(); // return 1, the pointer moves to the next element [1,2,3].\n peekingIterator.peek(); // return 2, the pointer does not move [1,2,3].\n peekingIterator.next(); // return 2, the pointer moves to the next element [1,2,3]\n peekingIterator.next(); // return 3, the pointer moves to the next element [1,2,3]\n peekingIterator.hasNext(); // return False\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 287, - "title": "Find the Duplicate Number", - "question": "class Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n \"\"\"\n Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.\n There is only one repeated number in nums, return this repeated number.\n You must solve the problem without modifying the array nums and uses only constant extra space.\n Example 1:\n Input: nums = [1,3,4,2,2]\n Output: 2\n Example 2:\n Input: nums = [3,1,3,4,2]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 289, - "title": "Game of Life", - "question": "class Solution:\n def gameOfLife(self, board: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n 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.\"\n The 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):\n Any live cell with fewer than two live neighbors dies as if caused by under-population.\n Any live cell with two or three live neighbors lives on to the next generation.\n Any live cell with more than three live neighbors dies, as if by over-population.\n Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.\n The 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:\n Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]\n Example 2:\n Input: board = [[1,1],[1,0]]\n Output: [[1,1],[1,1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 290, - "title": "Word Pattern", - "question": "class Solution:\n def wordPattern(self, pattern: str, s: str) -> bool:\n \"\"\"\n Given a pattern and a string s, find if s follows the same pattern.\n Here 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:\n Input: pattern = \"abba\", s = \"dog cat cat dog\"\n Output: true\n Example 2:\n Input: pattern = \"abba\", s = \"dog cat cat fish\"\n Output: false\n Example 3:\n Input: pattern = \"aaaa\", s = \"dog cat cat dog\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 292, - "title": "Nim Game", - "question": "class Solution:\n def canWinNim(self, n: int) -> bool:\n \"\"\"\n You are playing the following Nim Game with your friend:\n Initially, there is a heap of stones on the table.\n You and your friend will alternate taking turns, and you go first.\n On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.\n The one who removes the last stone is the winner.\n Given 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:\n Input: n = 4\n Output: false\n Explanation: These are the possible outcomes:\n 1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.\n 2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.\n 3. You remove 3 stones. Your friend removes the last stone. Your friend wins.\n In all outcomes, your friend wins.\n Example 2:\n Input: n = 1\n Output: true\n Example 3:\n Input: n = 2\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 295, - "title": "Find Median from Data Stream", - "question": "class MedianFinder:\n def __init__(self):\n def addNum(self, num: int) -> None:\n def findMedian(self) -> float:\n \"\"\"\n The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.\n For example, for arr = [2,3,4], the median is 3.\n For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.\n Implement the MedianFinder class:\n MedianFinder() initializes the MedianFinder object.\n void addNum(int num) adds the integer num from the data stream to the data structure.\n double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\n Input\n [\"MedianFinder\", \"addNum\", \"addNum\", \"findMedian\", \"addNum\", \"findMedian\"]\n [[], [1], [2], [], [3], []]\n Output\n [null, null, null, 1.5, null, 2.0]\n Explanation\n MedianFinder medianFinder = new MedianFinder();\n medianFinder.addNum(1); // arr = [1]\n medianFinder.addNum(2); // arr = [1, 2]\n medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\n medianFinder.addNum(3); // arr[1, 2, 3]\n medianFinder.findMedian(); // return 2.0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 297, - "title": "Serialize and Deserialize Binary Tree", - "question": "class Codec:\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n :type root: TreeNode\n :rtype: str\n Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.\n Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.\n Example 1:\n Input: root = [1,2,3,null,null,4,5]\n Output: [1,2,3,null,null,4,5]\n Example 2:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 299, - "title": "Bulls and Cows", - "question": "class Solution:\n def getHint(self, secret: str, guess: str) -> str:\n \"\"\"\n You are playing the Bulls and Cows game with your friend.\n You 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:\n The number of \"bulls\", which are digits in the guess that are in the correct position.\n The 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.\n Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.\n The 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:\n Input: secret = \"1807\", guess = \"7810\"\n Output: \"1A3B\"\n Explanation: Bulls are connected with a '|' and cows are underlined:\n \"1807\"\n |\n \"7810\"\n Example 2:\n Input: secret = \"1123\", guess = \"0111\"\n Output: \"1A1B\"\n Explanation: Bulls are connected with a '|' and cows are underlined:\n \"1123\" \"1123\"\n | or |\n \"0111\" \"0111\"\n Note 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 300, - "title": "Longest Increasing Subsequence", - "question": "class Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the length of the longest strictly increasing subsequence.\n Example 1:\n Input: nums = [10,9,2,5,3,7,101,18]\n Output: 4\n Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.\n Example 2:\n Input: nums = [0,1,0,3,2,3]\n Output: 4\n Example 3:\n Input: nums = [7,7,7,7,7,7,7]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 301, - "title": "Remove Invalid Parentheses", - "question": "class Solution:\n def removeInvalidParentheses(self, s: str) -> List[str]:\n \"\"\"\n Given a string s that contains parentheses and letters, remove the minimum number of invalid parentheses to make the input string valid.\n Return 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:\n Input: s = \"()())()\"\n Output: [\"(())()\",\"()()()\"]\n Example 2:\n Input: s = \"(a)())()\"\n Output: [\"(a())()\",\"(a)()()\"]\n Example 3:\n Input: s = \")(\"\n Output: [\"\"]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 303, - "title": "Range Sum Query - Immutable", - "question": "class NumArray:\n def __init__(self, nums: List[int]):\n def sumRange(self, left: int, right: int) -> int:\n \"\"\"\n Given an integer array nums, handle multiple queries of the following type:\n Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.\n Implement the NumArray class:\n NumArray(int[] nums) Initializes the object with the integer array nums.\n int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).\n Example 1:\n Input\n [\"NumArray\", \"sumRange\", \"sumRange\", \"sumRange\"]\n [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]\n Output\n [null, 1, -1, -3]\n Explanation\n NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);\n numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1\n numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1\n numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 304, - "title": "Range Sum Query 2D - Immutable", - "question": "class NumMatrix:\n def __init__(self, matrix: List[List[int]]):\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n \"\"\"\n Given a 2D matrix matrix, handle multiple queries of the following type:\n Calculate the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).\n Implement the NumMatrix class:\n NumMatrix(int[][] matrix) Initializes the object with the integer matrix matrix.\n int sumRegion(int row1, int col1, int row2, int col2) Returns the sum of the elements of matrix inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).\n You must design an algorithm where sumRegion works on O(1) time complexity.\n Example 1:\n Input\n [\"NumMatrix\", \"sumRegion\", \"sumRegion\", \"sumRegion\"]\n [[[[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]], [2, 1, 4, 3], [1, 1, 2, 2], [1, 2, 2, 4]]\n Output\n [null, 8, 11, 12]\n Explanation\n NumMatrix numMatrix = new NumMatrix([[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]]);\n numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)\n numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)\n numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 306, - "title": "Additive Number", - "question": "class Solution:\n def isAdditiveNumber(self, num: str) -> bool:\n \"\"\"\n An additive number is a string whose digits can form an additive sequence.\n A 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.\n Given a string containing only digits, return true if it is an additive number or false otherwise.\n Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.\n Example 1:\n Input: \"112358\"\n Output: true\n Explanation: \n The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. \n 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8\n Example 2:\n Input: \"199100199\"\n Output: true\n Explanation: \n The additive sequence is: 1, 99, 100, 199. \n 1 + 99 = 100, 99 + 100 = 199\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 307, - "title": "Range Sum Query - Mutable", - "question": "class NumArray:\n def __init__(self, nums: List[int]):\n def update(self, index: int, val: int) -> None:\n def sumRange(self, left: int, right: int) -> int:\n \"\"\"\n Given an integer array nums, handle multiple queries of the following types:\n Update the value of an element in nums.\n Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.\n Implement the NumArray class:\n NumArray(int[] nums) Initializes the object with the integer array nums.\n void update(int index, int val) Updates the value of nums[index] to be val.\n int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).\n Example 1:\n Input\n [\"NumArray\", \"sumRange\", \"update\", \"sumRange\"]\n [[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]\n Output\n [null, 9, null, 8]\n Explanation\n NumArray numArray = new NumArray([1, 3, 5]);\n numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9\n numArray.update(1, 2); // nums = [1, 2, 5]\n numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 309, - "title": "Best Time to Buy and Sell Stock with Cooldown", - "question": "class Solution:\n def maxProfit(self, prices: List[int]) -> int:\n \"\"\"\n You are given an array prices where prices[i] is the price of a given stock on the ith day.\n Find 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:\n After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).\n Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\n Input: prices = [1,2,3,0,2]\n Output: 3\n Explanation: transactions = [buy, sell, cooldown, buy, sell]\n Example 2:\n Input: prices = [1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 310, - "title": "Minimum Height Trees", - "question": "class Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n Given 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).\n Return a list of all MHTs' root labels. You can return the answer in any order.\n The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.\n Example 1:\n Input: n = 4, edges = [[1,0],[1,2],[1,3]]\n Output: [1]\n Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.\n Example 2:\n Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\n Output: [3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 312, - "title": "Burst Balloons", - "question": "class Solution:\n def maxCoins(self, nums: List[int]) -> int:\n \"\"\"\n You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.\n If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.\n Return the maximum coins you can collect by bursting the balloons wisely.\n Example 1:\n Input: nums = [3,1,5,8]\n Output: 167\n Explanation:\n nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []\n coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167\n Example 2:\n Input: nums = [1,5]\n Output: 10\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 313, - "title": "Super Ugly Number", - "question": "class Solution:\n def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:\n \"\"\"\n A super ugly number is a positive integer whose prime factors are in the array primes.\n Given an integer n and an array of integers primes, return the nth super ugly number.\n The nth super ugly number is guaranteed to fit in a 32-bit signed integer.\n Example 1:\n Input: n = 12, primes = [2,7,13,19]\n Output: 32\n Explanation: [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].\n Example 2:\n Input: n = 1, primes = [2,3,5]\n Output: 1\n Explanation: 1 has no prime factors, therefore all of its prime factors are in the array primes = [2,3,5].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 315, - "title": "Count of Smaller Numbers After Self", - "question": "class Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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:\n Input: nums = [5,2,6,1]\n Output: [2,1,1,0]\n Explanation:\n To the right of 5 there are 2 smaller elements (2 and 1).\n To the right of 2 there is only 1 smaller element (1).\n To the right of 6 there is 1 smaller element (1).\n To the right of 1 there is 0 smaller element.\n Example 2:\n Input: nums = [-1]\n Output: [0]\n Example 3:\n Input: nums = [-1,-1]\n Output: [0,0]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 316, - "title": "Remove Duplicate Letters", - "question": "class Solution:\n def removeDuplicateLetters(self, s: str) -> str:\n \"\"\"\n Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.\n Example 1:\n Input: s = \"bcabc\"\n Output: \"abc\"\n Example 2:\n Input: s = \"cbacdcbc\"\n Output: \"acdb\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 318, - "title": "Maximum Product of Word Lengths", - "question": "class Solution:\n def maxProduct(self, words: List[str]) -> int:\n \"\"\"\n 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:\n Input: words = [\"abcw\",\"baz\",\"foo\",\"bar\",\"xtfn\",\"abcdef\"]\n Output: 16\n Explanation: The two words can be \"abcw\", \"xtfn\".\n Example 2:\n Input: words = [\"a\",\"ab\",\"abc\",\"d\",\"cd\",\"bcd\",\"abcd\"]\n Output: 4\n Explanation: The two words can be \"ab\", \"cd\".\n Example 3:\n Input: words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\n Output: 0\n Explanation: No such pair of words.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 319, - "title": "Bulb Switcher", - "question": "class Solution:\n def bulbSwitch(self, n: int) -> int:\n \"\"\"\n There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.\n On 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.\n Return the number of bulbs that are on after n rounds.\n Example 1:\n Input: n = 3\n Output: 1\n Explanation: At first, the three bulbs are [off, off, off].\n After the first round, the three bulbs are [on, on, on].\n After the second round, the three bulbs are [on, off, on].\n After the third round, the three bulbs are [on, off, off]. \n So you should return 1 because there is only one bulb is on.\n Example 2:\n Input: n = 0\n Output: 0\n Example 3:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 321, - "title": "Create Maximum Number", - "question": "class Solution:\n def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:\n \"\"\"\n You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k.\n Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.\n Return an array of the k digits representing the answer.\n Example 1:\n Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5\n Output: [9,8,6,5,3]\n Example 2:\n Input: nums1 = [6,7], nums2 = [6,0,4], k = 5\n Output: [6,7,6,0,4]\n Example 3:\n Input: nums1 = [3,9], nums2 = [8,9], k = 3\n Output: [9,8,9]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 322, - "title": "Coin Change", - "question": "class Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n \"\"\"\n You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\n Return 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.\n You may assume that you have an infinite number of each kind of coin.\n Example 1:\n Input: coins = [1,2,5], amount = 11\n Output: 3\n Explanation: 11 = 5 + 5 + 1\n Example 2:\n Input: coins = [2], amount = 3\n Output: -1\n Example 3:\n Input: coins = [1], amount = 0\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 324, - "title": "Wiggle Sort II", - "question": "class Solution:\n def wiggleSort(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....\n You may assume the input array always has a valid answer.\n Example 1:\n Input: nums = [1,5,1,1,6,4]\n Output: [1,6,1,5,1,4]\n Explanation: [1,4,1,5,1,6] is also accepted.\n Example 2:\n Input: nums = [1,3,2,2,3,1]\n Output: [2,3,1,3,1,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 326, - "title": "Power of Three", - "question": "class Solution:\n def isPowerOfThree(self, n: int) -> bool:\n \"\"\"\n Given an integer n, return true if it is a power of three. Otherwise, return false.\n An integer n is a power of three, if there exists an integer x such that n == 3x.\n Example 1:\n Input: n = 27\n Output: true\n Explanation: 27 = 33\n Example 2:\n Input: n = 0\n Output: false\n Explanation: There is no x where 3x = 0.\n Example 3:\n Input: n = -1\n Output: false\n Explanation: There is no x where 3x = (-1).\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 327, - "title": "Count of Range Sum", - "question": "class Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n \"\"\"\n Given an integer array nums and two integers lower and upper, return the number of range sums that lie in [lower, upper] inclusive.\n Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j inclusive, where i <= j.\n Example 1:\n Input: nums = [-2,5,-1], lower = -2, upper = 2\n Output: 3\n Explanation: The three ranges are: [0,0], [2,2], and [0,2] and their respective sums are: -2, -1, 2.\n Example 2:\n Input: nums = [0], lower = 0, upper = 0\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 328, - "title": "Odd Even Linked List", - "question": "class Solution:\n def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n 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.\n The first node is considered odd, and the second node is even, and so on.\n Note that the relative order inside both the even and odd groups should remain as it was in the input.\n You must solve the problem in O(1) extra space complexity and O(n) time complexity.\n Example 1:\n Input: head = [1,2,3,4,5]\n Output: [1,3,5,2,4]\n Example 2:\n Input: head = [2,1,3,5,6,4,7]\n Output: [2,3,6,7,1,5,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 329, - "title": "Longest Increasing Path in a Matrix", - "question": "class Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n \"\"\"\n Given an m x n integers matrix, return the length of the longest increasing path in matrix.\n From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).\n Example 1:\n Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]\n Output: 4\n Explanation: The longest increasing path is [1, 2, 6, 9].\n Example 2:\n Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]\n Output: 4\n Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.\n Example 3:\n Input: matrix = [[1]]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 330, - "title": "Patching Array", - "question": "class Solution:\n def minPatches(self, nums: List[int], n: int) -> int:\n \"\"\"\n Given a sorted integer array nums and an integer n, add/patch elements to the array such that any number in the range [1, n] inclusive can be formed by the sum of some elements in the array.\n Return the minimum number of patches required.\n Example 1:\n Input: nums = [1,3], n = 6\n Output: 1\n Explanation:\n Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.\n Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].\n Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].\n So we only need 1 patch.\n Example 2:\n Input: nums = [1,5,10], n = 20\n Output: 2\n Explanation: The two patches can be [2, 4].\n Example 3:\n Input: nums = [1,2,2], n = 5\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 331, - "title": "Verify Preorder Serialization of a Binary Tree", - "question": "class Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n \"\"\"\n 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 '#'.\n For example, the above binary tree can be serialized to the string \"9,3,4,#,#,1,#,#,2,#,6,#,#\", where '#' represents a null node.\n Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.\n It is guaranteed that each comma-separated value in the string must be either an integer or a character '#' representing null pointer.\n You may assume that the input format is always valid.\n For example, it could never contain two consecutive commas, such as \"1,,3\".\n Note: You are not allowed to reconstruct the tree.\n Example 1:\n Input: preorder = \"9,3,4,#,#,1,#,#,2,#,6,#,#\"\n Output: true\n Example 2:\n Input: preorder = \"1,#\"\n Output: false\n Example 3:\n Input: preorder = \"9,#,#,1\"\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 332, - "title": "Reconstruct Itinerary", - "question": "class Solution:\n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n \"\"\"\n 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.\n All 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.\n For example, the itinerary [\"JFK\", \"LGA\"] has a smaller lexical order than [\"JFK\", \"LGB\"].\n You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.\n Example 1:\n Input: tickets = [[\"MUC\",\"LHR\"],[\"JFK\",\"MUC\"],[\"SFO\",\"SJC\"],[\"LHR\",\"SFO\"]]\n Output: [\"JFK\",\"MUC\",\"LHR\",\"SFO\",\"SJC\"]\n Example 2:\n Input: tickets = [[\"JFK\",\"SFO\"],[\"JFK\",\"ATL\"],[\"SFO\",\"ATL\"],[\"ATL\",\"JFK\"],[\"ATL\",\"SFO\"]]\n Output: [\"JFK\",\"ATL\",\"JFK\",\"SFO\",\"ATL\",\"SFO\"]\n Explanation: Another possible reconstruction is [\"JFK\",\"SFO\",\"ATL\",\"JFK\",\"ATL\",\"SFO\"] but it is larger in lexical order.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 334, - "title": "Increasing Triplet Subsequence", - "question": "class Solution:\n def increasingTriplet(self, nums: List[int]) -> bool:\n \"\"\"\n 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:\n Input: nums = [1,2,3,4,5]\n Output: true\n Explanation: Any triplet where i < j < k is valid.\n Example 2:\n Input: nums = [5,4,3,2,1]\n Output: false\n Explanation: No triplet exists.\n Example 3:\n Input: nums = [2,1,5,0,4,6]\n Output: true\n Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 335, - "title": "Self Crossing", - "question": "class Solution:\n def isSelfCrossing(self, distance: List[int]) -> bool:\n \"\"\"\n You are given an array of integers distance.\n You 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.\n Return true if your path crosses itself or false if it does not.\n Example 1:\n Input: distance = [2,1,1,2]\n Output: true\n Explanation: The path crosses itself at the point (0, 1).\n Example 2:\n Input: distance = [1,2,3,4]\n Output: false\n Explanation: The path does not cross itself at any point.\n Example 3:\n Input: distance = [1,1,1,2,1]\n Output: true\n Explanation: The path crosses itself at the point (0, 0).\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 336, - "title": "Palindrome Pairs", - "question": "class Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n \"\"\"\n You are given a 0-indexed array of unique strings words.\n A palindrome pair is a pair of integers (i, j) such that:\n 0 <= i, j < words.length,\n i != j, and\n words[i] + words[j] (the concatenation of the two strings) is a palindrome.\n Return an array of all the palindrome pairs of words.\n Example 1:\n Input: words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\n Output: [[0,1],[1,0],[3,2],[2,4]]\n Explanation: The palindromes are [\"abcddcba\",\"dcbaabcd\",\"slls\",\"llssssll\"]\n Example 2:\n Input: words = [\"bat\",\"tab\",\"cat\"]\n Output: [[0,1],[1,0]]\n Explanation: The palindromes are [\"battab\",\"tabbat\"]\n Example 3:\n Input: words = [\"a\",\"\"]\n Output: [[0,1],[1,0]]\n Explanation: The palindromes are [\"a\",\"a\"]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 337, - "title": "House Robber III", - "question": "class Solution:\n def rob(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.\n Besides 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.\n Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.\n Example 1:\n Input: root = [3,2,3,null,3,null,1]\n Output: 7\n Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.\n Example 2:\n Input: root = [3,4,5,1,3,null,1]\n Output: 9\n Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 338, - "title": "Counting Bits", - "question": "class Solution:\n def countBits(self, n: int) -> List[int]:\n \"\"\"\n 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:\n Input: n = 2\n Output: [0,1,1]\n Explanation:\n 0 --> 0\n 1 --> 1\n 2 --> 10\n Example 2:\n Input: n = 5\n Output: [0,1,1,2,1,2]\n Explanation:\n 0 --> 0\n 1 --> 1\n 2 --> 10\n 3 --> 11\n 4 --> 100\n 5 --> 101\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 341, - "title": "Flatten Nested List Iterator", - "question": " \"\"\"\n You are given a nested list of integers nestedList. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.\n Implement the NestedIterator class:\n NestedIterator(List nestedList) Initializes the iterator with the nested list nestedList.\n int next() Returns the next integer in the nested list.\n boolean hasNext() Returns true if there are still some integers in the nested list and false otherwise.\n Your code will be tested with the following pseudocode:\n initialize iterator with nestedList\n res = []\n while iterator.hasNext()\n append iterator.next() to the end of res\n return res\n If res matches the expected flattened list, then your code will be judged as correct.\n Example 1:\n Input: nestedList = [[1,1],2,[1,1]]\n Output: [1,1,2,1,1]\n Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].\n Example 2:\n Input: nestedList = [1,[4,[6]]]\n Output: [1,4,6]\n Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 342, - "title": "Power of Four", - "question": "class Solution:\n def isPowerOfFour(self, n: int) -> bool:\n \"\"\"\n Given an integer n, return true if it is a power of four. Otherwise, return false.\n An integer n is a power of four, if there exists an integer x such that n == 4x.\n Example 1:\n Input: n = 16\n Output: true\n Example 2:\n Input: n = 5\n Output: false\n Example 3:\n Input: n = 1\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 343, - "title": "Integer Break", - "question": "class Solution:\n def integerBreak(self, n: int) -> int:\n \"\"\"\n Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.\n Return the maximum product you can get.\n Example 1:\n Input: n = 2\n Output: 1\n Explanation: 2 = 1 + 1, 1 \u00d7 1 = 1.\n Example 2:\n Input: n = 10\n Output: 36\n Explanation: 10 = 3 + 3 + 4, 3 \u00d7 3 \u00d7 4 = 36.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 344, - "title": "Reverse String", - "question": "class Solution:\n def reverseString(self, s: List[str]) -> None:\n \"\"\"\n Do not return anything, modify s in-place instead.\n Write a function that reverses a string. The input string is given as an array of characters s.\n You must do this by modifying the input array in-place with O(1) extra memory.\n Example 1:\n Input: s = [\"h\",\"e\",\"l\",\"l\",\"o\"]\n Output: [\"o\",\"l\",\"l\",\"e\",\"h\"]\n Example 2:\n Input: s = [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"]\n Output: [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 345, - "title": "Reverse Vowels of a String", - "question": "class Solution:\n def reverseVowels(self, s: str) -> str:\n \"\"\"\n Given a string s, reverse only all the vowels in the string and return it.\n The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases, more than once.\n Example 1:\n Input: s = \"hello\"\n Output: \"holle\"\n Example 2:\n Input: s = \"leetcode\"\n Output: \"leotcede\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 347, - "title": "Top K Frequent Elements", - "question": "class Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n \"\"\"\n 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:\n Input: nums = [1,1,1,2,2,3], k = 2\n Output: [1,2]\n Example 2:\n Input: nums = [1], k = 1\n Output: [1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 349, - "title": "Intersection of Two Arrays", - "question": "class Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.\n Example 1:\n Input: nums1 = [1,2,2,1], nums2 = [2,2]\n Output: [2]\n Example 2:\n Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n Output: [9,4]\n Explanation: [4,9] is also accepted.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 350, - "title": "Intersection of Two Arrays II", - "question": "class Solution:\n def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n 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:\n Input: nums1 = [1,2,2,1], nums2 = [2,2]\n Output: [2,2]\n Example 2:\n Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]\n Output: [4,9]\n Explanation: [9,4] is also accepted.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 352, - "title": "Data Stream as Disjoint Intervals", - "question": "class SummaryRanges:\n def __init__(self):\n def addNum(self, value: int) -> None:\n def getIntervals(self) -> List[List[int]]:\n \"\"\"\n Given a data stream input of non-negative integers a1, a2, ..., an, summarize the numbers seen so far as a list of disjoint intervals.\n Implement the SummaryRanges class:\n SummaryRanges() Initializes the object with an empty stream.\n void addNum(int value) Adds the integer value to the stream.\n int[][] getIntervals() Returns a summary of the integers in the stream currently as a list of disjoint intervals [starti, endi]. The answer should be sorted by starti.\n Example 1:\n Input\n [\"SummaryRanges\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\", \"addNum\", \"getIntervals\"]\n [[], [1], [], [3], [], [7], [], [2], [], [6], []]\n Output\n [null, null, [[1, 1]], null, [[1, 1], [3, 3]], null, [[1, 1], [3, 3], [7, 7]], null, [[1, 3], [7, 7]], null, [[1, 3], [6, 7]]]\n Explanation\n SummaryRanges summaryRanges = new SummaryRanges();\n summaryRanges.addNum(1); // arr = [1]\n summaryRanges.getIntervals(); // return [[1, 1]]\n summaryRanges.addNum(3); // arr = [1, 3]\n summaryRanges.getIntervals(); // return [[1, 1], [3, 3]]\n summaryRanges.addNum(7); // arr = [1, 3, 7]\n summaryRanges.getIntervals(); // return [[1, 1], [3, 3], [7, 7]]\n summaryRanges.addNum(2); // arr = [1, 2, 3, 7]\n summaryRanges.getIntervals(); // return [[1, 3], [7, 7]]\n summaryRanges.addNum(6); // arr = [1, 2, 3, 6, 7]\n summaryRanges.getIntervals(); // return [[1, 3], [6, 7]]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 354, - "title": "Russian Doll Envelopes", - "question": "class Solution:\n def maxEnvelopes(self, envelopes: List[List[int]]) -> int:\n \"\"\"\n You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.\n One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.\n Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).\n Note: You cannot rotate an envelope.\n Example 1:\n Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]\n Output: 3\n Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).\n Example 2:\n Input: envelopes = [[1,1],[1,1],[1,1]]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 355, - "title": "Design Twitter", - "question": "class Twitter:\n def __init__(self):\n def postTweet(self, userId: int, tweetId: int) -> None:\n def getNewsFeed(self, userId: int) -> List[int]:\n def follow(self, followerId: int, followeeId: int) -> None:\n def unfollow(self, followerId: int, followeeId: int) -> None:\n \"\"\"\n Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed.\n Implement the Twitter class:\n Twitter() Initializes your twitter object.\n void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId.\n List getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent.\n void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId.\n void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.\n Example 1:\n Input\n [\"Twitter\", \"postTweet\", \"getNewsFeed\", \"follow\", \"postTweet\", \"getNewsFeed\", \"unfollow\", \"getNewsFeed\"]\n [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]\n Output\n [null, null, [5], null, null, [6, 5], null, [5]]\n Explanation\n Twitter twitter = new Twitter();\n twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).\n twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]\n twitter.follow(1, 2); // User 1 follows user 2.\n twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).\n twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.\n twitter.unfollow(1, 2); // User 1 unfollows user 2.\n twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 357, - "title": "Count Numbers with Unique Digits", - "question": "class Solution:\n def countNumbersWithUniqueDigits(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the count of all numbers with unique digits, x, where 0 <= x < 10n.\n Example 1:\n Input: n = 2\n Output: 91\n Explanation: 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\n Example 2:\n Input: n = 0\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 363, - "title": "Max Sum of Rectangle No Larger Than K", - "question": "class Solution:\n def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:\n \"\"\"\n Given an m x n matrix matrix and an integer k, return the max sum of a rectangle in the matrix such that its sum is no larger than k.\n It is guaranteed that there will be a rectangle with a sum no larger than k.\n Example 1:\n Input: matrix = [[1,0,1],[0,-2,3]], k = 2\n Output: 2\n Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).\n Example 2:\n Input: matrix = [[2,2,-1]], k = 3\n Output: 3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 365, - "title": "Water and Jug Problem", - "question": "class Solution:\n def canMeasureWater(self, jug1Capacity: int, jug2Capacity: int, targetCapacity: int) -> bool:\n \"\"\"\n You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.\n If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.\n Operations allowed:\n Fill any of the jugs with water.\n Empty any of the jugs.\n Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.\n Example 1:\n Input: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4\n Output: true\n Explanation: The famous Die Hard example \n Example 2:\n Input: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5\n Output: false\n Example 3:\n Input: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 367, - "title": "Valid Perfect Square", - "question": "class Solution:\n def isPerfectSquare(self, num: int) -> bool:\n \"\"\"\n Given a positive integer num, return true if num is a perfect square or false otherwise.\n A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.\n You must not use any built-in library function, such as sqrt.\n Example 1:\n Input: num = 16\n Output: true\n Explanation: We return true because 4 * 4 = 16 and 4 is an integer.\n Example 2:\n Input: num = 14\n Output: false\n Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an integer.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 368, - "title": "Largest Divisible Subset", - "question": "class Solution:\n def largestDivisibleSubset(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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:\n answer[i] % answer[j] == 0, or\n answer[j] % answer[i] == 0\n If there are multiple solutions, return any of them.\n Example 1:\n Input: nums = [1,2,3]\n Output: [1,2]\n Explanation: [1,3] is also accepted.\n Example 2:\n Input: nums = [1,2,4,8]\n Output: [1,2,4,8]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 371, - "title": "Sum of Two Integers", - "question": "class Solution:\n def getSum(self, a: int, b: int) -> int:\n \"\"\"\n Given two integers a and b, return the sum of the two integers without using the operators + and -.\n Example 1:\n Input: a = 1, b = 2\n Output: 3\n Example 2:\n Input: a = 2, b = 3\n Output: 5\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 372, - "title": "Super Pow", - "question": "class Solution:\n def superPow(self, a: int, b: List[int]) -> int:\n \"\"\"\n 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:\n Input: a = 2, b = [3]\n Output: 8\n Example 2:\n Input: a = 2, b = [1,0]\n Output: 1024\n Example 3:\n Input: a = 1, b = [4,3,3,8,5,2]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 373, - "title": "Find K Pairs with Smallest Sums", - "question": "class Solution:\n def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:\n \"\"\"\n You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.\n Define a pair (u, v) which consists of one element from the first array and one element from the second array.\n Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.\n Example 1:\n Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3\n Output: [[1,2],[1,4],[1,6]]\n Explanation: 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]\n Example 2:\n Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2\n Output: [[1,1],[1,1]]\n Explanation: 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 Example 3:\n Input: nums1 = [1,2], nums2 = [3], k = 3\n Output: [[1,3],[2,3]]\n Explanation: All possible pairs are returned from the sequence: [1,3],[2,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 374, - "title": "Guess Number Higher or Lower", - "question": "class Solution:\n def guessNumber(self, n: int) -> int:\n \"\"\"\n We are playing the Guess Game. The game is as follows:\n I pick a number from 1 to n. You have to guess which number I picked.\n Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.\n You 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).\n 1: Your guess is lower than the number I picked (i.e. num < pick).\n 0: your guess is equal to the number I picked (i.e. num == pick).\n Return the number that I picked.\n Example 1:\n Input: n = 10, pick = 6\n Output: 6\n Example 2:\n Input: n = 1, pick = 1\n Output: 1\n Example 3:\n Input: n = 2, pick = 1\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 375, - "title": "Guess Number Higher or Lower II", - "question": "class Solution:\n def getMoneyAmount(self, n: int) -> int:\n \"\"\"\n We are playing the Guessing Game. The game will work as follows:\n I pick a number between 1 and n.\n You guess a number.\n If you guess the right number, you win the game.\n If you guess the wrong number, then I will tell you whether the number I picked is higher or lower, and you will continue guessing.\n Every time you guess a wrong number x, you will pay x dollars. If you run out of money, you lose the game.\n Given a particular n, return the minimum amount of money you need to guarantee a win regardless of what number I pick.\n Example 1:\n Input: n = 10\n Output: 16\n Explanation: 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.\n The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.\n Example 2:\n Input: n = 1\n Output: 0\n Explanation: There is only one possible number, so you can guess 1 and not have to pay anything.\n Example 3:\n Input: n = 2\n Output: 1\n Explanation: 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.\n The worst case is that you pay $1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 376, - "title": "Wiggle Subsequence", - "question": "class Solution:\n def wiggleMaxLength(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.\n In 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.\n A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.\n Given an integer array nums, return the length of the longest wiggle subsequence of nums.\n Example 1:\n Input: nums = [1,7,4,9,2,5]\n Output: 6\n Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).\n Example 2:\n Input: nums = [1,17,5,10,13,15,10,5,16,8]\n Output: 7\n Explanation: There are several subsequences that achieve this length.\n One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).\n Example 3:\n Input: nums = [1,2,3,4,5,6,7,8,9]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 377, - "title": "Combination Sum IV", - "question": "class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n \"\"\"\n Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.\n The test cases are generated so that the answer can fit in a 32-bit integer.\n Example 1:\n Input: nums = [1,2,3], target = 4\n Output: 7\n Explanation:\n The 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)\n Note that different sequences are counted as different combinations.\n Example 2:\n Input: nums = [9], target = 3\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 378, - "title": "Kth Smallest Element in a Sorted Matrix", - "question": "class Solution:\n def kthSmallest(self, matrix: List[List[int]], k: int) -> int:\n \"\"\"\n 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.\n Note that it is the kth smallest element in the sorted order, not the kth distinct element.\n You must find a solution with a memory complexity better than O(n2).\n Example 1:\n Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8\n Output: 13\n Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13\n Example 2:\n Input: matrix = [[-5]], k = 1\n Output: -5\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 380, - "title": "Insert Delete GetRandom O(1)", - "question": "class RandomizedSet:\n def __init__(self):\n def insert(self, val: int) -> bool:\n def remove(self, val: int) -> bool:\n def getRandom(self) -> int:\n \"\"\"\n Implement the RandomizedSet class:\n RandomizedSet() Initializes the RandomizedSet object.\n bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.\n bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.\n int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.\n You must implement the functions of the class such that each function works in average O(1) time complexity.\n Example 1:\n Input\n [\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"]\n [[], [1], [2], [2], [], [1], [2], []]\n Output\n [null, true, false, true, 2, true, false, 2]\n Explanation\n RandomizedSet randomizedSet = new RandomizedSet();\n randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.\n randomizedSet.remove(2); // Returns false as 2 does not exist in the set.\n randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].\n randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.\n randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].\n randomizedSet.insert(2); // 2 was already in the set, so return false.\n randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 381, - "title": "Insert Delete GetRandom O(1) - Duplicates allowed", - "question": "class RandomizedCollection:\n def __init__(self):\n def insert(self, val: int) -> bool:\n def remove(self, val: int) -> bool:\n def getRandom(self) -> int:\n \"\"\"\n RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.\n Implement the RandomizedCollection class:\n RandomizedCollection() Initializes the empty RandomizedCollection object.\n bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise.\n bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them.\n int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains.\n You must implement the functions of the class such that each function works on average O(1) time complexity.\n Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.\n Example 1:\n Input\n [\"RandomizedCollection\", \"insert\", \"insert\", \"insert\", \"getRandom\", \"remove\", \"getRandom\"]\n [[], [1], [1], [2], [], [1], []]\n Output\n [null, true, false, true, 2, true, 1]\n Explanation\n RandomizedCollection randomizedCollection = new RandomizedCollection();\n randomizedCollection.insert(1); // return true since the collection does not contain 1.\n // Inserts 1 into the collection.\n randomizedCollection.insert(1); // return false since the collection contains 1.\n // Inserts another 1 into the collection. Collection now contains [1,1].\n randomizedCollection.insert(2); // return true since the collection does not contain 2.\n // Inserts 2 into the collection. Collection now contains [1,1,2].\n randomizedCollection.getRandom(); // getRandom should:\n // - return 1 with probability 2/3, or\n // - return 2 with probability 1/3.\n randomizedCollection.remove(1); // return true since the collection contains 1.\n // Removes 1 from the collection. Collection now contains [1,2].\n randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 382, - "title": "Linked List Random Node", - "question": "class Solution:\n def __init__(self, head: Optional[ListNode]):\n def getRandom(self) -> int:\n \"\"\"\n 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.\n Implement the Solution class:\n Solution(ListNode head) Initializes the object with the head of the singly-linked list head.\n int 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:\n Input\n [\"Solution\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\", \"getRandom\"]\n [[[1, 2, 3]], [], [], [], [], []]\n Output\n [null, 1, 3, 2, 2, 3]\n Explanation\n Solution solution = new Solution([1, 2, 3]);\n solution.getRandom(); // return 1\n solution.getRandom(); // return 3\n solution.getRandom(); // return 2\n solution.getRandom(); // return 2\n solution.getRandom(); // return 3\n // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 383, - "title": "Ransom Note", - "question": "class Solution:\n def canConstruct(self, ransomNote: str, magazine: str) -> bool:\n \"\"\"\n Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.\n Each letter in magazine can only be used once in ransomNote.\n Example 1:\n Input: ransomNote = \"a\", magazine = \"b\"\n Output: false\n Example 2:\n Input: ransomNote = \"aa\", magazine = \"ab\"\n Output: false\n Example 3:\n Input: ransomNote = \"aa\", magazine = \"aab\"\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 384, - "title": "Shuffle an Array", - "question": "class Solution:\n def __init__(self, nums: List[int]):\n def reset(self) -> List[int]:\n def shuffle(self) -> List[int]:\n \"\"\"\n 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.\n Implement the Solution class:\n Solution(int[] nums) Initializes the object with the integer array nums.\n int[] reset() Resets the array to its original configuration and returns it.\n int[] shuffle() Returns a random shuffling of the array.\n Example 1:\n Input\n [\"Solution\", \"shuffle\", \"reset\", \"shuffle\"]\n [[[1, 2, 3]], [], [], []]\n Output\n [null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]\n Explanation\n Solution solution = new Solution([1, 2, 3]);\n solution.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]\n solution.reset(); // Resets the array back to its original configuration [1,2,3]. Return [1, 2, 3]\n solution.shuffle(); // Returns the random shuffling of array [1,2,3]. Example: return [1, 3, 2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 385, - "title": "Mini Parser", - "question": " \"\"\"\n Given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger.\n Each element is either an integer or a list whose elements may also be integers or other lists.\n Example 1:\n Input: s = \"324\"\n Output: 324\n Explanation: You should return a NestedInteger object which contains a single integer 324.\n Example 2:\n Input: s = \"[123,[456,[789]]]\"\n Output: [123,[456,[789]]]\n Explanation: Return a NestedInteger object containing a nested list with 2 elements:\n 1. An integer containing value 123.\n 2. 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 386, - "title": "Lexicographical Numbers", - "question": "class Solution:\n def lexicalOrder(self, n: int) -> List[int]:\n \"\"\"\n Given an integer n, return all the numbers in the range [1, n] sorted in lexicographical order.\n You must write an algorithm that runs in O(n) time and uses O(1) extra space. \n Example 1:\n Input: n = 13\n Output: [1,10,11,12,13,2,3,4,5,6,7,8,9]\n Example 2:\n Input: n = 2\n Output: [1,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 387, - "title": "First Unique Character in a String", - "question": "class Solution:\n def firstUniqChar(self, s: str) -> int:\n \"\"\"\n 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:\n Input: s = \"leetcode\"\n Output: 0\n Example 2:\n Input: s = \"loveleetcode\"\n Output: 2\n Example 3:\n Input: s = \"aabb\"\n Output: -1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 388, - "title": "Longest Absolute File Path", - "question": "class Solution:\n def lengthLongestPath(self, input: str) -> int:\n \"\"\"\n Suppose we have a file system that stores both files and directories. An example of one system is represented in the following picture:\n Here, 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.\n In text form, it looks like this (with \u27f6 representing the tab character):\n dir\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\n If 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.\n Every 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.\n Given 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.\n Note that the testcases are generated such that the file system is valid and no file or directory name has length 0.\n Example 1:\n Input: input = \"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\"\n Output: 20\n Explanation: We have only one file, and the absolute path is \"dir/subdir2/file.ext\" of length 20.\n Example 2:\n Input: input = \"dir\\n\\tsubdir1\\n\\t\\tfile1.ext\\n\\t\\tsubsubdir1\\n\\tsubdir2\\n\\t\\tsubsubdir2\\n\\t\\t\\tfile2.ext\"\n Output: 32\n Explanation: We have two files:\n \"dir/subdir1/file1.ext\" of length 21\n \"dir/subdir2/subsubdir2/file2.ext\" of length 32.\n We return 32 since it is the longest absolute path to a file.\n Example 3:\n Input: input = \"a\"\n Output: 0\n Explanation: We do not have any files, just a single directory named \"a\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 389, - "title": "Find the Difference", - "question": "class Solution:\n def findTheDifference(self, s: str, t: str) -> str:\n \"\"\"\n You are given two strings s and t.\n String t is generated by random shuffling string s and then add one more letter at a random position.\n Return the letter that was added to t.\n Example 1:\n Input: s = \"abcd\", t = \"abcde\"\n Output: \"e\"\n Explanation: 'e' is the letter that was added.\n Example 2:\n Input: s = \"\", t = \"y\"\n Output: \"y\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 390, - "title": "Elimination Game", - "question": "class Solution:\n def lastRemaining(self, n: int) -> int:\n \"\"\"\n 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:\n Starting from left to right, remove the first number and every other number afterward until you reach the end of the list.\n Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers.\n Keep repeating the steps again, alternating left to right and right to left, until a single number remains.\n Given the integer n, return the last number that remains in arr.\n Example 1:\n Input: n = 9\n Output: 6\n Explanation:\n arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n arr = [2, 4, 6, 8]\n arr = [2, 6]\n arr = [6]\n Example 2:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 391, - "title": "Perfect Rectangle", - "question": "class Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n \"\"\"\n Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point of it is (ai, bi).\n Return true if all the rectangles together form an exact cover of a rectangular region.\n Example 1:\n Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n Output: true\n Explanation: All 5 rectangles together form an exact cover of a rectangular region.\n Example 2:\n Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2],[3,2,4,4]]\n Output: false\n Explanation: Because there is a gap between the two rectangular regions.\n Example 3:\n Input: rectangles = [[1,1,3,3],[3,1,4,2],[1,3,2,4],[2,2,4,4]]\n Output: false\n Explanation: Because two of the rectangles overlap with each other.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 392, - "title": "Is Subsequence", - "question": "class Solution:\n def isSubsequence(self, s: str, t: str) -> bool:\n \"\"\"\n Given two strings s and t, return true if s is a subsequence of t, or false otherwise.\n A 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:\n Input: s = \"abc\", t = \"ahbgdc\"\n Output: true\n Example 2:\n Input: s = \"axc\", t = \"ahbgdc\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 393, - "title": "UTF-8 Validation", - "question": "class Solution:\n def validUtf8(self, data: List[int]) -> bool:\n \"\"\"\n 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).\n A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:\n For a 1-byte character, the first bit is a 0, followed by its Unicode code.\n For 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.\n This 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\n x denotes a bit in the binary form of a byte that may be either 0 or 1.\n Note: 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:\n Input: data = [197,130,1]\n Output: true\n Explanation: data represents the octet sequence: 11000101 10000010 00000001.\n It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.\n Example 2:\n Input: data = [235,140,4]\n Output: false\n Explanation: data represented the octet sequence: 11101011 10001100 00000100.\n The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.\n The next byte is a continuation byte which starts with 10 and that's correct.\n But the second continuation byte does not start with 10, so it is invalid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 394, - "title": "Decode String", - "question": "class Solution:\n def decodeString(self, s: str) -> str:\n \"\"\"\n Given an encoded string, return its decoded string.\n The 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.\n You 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].\n The test cases are generated so that the length of the output will never exceed 105.\n Example 1:\n Input: s = \"3[a]2[bc]\"\n Output: \"aaabcbc\"\n Example 2:\n Input: s = \"3[a2[c]]\"\n Output: \"accaccacc\"\n Example 3:\n Input: s = \"2[abc]3[cd]ef\"\n Output: \"abcabccdcdcdef\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 395, - "title": "Longest Substring with At Least K Repeating Characters", - "question": "class Solution:\n def longestSubstring(self, s: str, k: int) -> int:\n \"\"\"\n 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.\n Example 1:\n Input: s = \"aaabb\", k = 3\n Output: 3\n Explanation: The longest substring is \"aaa\", as 'a' is repeated 3 times.\n Example 2:\n Input: s = \"ababbc\", k = 2\n Output: 5\n Explanation: The longest substring is \"ababb\", as 'a' is repeated 2 times and 'b' is repeated 3 times.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 396, - "title": "Rotate Function", - "question": "class Solution:\n def maxRotateFunction(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums of length n.\n Assume arrk to be an array obtained by rotating nums by k positions clock-wise. We define the rotation function F on nums as follow:\n F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].\n Return the maximum value of F(0), F(1), ..., F(n-1).\n The test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\n Input: nums = [4,3,2,6]\n Output: 26\n Explanation:\n F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25\n F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16\n F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23\n F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26\n So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.\n Example 2:\n Input: nums = [100]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 397, - "title": "Integer Replacement", - "question": "class Solution:\n def integerReplacement(self, n: int) -> int:\n \"\"\"\n Given a positive integer n, you can apply one of the following operations:\n If n is even, replace n with n / 2.\n If n is odd, replace n with either n + 1 or n - 1.\n Return the minimum number of operations needed for n to become 1.\n Example 1:\n Input: n = 8\n Output: 3\n Explanation: 8 -> 4 -> 2 -> 1\n Example 2:\n Input: n = 7\n Output: 4\n Explanation: 7 -> 8 -> 4 -> 2 -> 1\n or 7 -> 6 -> 3 -> 2 -> 1\n Example 3:\n Input: n = 4\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 398, - "title": "Random Pick Index", - "question": "class Solution:\n def __init__(self, nums: List[int]):\n def pick(self, target: int) -> int:\n \"\"\"\n 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.\n Implement the Solution class:\n Solution(int[] nums) Initializes the object with the array nums.\n int 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:\n Input\n [\"Solution\", \"pick\", \"pick\", \"pick\"]\n [[[1, 2, 3, 3, 3]], [3], [1], [3]]\n Output\n [null, 4, 0, 2]\n Explanation\n Solution solution = new Solution([1, 2, 3, 3, 3]);\n solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.\n solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 399, - "title": "Evaluate Division", - "question": "class Solution:\n def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n \"\"\"\n 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.\n You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query where you must find the answer for Cj / Dj = ?.\n Return the answers to all queries. If a single answer cannot be determined, return -1.0.\n Note: 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.\n Example 1:\n Input: equations = [[\"a\",\"b\"],[\"b\",\"c\"]], values = [2.0,3.0], queries = [[\"a\",\"c\"],[\"b\",\"a\"],[\"a\",\"e\"],[\"a\",\"a\"],[\"x\",\"x\"]]\n Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]\n Explanation: \n Given: a / b = 2.0, b / c = 3.0\n queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?\n return: [6.0, 0.5, -1.0, 1.0, -1.0 ]\n Example 2:\n Input: equations = [[\"a\",\"b\"],[\"b\",\"c\"],[\"bc\",\"cd\"]], values = [1.5,2.5,5.0], queries = [[\"a\",\"c\"],[\"c\",\"b\"],[\"bc\",\"cd\"],[\"cd\",\"bc\"]]\n Output: [3.75000,0.40000,5.00000,0.20000]\n Example 3:\n Input: equations = [[\"a\",\"b\"]], values = [0.5], queries = [[\"a\",\"b\"],[\"b\",\"a\"],[\"a\",\"c\"],[\"x\",\"y\"]]\n Output: [0.50000,2.00000,-1.00000,-1.00000]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 400, - "title": "Nth Digit", - "question": "class Solution:\n def findNthDigit(self, n: int) -> int:\n \"\"\"\n 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:\n Input: n = 3\n Output: 3\n Example 2:\n Input: n = 11\n Output: 0\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 401, - "title": "Binary Watch", - "question": "class Solution:\n def readBinaryWatch(self, turnedOn: int) -> List[str]:\n \"\"\"\n 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.\n For example, the below binary watch reads \"4:51\".\n Given 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.\n The hour must not contain a leading zero.\n For example, \"01:00\" is not valid. It should be \"1:00\".\n The minute must be consist of two digits and may contain a leading zero.\n For example, \"10:2\" is not valid. It should be \"10:02\".\n Example 1:\n Input: turnedOn = 1\n Output: [\"0:01\",\"0:02\",\"0:04\",\"0:08\",\"0:16\",\"0:32\",\"1:00\",\"2:00\",\"4:00\",\"8:00\"]\n Example 2:\n Input: turnedOn = 9\n Output: []\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 402, - "title": "Remove K Digits", - "question": "class Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n \"\"\"\n 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:\n Input: num = \"1432219\", k = 3\n Output: \"1219\"\n Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.\n Example 2:\n Input: num = \"10200\", k = 1\n Output: \"200\"\n Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.\n Example 3:\n Input: num = \"10\", k = 2\n Output: \"0\"\n Explanation: Remove all the digits from the number and it is left with nothing which is 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 403, - "title": "Frog Jump", - "question": "class Solution:\n def canCross(self, stones: List[int]) -> bool:\n \"\"\"\n A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.\n Given a list of stones' positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.\n If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.\n Example 1:\n Input: stones = [0,1,3,5,6,8,12,17]\n Output: true\n Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.\n Example 2:\n Input: stones = [0,1,2,3,4,8,9,11]\n Output: false\n Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 404, - "title": "Sum of Left Leaves", - "question": "class Solution:\n def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return the sum of all left leaves.\n A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.\n Example 1:\n Input: root = [3,9,20,null,null,15,7]\n Output: 24\n Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.\n Example 2:\n Input: root = [1]\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 405, - "title": "Convert a Number to Hexadecimal", - "question": "class Solution:\n def toHex(self, num: int) -> str:\n \"\"\"\n Given an integer num, return a string representing its hexadecimal representation. For negative integers, two\u2019s complement method is used.\n All 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.\n Note: You are not allowed to use any built-in library method to directly solve this problem.\n Example 1:\n Input: num = 26\n Output: \"1a\"\n Example 2:\n Input: num = -1\n Output: \"ffffffff\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 406, - "title": "Queue Reconstruction by Height", - "question": "class Solution:\n def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n Reconstruct 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:\n Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\n Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\n Explanation:\n Person 0 has height 5 with no other people taller or the same height in front.\n Person 1 has height 7 with no other people taller or the same height in front.\n Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.\n Person 3 has height 6 with one person taller or the same height in front, which is person 1.\n Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.\n Person 5 has height 7 with one person taller or the same height in front, which is person 1.\n Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.\n Example 2:\n Input: people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\n Output: [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 407, - "title": "Trapping Rain Water II", - "question": "class Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n \"\"\"\n 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:\n Input: heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\n Output: 4\n Explanation: After the rain, water is trapped between the blocks.\n We have two small ponds 1 and 3 units trapped.\n The total volume of water trapped is 4.\n Example 2:\n Input: 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]]\n Output: 10\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 409, - "title": "Longest Palindrome", - "question": "class Solution:\n def longestPalindrome(self, s: str) -> int:\n \"\"\"\n 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.\n Letters are case sensitive, for example, \"Aa\" is not considered a palindrome here.\n Example 1:\n Input: s = \"abccccdd\"\n Output: 7\n Explanation: One longest palindrome that can be built is \"dccaccd\", whose length is 7.\n Example 2:\n Input: s = \"a\"\n Output: 1\n Explanation: The longest palindrome that can be built is \"a\", whose length is 1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 410, - "title": "Split Array Largest Sum", - "question": "class Solution:\n def splitArray(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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.\n Return the minimized largest sum of the split.\n A subarray is a contiguous part of the array.\n Example 1:\n Input: nums = [7,2,5,10,8], k = 2\n Output: 18\n Explanation: There are four ways to split nums into two subarrays.\n The best way is to split it into [7,2,5] and [10,8], where the largest sum among the two subarrays is only 18.\n Example 2:\n Input: nums = [1,2,3,4,5], k = 2\n Output: 9\n Explanation: There are four ways to split nums into two subarrays.\n The 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 412, - "title": "Fizz Buzz", - "question": "class Solution:\n def fizzBuzz(self, n: int) -> List[str]:\n \"\"\"\n Given an integer n, return a string array answer (1-indexed) where:\n answer[i] == \"FizzBuzz\" if i is divisible by 3 and 5.\n answer[i] == \"Fizz\" if i is divisible by 3.\n answer[i] == \"Buzz\" if i is divisible by 5.\n answer[i] == i (as a string) if none of the above conditions are true.\n Example 1:\n Input: n = 3\n Output: [\"1\",\"2\",\"Fizz\"]\n Example 2:\n Input: n = 5\n Output: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"]\n Example 3:\n Input: n = 15\n Output: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 413, - "title": "Arithmetic Slices", - "question": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n \"\"\"\n An integer array is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n For example, [1,3,5,7,9], [7,7,7,7], and [3,-1,-5,-9] are arithmetic sequences.\n Given an integer array nums, return the number of arithmetic subarrays of nums.\n A subarray is a contiguous subsequence of the array.\n Example 1:\n Input: nums = [1,2,3,4]\n Output: 3\n Explanation: We have 3 arithmetic slices in nums: [1, 2, 3], [2, 3, 4] and [1,2,3,4] itself.\n Example 2:\n Input: nums = [1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 414, - "title": "Third Maximum Number", - "question": "class Solution:\n def thirdMax(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [3,2,1]\n Output: 1\n Explanation:\n The first distinct maximum is 3.\n The second distinct maximum is 2.\n The third distinct maximum is 1.\n Example 2:\n Input: nums = [1,2]\n Output: 2\n Explanation:\n The first distinct maximum is 2.\n The second distinct maximum is 1.\n The third distinct maximum does not exist, so the maximum (2) is returned instead.\n Example 3:\n Input: nums = [2,2,3,1]\n Output: 1\n Explanation:\n The first distinct maximum is 3.\n The second distinct maximum is 2 (both 2's are counted together since they have the same value).\n The third distinct maximum is 1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 415, - "title": "Add Strings", - "question": "class Solution:\n def addStrings(self, num1: str, num2: str) -> str:\n \"\"\"\n Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.\n You 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:\n Input: num1 = \"11\", num2 = \"123\"\n Output: \"134\"\n Example 2:\n Input: num1 = \"456\", num2 = \"77\"\n Output: \"533\"\n Example 3:\n Input: num1 = \"0\", num2 = \"0\"\n Output: \"0\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 416, - "title": "Partition Equal Subset Sum", - "question": "class Solution:\n def canPartition(self, nums: List[int]) -> bool:\n \"\"\"\n 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:\n Input: nums = [1,5,11,5]\n Output: true\n Explanation: The array can be partitioned as [1, 5, 5] and [11].\n Example 2:\n Input: nums = [1,2,3,5]\n Output: false\n Explanation: The array cannot be partitioned into equal sum subsets.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 417, - "title": "Pacific Atlantic Water Flow", - "question": "class Solution:\n def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n The 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).\n The 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.\n Return 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:\n Input: 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]]\n Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]\n Explanation: 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\n Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans.\n Example 2:\n Input: heights = [[1]]\n Output: [[0,0]]\n Explanation: The water can flow from the only cell to the Pacific and Atlantic oceans.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 419, - "title": "Battleships in a Board", - "question": "class Solution:\n def countBattleships(self, board: List[List[str]]) -> int:\n \"\"\"\n Given an m x n matrix board where each cell is a battleship 'X' or empty '.', return the number of the battleships on board.\n Battleships 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:\n Input: board = [[\"X\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"],[\".\",\".\",\".\",\"X\"]]\n Output: 2\n Example 2:\n Input: board = [[\".\"]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 420, - "title": "Strong Password Checker", - "question": "class Solution:\n def strongPasswordChecker(self, password: str) -> int:\n \"\"\"\n A password is considered strong if the below conditions are all met:\n It has at least 6 characters and at most 20 characters.\n It contains at least one lowercase letter, at least one uppercase letter, and at least one digit.\n It does not contain three repeating characters in a row (i.e., \"Baaabb0\" is weak, but \"Baaba0\" is strong).\n Given a string password, return the minimum number of steps required to make password strong. if password is already strong, return 0.\n In one step, you can:\n Insert one character to password,\n Delete one character from password, or\n Replace one character of password with another character.\n Example 1:\n Input: password = \"a\"\n Output: 5\n Example 2:\n Input: password = \"aA1\"\n Output: 3\n Example 3:\n Input: password = \"1337C0d3\"\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 421, - "title": "Maximum XOR of Two Numbers in an Array", - "question": "class Solution:\n def findMaximumXOR(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.\n Example 1:\n Input: nums = [3,10,5,25,2,8]\n Output: 28\n Explanation: The maximum result is 5 XOR 25 = 28.\n Example 2:\n Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]\n Output: 127\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 423, - "title": "Reconstruct Original Digits from English", - "question": "class Solution:\n def originalDigits(self, s: str) -> str:\n \"\"\"\n Given a string s containing an out-of-order English representation of digits 0-9, return the digits in ascending order.\n Example 1:\n Input: s = \"owoztneoer\"\n Output: \"012\"\n Example 2:\n Input: s = \"fviefuro\"\n Output: \"45\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 424, - "title": "Longest Repeating Character Replacement", - "question": "class Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n \"\"\"\n 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.\n Return the length of the longest substring containing the same letter you can get after performing the above operations.\n Example 1:\n Input: s = \"ABAB\", k = 2\n Output: 4\n Explanation: Replace the two 'A's with two 'B's or vice versa.\n Example 2:\n Input: s = \"AABABBA\", k = 1\n Output: 4\n Explanation: Replace the one 'A' in the middle with 'B' and form \"AABBBBA\".\n The substring \"BBBB\" has the longest repeating letters, which is 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 432, - "title": "All O`one Data Structure", - "question": "class AllOne:\n def __init__(self):\n def inc(self, key: str) -> None:\n def dec(self, key: str) -> None:\n def getMaxKey(self) -> str:\n def getMinKey(self) -> str:\n \"\"\"\n Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.\n Implement the AllOne class:\n AllOne() Initializes the object of the data structure.\n inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1.\n dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement.\n getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string \"\".\n getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string \"\".\n Note that each function must run in O(1) average time complexity.\n Example 1:\n Input\n [\"AllOne\", \"inc\", \"inc\", \"getMaxKey\", \"getMinKey\", \"inc\", \"getMaxKey\", \"getMinKey\"]\n [[], [\"hello\"], [\"hello\"], [], [], [\"leet\"], [], []]\n Output\n [null, null, null, \"hello\", \"hello\", null, \"hello\", \"leet\"]\n Explanation\n AllOne allOne = new AllOne();\n allOne.inc(\"hello\");\n allOne.inc(\"hello\");\n allOne.getMaxKey(); // return \"hello\"\n allOne.getMinKey(); // return \"hello\"\n allOne.inc(\"leet\");\n allOne.getMaxKey(); // return \"hello\"\n allOne.getMinKey(); // return \"leet\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 433, - "title": "Minimum Genetic Mutation", - "question": "class Solution:\n def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:\n \"\"\"\n A gene string can be represented by an 8-character long string, with choices from 'A', 'C', 'G', and 'T'.\n Suppose 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.\n For example, \"AACCGGTT\" --> \"AACCGGTA\" is one mutation.\n There 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.\n Given 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.\n Note that the starting point is assumed to be valid, so it might not be included in the bank.\n Example 1:\n Input: startGene = \"AACCGGTT\", endGene = \"AACCGGTA\", bank = [\"AACCGGTA\"]\n Output: 1\n Example 2:\n Input: startGene = \"AACCGGTT\", endGene = \"AAACGGTA\", bank = [\"AACCGGTA\",\"AACCGCTA\",\"AAACGGTA\"]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 434, - "title": "Number of Segments in a String", - "question": "class Solution:\n def countSegments(self, s: str) -> int:\n \"\"\"\n Given a string s, return the number of segments in the string.\n A segment is defined to be a contiguous sequence of non-space characters.\n Example 1:\n Input: s = \"Hello, my name is John\"\n Output: 5\n Explanation: The five segments are [\"Hello,\", \"my\", \"name\", \"is\", \"John\"]\n Example 2:\n Input: s = \"Hello\"\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 435, - "title": "Non-overlapping Intervals", - "question": "class Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n \"\"\"\n 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:\n Input: intervals = [[1,2],[2,3],[3,4],[1,3]]\n Output: 1\n Explanation: [1,3] can be removed and the rest of the intervals are non-overlapping.\n Example 2:\n Input: intervals = [[1,2],[1,2],[1,2]]\n Output: 2\n Explanation: You need to remove two [1,2] to make the rest of the intervals non-overlapping.\n Example 3:\n Input: intervals = [[1,2],[2,3]]\n Output: 0\n Explanation: You don't need to remove any of the intervals since they're already non-overlapping.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 436, - "title": "Find Right Interval", - "question": "class Solution:\n def findRightInterval(self, intervals: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an array of intervals, where intervals[i] = [starti, endi] and each starti is unique.\n The right interval for an interval i is an interval j such that startj >= endi and startj is minimized. Note that i may equal j.\n Return 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:\n Input: intervals = [[1,2]]\n Output: [-1]\n Explanation: There is only one interval in the collection, so it outputs -1.\n Example 2:\n Input: intervals = [[3,4],[2,3],[1,2]]\n Output: [-1,0,1]\n Explanation: There is no right interval for [3,4].\n The right interval for [2,3] is [3,4] since start0 = 3 is the smallest start that is >= end1 = 3.\n The right interval for [1,2] is [2,3] since start1 = 2 is the smallest start that is >= end2 = 2.\n Example 3:\n Input: intervals = [[1,4],[2,3],[3,4]]\n Output: [-1,2,-1]\n Explanation: There is no right interval for [1,4] and [3,4].\n The right interval for [2,3] is [3,4] since start2 = 3 is the smallest start that is >= end1 = 3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 437, - "title": "Path Sum III", - "question": "class Solution:\n def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:\n \"\"\"\n 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.\n The 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:\n Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8\n Output: 3\n Explanation: The paths that sum to 8 are shown.\n Example 2:\n Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 438, - "title": "Find All Anagrams in a String", - "question": "class Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n \"\"\"\n 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.\n An 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:\n Input: s = \"cbaebabacd\", p = \"abc\"\n Output: [0,6]\n Explanation:\n The substring with start index = 0 is \"cba\", which is an anagram of \"abc\".\n The substring with start index = 6 is \"bac\", which is an anagram of \"abc\".\n Example 2:\n Input: s = \"abab\", p = \"ab\"\n Output: [0,1,2]\n Explanation:\n The substring with start index = 0 is \"ab\", which is an anagram of \"ab\".\n The substring with start index = 1 is \"ba\", which is an anagram of \"ab\".\n The substring with start index = 2 is \"ab\", which is an anagram of \"ab\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 440, - "title": "K-th Smallest in Lexicographical Order", - "question": "class Solution:\n def findKthNumber(self, n: int, k: int) -> int:\n \"\"\"\n Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n].\n Example 1:\n Input: n = 13, k = 2\n Output: 10\n Explanation: The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.\n Example 2:\n Input: n = 1, k = 1\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 441, - "title": "Arranging Coins", - "question": "class Solution:\n def arrangeCoins(self, n: int) -> int:\n \"\"\"\n 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.\n Given the integer n, return the number of complete rows of the staircase you will build.\n Example 1:\n Input: n = 5\n Output: 2\n Explanation: Because the 3rd row is incomplete, we return 2.\n Example 2:\n Input: n = 8\n Output: 3\n Explanation: Because the 4th row is incomplete, we return 3.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 442, - "title": "Find All Duplicates in an Array", - "question": "class Solution:\n def findDuplicates(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n You must write an algorithm that runs in O(n) time and uses only constant extra space.\n Example 1:\n Input: nums = [4,3,2,7,8,2,3,1]\n Output: [2,3]\n Example 2:\n Input: nums = [1,1,2]\n Output: [1]\n Example 3:\n Input: nums = [1]\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 443, - "title": "String Compression", - "question": "class Solution:\n def compress(self, chars: List[str]) -> int:\n \"\"\"\n Given an array of characters chars, compress it using the following algorithm:\n Begin with an empty string s. For each group of consecutive repeating characters in chars:\n If the group's length is 1, append the character to s.\n Otherwise, append the character followed by the group's length.\n The 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.\n After you are done modifying the input array, return the new length of the array.\n You must write an algorithm that uses only constant extra space.\n Example 1:\n Input: chars = [\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"c\"]\n Output: Return 6, and the first 6 characters of the input array should be: [\"a\",\"2\",\"b\",\"2\",\"c\",\"3\"]\n Explanation: The groups are \"aa\", \"bb\", and \"ccc\". This compresses to \"a2b2c3\".\n Example 2:\n Input: chars = [\"a\"]\n Output: Return 1, and the first character of the input array should be: [\"a\"]\n Explanation: The only group is \"a\", which remains uncompressed since it's a single character.\n Example 3:\n Input: chars = [\"a\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\",\"b\"]\n Output: Return 4, and the first 4 characters of the input array should be: [\"a\",\"b\",\"1\",\"2\"].\n Explanation: The groups are \"a\" and \"bbbbbbbbbbbb\". This compresses to \"ab12\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 445, - "title": "Add Two Numbers II", - "question": "class Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n 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.\n You may assume the two numbers do not contain any leading zero, except the number 0 itself.\n Example 1:\n Input: l1 = [7,2,4,3], l2 = [5,6,4]\n Output: [7,8,0,7]\n Example 2:\n Input: l1 = [2,4,3], l2 = [5,6,4]\n Output: [8,0,7]\n Example 3:\n Input: l1 = [0], l2 = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 446, - "title": "Arithmetic Slices II - Subsequence", - "question": "class Solution:\n def numberOfArithmeticSlices(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the number of all the arithmetic subsequences of nums.\n A sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.\n For example, [1, 3, 5, 7, 9], [7, 7, 7, 7], and [3, -1, -5, -9] are arithmetic sequences.\n For example, [1, 1, 2, 5, 7] is not an arithmetic sequence.\n A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\n For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\n The test cases are generated so that the answer fits in 32-bit integer.\n Example 1:\n Input: nums = [2,4,6,8,10]\n Output: 7\n Explanation: 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]\n Example 2:\n Input: nums = [7,7,7,7,7]\n Output: 16\n Explanation: Any subsequence of this array is arithmetic.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 447, - "title": "Number of Boomerangs", - "question": "class Solution:\n def numberOfBoomerangs(self, points: List[List[int]]) -> int:\n \"\"\"\n 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).\n Return the number of boomerangs.\n Example 1:\n Input: points = [[0,0],[1,0],[2,0]]\n Output: 2\n Explanation: The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].\n Example 2:\n Input: points = [[1,1],[2,2],[3,3]]\n Output: 2\n Example 3:\n Input: points = [[1,1]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 448, - "title": "Find All Numbers Disappeared in an Array", - "question": "class Solution:\n def findDisappearedNumbers(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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:\n Input: nums = [4,3,2,7,8,2,3,1]\n Output: [5,6]\n Example 2:\n Input: nums = [1,1]\n Output: [2]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 449, - "title": "Serialize and Deserialize BST", - "question": "class Codec:\n def serialize(self, root: Optional[TreeNode]) -> str:\n \"\"\"Encodes a tree to a single string.\n Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.\n Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.\n The encoded string should be as compact as possible.\n Example 1:\n Input: root = [2,1,3]\n Output: [2,1,3]\n Example 2:\n Input: root = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 450, - "title": "Delete Node in a BST", - "question": "class Solution:\n def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:\n \"\"\"\n 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.\n Basically, the deletion can be divided into two stages:\n Search for a node to remove.\n If the node is found, delete the node.\n Example 1:\n Input: root = [5,3,6,2,4,null,7], key = 3\n Output: [5,4,6,2,null,null,7]\n Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.\n One valid answer is [5,4,6,2,null,null,7], shown in the above BST.\n Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.\n Example 2:\n Input: root = [5,3,6,2,4,null,7], key = 0\n Output: [5,3,6,2,4,null,7]\n Explanation: The tree does not contain a node with value = 0.\n Example 3:\n Input: root = [], key = 0\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 451, - "title": "Sort Characters By Frequency", - "question": "class Solution:\n def frequencySort(self, s: str) -> str:\n \"\"\"\n 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.\n Return the sorted string. If there are multiple answers, return any of them.\n Example 1:\n Input: s = \"tree\"\n Output: \"eert\"\n Explanation: 'e' appears twice while 'r' and 't' both appear once.\n So 'e' must appear before both 'r' and 't'. Therefore \"eetr\" is also a valid answer.\n Example 2:\n Input: s = \"cccaaa\"\n Output: \"aaaccc\"\n Explanation: Both 'c' and 'a' appear three times, so both \"cccaaa\" and \"aaaccc\" are valid answers.\n Note that \"cacaca\" is incorrect, as the same characters must be together.\n Example 3:\n Input: s = \"Aabb\"\n Output: \"bbAa\"\n Explanation: \"bbaA\" is also a valid answer, but \"Aabb\" is incorrect.\n Note that 'A' and 'a' are treated as two different characters.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 452, - "title": "Minimum Number of Arrows to Burst Balloons", - "question": "class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n \"\"\"\n 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.\n Arrows 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.\n Given the array points, return the minimum number of arrows that must be shot to burst all balloons.\n Example 1:\n Input: points = [[10,16],[2,8],[1,6],[7,12]]\n Output: 2\n Explanation: 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].\n Example 2:\n Input: points = [[1,2],[3,4],[5,6],[7,8]]\n Output: 4\n Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows.\n Example 3:\n Input: points = [[1,2],[2,3],[3,4],[4,5]]\n Output: 2\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 453, - "title": "Minimum Moves to Equal Array Elements", - "question": "class Solution:\n def minMoves(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.\n In one move, you can increment n - 1 elements of the array by 1.\n Example 1:\n Input: nums = [1,2,3]\n Output: 3\n Explanation: Only three moves are needed (remember each move increments two elements):\n [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]\n Example 2:\n Input: nums = [1,1,1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 454, - "title": "4Sum II", - "question": "class Solution:\n def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int:\n \"\"\"\n Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that:\n 0 <= i, j, k, l < n\n nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0\n Example 1:\n Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2]\n Output: 2\n Explanation:\n The two tuples are:\n 1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0\n 2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0\n Example 2:\n Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 455, - "title": "Assign Cookies", - "question": "class Solution:\n def findContentChildren(self, g: List[int], s: List[int]) -> int:\n \"\"\"\n Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.\n Each 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:\n Input: g = [1,2,3], s = [1,1]\n Output: 1\n Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. \n And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.\n You need to output 1.\n Example 2:\n Input: g = [1,2], s = [1,2,3]\n Output: 2\n Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. \n You have 3 cookies and their sizes are big enough to gratify all of the children, \n You need to output 2.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 456, - "title": "132 Pattern", - "question": "class Solution:\n def find132pattern(self, nums: List[int]) -> bool:\n \"\"\"\n 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].\n Return true if there is a 132 pattern in nums, otherwise, return false.\n Example 1:\n Input: nums = [1,2,3,4]\n Output: false\n Explanation: There is no 132 pattern in the sequence.\n Example 2:\n Input: nums = [3,1,4,2]\n Output: true\n Explanation: There is a 132 pattern in the sequence: [1, 4, 2].\n Example 3:\n Input: nums = [-1,3,2,0]\n Output: true\n Explanation: There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 457, - "title": "Circular Array Loop", - "question": "class Solution:\n def circularArrayLoop(self, nums: List[int]) -> bool:\n \"\"\"\n 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:\n If nums[i] is positive, move nums[i] steps forward, and\n If nums[i] is negative, move nums[i] steps backward.\n Since 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.\n A cycle in the array consists of a sequence of indices seq of length k where:\n Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...\n Every nums[seq[j]] is either all positive or all negative.\n k > 1\n Return true if there is a cycle in nums, or false otherwise.\n Example 1:\n Input: nums = [2,-1,1,2,2]\n Output: true\n Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\n We can see the cycle 0 --> 2 --> 3 --> 0 --> ..., and all of its nodes are white (jumping in the same direction).\n Example 2:\n Input: nums = [-1,-2,-3,-4,-5,6]\n Output: false\n Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\n The only cycle is of size 1, so we return false.\n Example 3:\n Input: nums = [1,-1,5,1,4]\n Output: true\n Explanation: The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.\n We 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.\n We can see the cycle 3 --> 4 --> 3 --> ..., and all of its nodes are white (jumping in the same direction).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 458, - "title": "Poor Pigs", - "question": "class Solution:\n def poorPigs(self, buckets: int, minutesToDie: int, minutesToTest: int) -> int:\n \"\"\"\n There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.\n You can feed the pigs according to these steps:\n Choose some live pigs to feed.\n For 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.\n Wait for minutesToDie minutes. You may not feed any other pigs during this time.\n After minutesToDie minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.\n Repeat this process until you run out of time.\n Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.\n Example 1:\n Input: buckets = 4, minutesToDie = 15, minutesToTest = 15\n Output: 2\n Explanation: We can determine the poisonous bucket as follows:\n At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.\n At 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.\n Example 2:\n Input: buckets = 4, minutesToDie = 15, minutesToTest = 30\n Output: 2\n Explanation: We can determine the poisonous bucket as follows:\n At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.\n At 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.\n At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 459, - "title": "Repeated Substring Pattern", - "question": "class Solution:\n def repeatedSubstringPattern(self, s: str) -> bool:\n \"\"\"\n 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:\n Input: s = \"abab\"\n Output: true\n Explanation: It is the substring \"ab\" twice.\n Example 2:\n Input: s = \"aba\"\n Output: false\n Example 3:\n Input: s = \"abcabcabcabc\"\n Output: true\n Explanation: It is the substring \"abc\" four times or the substring \"abcabc\" twice.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 460, - "title": "LFU Cache", - "question": "class LFUCache:\n def __init__(self, capacity: int):\n def get(self, key: int) -> int:\n def put(self, key: int, value: int) -> None:\n \"\"\"\n Design and implement a data structure for a Least Frequently Used (LFU) cache.\n Implement the LFUCache class:\n LFUCache(int capacity) Initializes the object with the capacity of the data structure.\n int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.\n void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated.\n To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key.\n When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it.\n The functions get and put must each run in O(1) average time complexity.\n Example 1:\n Input\n [\"LFUCache\", \"put\", \"put\", \"get\", \"put\", \"get\", \"get\", \"put\", \"get\", \"get\", \"get\"]\n [[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]\n Output\n [null, null, null, 1, null, -1, 3, null, -1, 3, 4]\n Explanation\n // cnt(x) = the use counter for key x\n // cache=[] will show the last used order for tiebreakers (leftmost element is most recent)\n LFUCache lfu = new LFUCache(2);\n lfu.put(1, 1); // cache=[1,_], cnt(1)=1\n lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1\n lfu.get(1); // return 1\n // cache=[1,2], cnt(2)=1, cnt(1)=2\n lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.\n // cache=[3,1], cnt(3)=1, cnt(1)=2\n lfu.get(2); // return -1 (not found)\n lfu.get(3); // return 3\n // cache=[3,1], cnt(3)=2, cnt(1)=2\n lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.\n // cache=[4,3], cnt(4)=1, cnt(3)=2\n lfu.get(1); // return -1 (not found)\n lfu.get(3); // return 3\n // cache=[3,4], cnt(4)=1, cnt(3)=3\n lfu.get(4); // return 4\n // cache=[4,3], cnt(4)=2, cnt(3)=3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 461, - "title": "Hamming Distance", - "question": "class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n \"\"\"\n The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n Given two integers x and y, return the Hamming distance between them.\n Example 1:\n Input: x = 1, y = 4\n Output: 2\n Explanation:\n 1 (0 0 0 1)\n 4 (0 1 0 0)\n \u2191 \u2191\n The above arrows point to positions where the corresponding bits are different.\n Example 2:\n Input: x = 3, y = 1\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 462, - "title": "Minimum Moves to Equal Array Elements II", - "question": "class Solution:\n def minMoves2(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.\n In one move, you can increment or decrement an element of the array by 1.\n Test cases are designed so that the answer will fit in a 32-bit integer.\n Example 1:\n Input: nums = [1,2,3]\n Output: 2\n Explanation:\n Only two moves are needed (remember each move increments or decrements one element):\n [1,2,3] => [2,2,3] => [2,2,2]\n Example 2:\n Input: nums = [1,10,2,9]\n Output: 16\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 463, - "title": "Island Perimeter", - "question": "class Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water.\n Grid 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).\n The 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:\n Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]\n Output: 16\n Explanation: The perimeter is the 16 yellow stripes in the image above.\n Example 2:\n Input: grid = [[1]]\n Output: 4\n Example 3:\n Input: grid = [[1,0]]\n Output: 4\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 464, - "title": "Can I Win", - "question": "class Solution:\n def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:\n \"\"\"\n 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.\n What if we change the game so that players cannot re-use integers?\n For 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.\n Given 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:\n Input: maxChoosableInteger = 10, desiredTotal = 11\n Output: false\n Explanation:\n No matter which integer the first player choose, the first player will lose.\n The first player can choose an integer from 1 up to 10.\n If the first player choose 1, the second player can only choose integers from 2 up to 10.\n The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.\n Same with other integers chosen by the first player, the second player will always win.\n Example 2:\n Input: maxChoosableInteger = 10, desiredTotal = 0\n Output: true\n Example 3:\n Input: maxChoosableInteger = 10, desiredTotal = 1\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 466, - "title": "Count The Repetitions", - "question": "class Solution:\n def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:\n \"\"\"\n We define str = [s, n] as the string str which consists of the string s concatenated n times.\n For example, str == [\"abc\", 3] ==\"abcabcabc\".\n We define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1.\n For example, s1 = \"abc\" can be obtained from s2 = \"abdbec\" based on our definition by removing the bolded underlined characters.\n You 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].\n Return the maximum integer m such that str = [str2, m] can be obtained from str1.\n Example 1:\n Input: s1 = \"acb\", n1 = 4, s2 = \"ab\", n2 = 2\n Output: 2\n Example 2:\n Input: s1 = \"acb\", n1 = 1, s2 = \"acb\", n2 = 1\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 467, - "title": "Unique Substrings in Wraparound String", - "question": "class Solution:\n def findSubstringInWraproundString(self, s: str) -> int:\n \"\"\"\n We define the string base to be the infinite wraparound string of \"abcdefghijklmnopqrstuvwxyz\", so base will look like this:\n \"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....\".\n Given a string s, return the number of unique non-empty substrings of s are present in base.\n Example 1:\n Input: s = \"a\"\n Output: 1\n Explanation: Only the substring \"a\" of s is in base.\n Example 2:\n Input: s = \"cac\"\n Output: 2\n Explanation: There are two substrings (\"a\", \"c\") of s in base.\n Example 3:\n Input: s = \"zab\"\n Output: 6\n Explanation: There are six substrings (\"z\", \"a\", \"b\", \"za\", \"ab\", and \"zab\") of s in base.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 468, - "title": "Validate IP Address", - "question": "class Solution:\n def validIPAddress(self, queryIP: str) -> str:\n \"\"\"\n 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.\n A 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.\n A valid IPv6 address is an IP in the form \"x1:x2:x3:x4:x5:x6:x7:x8\" where:\n 1 <= xi.length <= 4\n xi is a hexadecimal string which may contain digits, lowercase English letter ('a' to 'f') and upper-case English letters ('A' to 'F').\n Leading zeros are allowed in xi.\n For 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:\n Input: queryIP = \"172.16.254.1\"\n Output: \"IPv4\"\n Explanation: This is a valid IPv4 address, return \"IPv4\".\n Example 2:\n Input: queryIP = \"2001:0db8:85a3:0:0:8A2E:0370:7334\"\n Output: \"IPv6\"\n Explanation: This is a valid IPv6 address, return \"IPv6\".\n Example 3:\n Input: queryIP = \"256.256.256.256\"\n Output: \"Neither\"\n Explanation: This is neither a IPv4 address nor a IPv6 address.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 472, - "title": "Concatenated Words", - "question": "class Solution:\n def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:\n \"\"\"\n Given an array of strings words (without duplicates), return all the concatenated words in the given list of words.\n A concatenated word is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.\n Example 1:\n Input: words = [\"cat\",\"cats\",\"catsdogcats\",\"dog\",\"dogcatsdog\",\"hippopotamuses\",\"rat\",\"ratcatdogcat\"]\n Output: [\"catsdogcats\",\"dogcatsdog\",\"ratcatdogcat\"]\n Explanation: \"catsdogcats\" can be concatenated by \"cats\", \"dog\" and \"cats\"; \n \"dogcatsdog\" can be concatenated by \"dog\", \"cats\" and \"dog\"; \n \"ratcatdogcat\" can be concatenated by \"rat\", \"cat\", \"dog\" and \"cat\".\n Example 2:\n Input: words = [\"cat\",\"dog\",\"catdog\"]\n Output: [\"catdog\"]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 473, - "title": "Matchsticks to Square", - "question": "class Solution:\n def makesquare(self, matchsticks: List[int]) -> bool:\n \"\"\"\n 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.\n Return true if you can make this square and false otherwise.\n Example 1:\n Input: matchsticks = [1,1,2,2,2]\n Output: true\n Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.\n Example 2:\n Input: matchsticks = [3,3,3,3,4]\n Output: false\n Explanation: You cannot find a way to form a square with all the matchsticks.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 474, - "title": "Ones and Zeroes", - "question": "class Solution:\n def findMaxForm(self, strs: List[str], m: int, n: int) -> int:\n \"\"\"\n You are given an array of binary strings strs and two integers m and n.\n Return the size of the largest subset of strs such that there are at most m 0's and n 1's in the subset.\n A set x is a subset of a set y if all elements of x are also elements of y.\n Example 1:\n Input: strs = [\"10\",\"0001\",\"111001\",\"1\",\"0\"], m = 5, n = 3\n Output: 4\n Explanation: The largest subset with at most 5 0's and 3 1's is {\"10\", \"0001\", \"1\", \"0\"}, so the answer is 4.\n Other 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.\n Example 2:\n Input: strs = [\"10\",\"0\",\"1\"], m = 1, n = 1\n Output: 2\n Explanation: The largest subset is {\"0\", \"1\"}, so the answer is 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 475, - "title": "Heaters", - "question": "class Solution:\n def findRadius(self, houses: List[int], heaters: List[int]) -> int:\n \"\"\"\n 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.\n Every house can be warmed, as long as the house is within the heater's warm radius range. \n Given 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.\n Notice that all the heaters follow your radius standard, and the warm radius will the same.\n Example 1:\n Input: houses = [1,2,3], heaters = [2]\n Output: 1\n Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.\n Example 2:\n Input: houses = [1,2,3,4], heaters = [1,4]\n Output: 1\n Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.\n Example 3:\n Input: houses = [1,5], heaters = [2]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 476, - "title": "Number Complement", - "question": "class Solution:\n def findComplement(self, num: int) -> int:\n \"\"\"\n 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.\n For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\n Given an integer num, return its complement.\n Example 1:\n Input: num = 5\n Output: 2\n Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.\n Example 2:\n Input: num = 1\n Output: 0\n Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 477, - "title": "Total Hamming Distance", - "question": "class Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n \"\"\"\n The Hamming distance between two integers is the number of positions at which the corresponding bits are different.\n Given an integer array nums, return the sum of Hamming distances between all the pairs of the integers in nums.\n Example 1:\n Input: nums = [4,14,2]\n Output: 6\n Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just\n showing the four bits relevant in this case).\n The answer will be:\n HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.\n Example 2:\n Input: nums = [4,14,4]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 479, - "title": "Largest Palindrome Product", - "question": "class Solution:\n def largestPalindrome(self, n: int) -> int:\n \"\"\"\n 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:\n Input: n = 2\n Output: 987\n Explanation: 99 x 91 = 9009, 9009 % 1337 = 987\n Example 2:\n Input: n = 1\n Output: 9\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 480, - "title": "Sliding Window Median", - "question": "class Solution:\n def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:\n \"\"\"\n 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.\n For examples, if arr = [2,3,4], the median is 3.\n For examples, if arr = [1,2,3,4], the median is (2 + 3) / 2 = 2.5.\n You 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.\n Return the median array for each window in the original array. Answers within 10-5 of the actual value will be accepted.\n Example 1:\n Input: nums = [1,3,-1,-3,5,3,6,7], k = 3\n Output: [1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000]\n Explanation: \n Window position Median\n --------------- -----\n [1 3 -1] -3 5 3 6 7 1\n 1 [3 -1 -3] 5 3 6 7 -1\n 1 3 [-1 -3 5] 3 6 7 -1\n 1 3 -1 [-3 5 3] 6 7 3\n 1 3 -1 -3 [5 3 6] 7 5\n 1 3 -1 -3 5 [3 6 7] 6\n Example 2:\n Input: nums = [1,2,3,4,2,3,1,4,2], k = 3\n Output: [2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 481, - "title": "Magical String", - "question": "class Solution:\n def magicalString(self, n: int) -> int:\n \"\"\"\n A magical string s consists of only '1' and '2' and obeys the following rules:\n The string s is magical because concatenating the number of contiguous occurrences of characters '1' and '2' generates the string s itself.\n The 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.\n Given an integer n, return the number of 1's in the first n number in the magical string s.\n Example 1:\n Input: n = 6\n Output: 3\n Explanation: The first 6 elements of magical string s is \"122112\" and it contains three 1's, so return 3.\n Example 2:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 482, - "title": "License Key Formatting", - "question": "class Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n \"\"\"\n 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.\n We 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.\n Return the reformatted license key.\n Example 1:\n Input: s = \"5F3Z-2e-9-w\", k = 4\n Output: \"5F3Z-2E9W\"\n Explanation: The string s has been split into two parts, each part has 4 characters.\n Note that the two extra dashes are not needed and can be removed.\n Example 2:\n Input: s = \"2-5g-3-J\", k = 2\n Output: \"2-5G-3J\"\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 483, - "title": "Smallest Good Base", - "question": "class Solution:\n def smallestGoodBase(self, n: str) -> str:\n \"\"\"\n Given an integer n represented as a string, return the smallest good base of n.\n We call k >= 2 a good base of n, if all digits of n base k are 1's.\n Example 1:\n Input: n = \"13\"\n Output: \"3\"\n Explanation: 13 base 3 is 111.\n Example 2:\n Input: n = \"4681\"\n Output: \"8\"\n Explanation: 4681 base 8 is 11111.\n Example 3:\n Input: n = \"1000000000000000000\"\n Output: \"999999999999999999\"\n Explanation: 1000000000000000000 base 999999999999999999 is 11.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 485, - "title": "Max Consecutive Ones", - "question": "class Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n \"\"\"\n Given a binary array nums, return the maximum number of consecutive 1's in the array.\n Example 1:\n Input: nums = [1,1,0,1,1,1]\n Output: 3\n Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.\n Example 2:\n Input: nums = [1,0,1,1,0,1]\n Output: 2\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 486, - "title": "Predict the Winner", - "question": "class Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.\n Player 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.\n Return 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:\n Input: nums = [1,5,2]\n Output: false\n Explanation: Initially, player 1 can choose between 1 and 2. \n If 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). \n So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. \n Hence, player 1 will never be the winner and you need to return false.\n Example 2:\n Input: nums = [1,5,233,7]\n Output: true\n Explanation: 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.\n Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 488, - "title": "Zuma Game", - "question": "class Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n \"\"\"\n You are playing a variation of the game Zuma.\n In this variation of Zuma, there is a single row of colored balls on a board, where each ball can be colored red 'R', yellow 'Y', blue 'B', green 'G', or white 'W'. You also have several colored balls in your hand.\n Your goal is to clear all of the balls from the board. On each turn:\n Pick any ball from your hand and insert it in between two balls in the row or on either end of the row.\n If there is a group of three or more consecutive balls of the same color, remove the group of balls from the board.\n If this removal causes more groups of three or more of the same color to form, then continue removing each group until there are none left.\n If there are no more balls on the board, then you win the game.\n Repeat this process until you either win or do not have any more balls in your hand.\n Given a string board, representing the row of balls on the board, and a string hand, representing the balls in your hand, return the minimum number of balls you have to insert to clear all the balls from the board. If you cannot clear all the balls from the board using the balls in your hand, return -1.\n Example 1:\n Input: board = \"WRRBBW\", hand = \"RB\"\n Output: -1\n Explanation: It is impossible to clear all the balls. The best you can do is:\n - Insert 'R' so the board becomes WRRRBBW. WRRRBBW -> WBBW.\n - Insert 'B' so the board becomes WBBBW. WBBBW -> WW.\n There are still balls remaining on the board, and you are out of balls to insert.\n Example 2:\n Input: board = \"WWRRBBWW\", hand = \"WRBRW\"\n Output: 2\n Explanation: 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.\n 2 balls from your hand were needed to clear the board.\n Example 3:\n Input: board = \"G\", hand = \"GGGGG\"\n Output: 2\n Explanation: To make the board empty:\n - Insert 'G' so the board becomes GG.\n - Insert 'G' so the board becomes GGG. GGG -> empty.\n 2 balls from your hand were needed to clear the board.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1643, - "title": "Kth Smallest Instructions", - "question": "class Solution:\n def kthSmallestPath(self, destination: List[int], k: int) -> str:\n \"\"\"\n Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.\n The instructions are represented as a string, where each character is either:\n 'H', meaning move horizontally (go right), or\n 'V', meaning move vertically (go down).\n Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both \"HHHVV\" and \"HVHVH\" are valid instructions.\n However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.\n Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.\n Example 1:\n Input: destination = [2,3], k = 1\n Output: \"HHHVV\"\n Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows:\n [\"HHHVV\", \"HHVHV\", \"HHVVH\", \"HVHHV\", \"HVHVH\", \"HVVHH\", \"VHHHV\", \"VHHVH\", \"VHVHH\", \"VVHHH\"].\n Example 2:\n Input: destination = [2,3], k = 2\n Output: \"HHVHV\"\n Example 3:\n Input: destination = [2,3], k = 3\n Output: \"HHVVH\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 491, - "title": "Non-decreasing Subsequences", - "question": "class Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n \"\"\"\n 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:\n Input: nums = [4,6,7,7]\n Output: [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]\n Example 2:\n Input: nums = [4,4,3,2,1]\n Output: [[4,4]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 492, - "title": "Construct the Rectangle", - "question": "class Solution:\n def constructRectangle(self, area: int) -> List[int]:\n \"\"\"\n 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:\n The area of the rectangular web page you designed must equal to the given target area.\n The width W should not be larger than the length L, which means L >= W.\n The difference between length L and width W should be as small as possible.\n Return an array [L, W] where L and W are the length and width of the web page you designed in sequence.\n Example 1:\n Input: area = 4\n Output: [2,2]\n Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. \n But 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.\n Example 2:\n Input: area = 37\n Output: [37,1]\n Example 3:\n Input: area = 122122\n Output: [427,286]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 493, - "title": "Reverse Pairs", - "question": "class Solution:\n def reversePairs(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the number of reverse pairs in the array.\n A reverse pair is a pair (i, j) where:\n 0 <= i < j < nums.length and\n nums[i] > 2 * nums[j].\n Example 1:\n Input: nums = [1,3,2,3,1]\n Output: 2\n Explanation: 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\n Example 2:\n Input: nums = [2,4,3,5,1]\n Output: 3\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 494, - "title": "Target Sum", - "question": "class Solution:\n def findTargetSumWays(self, nums: List[int], target: int) -> int:\n \"\"\"\n You are given an integer array nums and an integer target.\n You 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.\n For example, if nums = [2, 1], you can add a '+' before 2 and a '-' before 1 and concatenate them to build the expression \"+2-1\".\n Return the number of different expressions that you can build, which evaluates to target.\n Example 1:\n Input: nums = [1,1,1,1,1], target = 3\n Output: 5\n Explanation: 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\n Example 2:\n Input: nums = [1], target = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 495, - "title": "Teemo Attacking", - "question": "class Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n \"\"\"\n 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.\n You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.\n Return the total number of seconds that Ashe is poisoned.\n Example 1:\n Input: timeSeries = [1,4], duration = 2\n Output: 4\n Explanation: 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.\n Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.\n Example 2:\n Input: timeSeries = [1,2], duration = 2\n Output: 3\n Explanation: 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.\n Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 496, - "title": "Next Greater Element I", - "question": "class Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n 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.\n You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.\n For 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.\n Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.\n Example 1:\n Input: nums1 = [4,1,2], nums2 = [1,3,4,2]\n Output: [-1,3,-1]\n Explanation: 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.\n Example 2:\n Input: nums1 = [2,4], nums2 = [1,2,3,4]\n Output: [3,-1]\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 498, - "title": "Diagonal Traverse", - "question": "class Solution:\n def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:\n \"\"\"\n Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.\n Example 1:\n Input: mat = [[1,2,3],[4,5,6],[7,8,9]]\n Output: [1,2,4,7,5,3,6,8,9]\n Example 2:\n Input: mat = [[1,2],[3,4]]\n Output: [1,2,3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 500, - "title": "Keyboard Row", - "question": "class Solution:\n def findWords(self, words: List[str]) -> List[str]:\n \"\"\"\n 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.\n In the American keyboard:\n the first row consists of the characters \"qwertyuiop\",\n the second row consists of the characters \"asdfghjkl\", and\n the third row consists of the characters \"zxcvbnm\".\n Example 1:\n Input: words = [\"Hello\",\"Alaska\",\"Dad\",\"Peace\"]\n Output: [\"Alaska\",\"Dad\"]\n Example 2:\n Input: words = [\"omk\"]\n Output: []\n Example 3:\n Input: words = [\"adsdf\",\"sfd\"]\n Output: [\"adsdf\",\"sfd\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 501, - "title": "Find Mode in Binary Search Tree", - "question": "class Solution:\n def findMode(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n 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.\n If the tree has more than one mode, return them in any order.\n Assume a BST is defined as follows:\n The left subtree of a node contains only nodes with keys less than or equal to the node's key.\n The right subtree of a node contains only nodes with keys greater than or equal to the node's key.\n Both the left and right subtrees must also be binary search trees.\n Example 1:\n Input: root = [1,null,2,2]\n Output: [2]\n Example 2:\n Input: root = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 502, - "title": "IPO", - "question": "class Solution:\n def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:\n \"\"\"\n Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.\n You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of capital[i] is needed to start it.\n Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.\n Pick a list of at most k distinct projects from given projects to maximize your final capital, and return the final maximized capital.\n The answer is guaranteed to fit in a 32-bit signed integer.\n Example 1:\n Input: k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]\n Output: 4\n Explanation: Since your initial capital is 0, you can only start the project indexed 0.\n After finishing it you will obtain profit 1 and your capital becomes 1.\n With capital 1, you can either start the project indexed 1 or the project indexed 2.\n Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.\n Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.\n Example 2:\n Input: k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]\n Output: 6\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 503, - "title": "Next Greater Element II", - "question": "class Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n The 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:\n Input: nums = [1,2,1]\n Output: [2,-1,2]\n Explanation: The first 1's next greater number is 2; \n The number 2 can't find next greater number. \n The second 1's next greater number needs to search circularly, which is also 2.\n Example 2:\n Input: nums = [1,2,3,4,3]\n Output: [2,3,4,-1,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 504, - "title": "Base 7", - "question": "class Solution:\n def convertToBase7(self, num: int) -> str:\n \"\"\"\n Given an integer num, return a string of its base 7 representation.\n Example 1:\n Input: num = 100\n Output: \"202\"\n Example 2:\n Input: num = -7\n Output: \"-10\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 506, - "title": "Relative Ranks", - "question": "class Solution:\n def findRelativeRanks(self, score: List[int]) -> List[str]:\n \"\"\"\n 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.\n The 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:\n The 1st place athlete's rank is \"Gold Medal\".\n The 2nd place athlete's rank is \"Silver Medal\".\n The 3rd place athlete's rank is \"Bronze Medal\".\n For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete's rank is \"x\").\n Return an array answer of size n where answer[i] is the rank of the ith athlete.\n Example 1:\n Input: score = [5,4,3,2,1]\n Output: [\"Gold Medal\",\"Silver Medal\",\"Bronze Medal\",\"4\",\"5\"]\n Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].\n Example 2:\n Input: score = [10,3,8,9,4]\n Output: [\"Gold Medal\",\"5\",\"Bronze Medal\",\"Silver Medal\",\"4\"]\n Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 507, - "title": "Perfect Number", - "question": "class Solution:\n def checkPerfectNumber(self, num: int) -> bool:\n \"\"\"\n 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.\n Given an integer n, return true if n is a perfect number, otherwise return false.\n Example 1:\n Input: num = 28\n Output: true\n Explanation: 28 = 1 + 2 + 4 + 7 + 14\n 1, 2, 4, 7, and 14 are all divisors of 28.\n Example 2:\n Input: num = 7\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 508, - "title": "Most Frequent Subtree Sum", - "question": "class Solution:\n def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n 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.\n The 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:\n Input: root = [5,2,-3]\n Output: [2,-3,4]\n Example 2:\n Input: root = [5,2,-5]\n Output: [2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 513, - "title": "Find Bottom Left Tree Value", - "question": "class Solution:\n def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return the leftmost value in the last row of the tree.\n Example 1:\n Input: root = [2,1,3]\n Output: 1\n Example 2:\n Input: root = [1,2,3,4,null,5,6,null,null,7]\n Output: 7\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 514, - "title": "Freedom Trail", - "question": "class Solution:\n def findRotateSteps(self, ring: str, key: str) -> int:\n \"\"\"\n 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.\n Given 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.\n Initially, 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.\n At the stage of rotating the ring to spell the key character key[i]:\n You 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].\n If 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:\n Input: ring = \"godding\", key = \"gd\"\n Output: 4\n Explanation:\n For the first key character 'g', since it is already in place, we just need 1 step to spell this character. \n For the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\n Also, we need 1 more step for spelling.\n So the final output is 4.\n Example 2:\n Input: ring = \"godding\", key = \"godding\"\n Output: 13\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 515, - "title": "Find Largest Value in Each Tree Row", - "question": "class Solution:\n def largestValues(self, root: Optional[TreeNode]) -> List[int]:\n \"\"\"\n 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:\n Input: root = [1,3,2,5,3,null,9]\n Output: [1,3,9]\n Example 2:\n Input: root = [1,2,3]\n Output: [1,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 516, - "title": "Longest Palindromic Subsequence", - "question": "class Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n \"\"\"\n Given a string s, find the longest palindromic subsequence's length in s.\n A 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:\n Input: s = \"bbbab\"\n Output: 4\n Explanation: One possible longest palindromic subsequence is \"bbbb\".\n Example 2:\n Input: s = \"cbbd\"\n Output: 2\n Explanation: One possible longest palindromic subsequence is \"bb\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 517, - "title": "Super Washing Machines", - "question": "class Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n \"\"\"\n You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.\n For each move, you could choose any m (1 <= m <= n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.\n Given an integer array 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:\n Input: machines = [1,0,5]\n Output: 3\n Explanation:\n 1st move: 1 0 <-- 5 => 1 1 4\n 2nd move: 1 <-- 1 <-- 4 => 2 1 3\n 3rd move: 2 1 <-- 3 => 2 2 2\n Example 2:\n Input: machines = [0,3,0]\n Output: 2\n Explanation:\n 1st move: 0 <-- 3 0 => 1 2 0\n 2nd move: 1 2 --> 0 => 1 1 1\n Example 3:\n Input: machines = [0,2,0]\n Output: -1\n Explanation:\n It's impossible to make all three washing machines have the same number of dresses.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 518, - "title": "Coin Change II", - "question": "class Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n \"\"\"\n You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.\n Return 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.\n You may assume that you have an infinite number of each kind of coin.\n The answer is guaranteed to fit into a signed 32-bit integer.\n Example 1:\n Input: amount = 5, coins = [1,2,5]\n Output: 4\n Explanation: there are four ways to make up the amount:\n 5=5\n 5=2+2+1\n 5=2+1+1+1\n 5=1+1+1+1+1\n Example 2:\n Input: amount = 3, coins = [2]\n Output: 0\n Explanation: the amount of 3 cannot be made up just with coins of 2.\n Example 3:\n Input: amount = 10, coins = [10]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 520, - "title": "Detect Capital", - "question": "class Solution:\n def detectCapitalUse(self, word: str) -> bool:\n \"\"\"\n We define the usage of capitals in a word to be right when one of the following cases holds:\n All letters in this word are capitals, like \"USA\".\n All letters in this word are not capitals, like \"leetcode\".\n Only the first letter in this word is capital, like \"Google\".\n Given a string word, return true if the usage of capitals in it is right.\n Example 1:\n Input: word = \"USA\"\n Output: true\n Example 2:\n Input: word = \"FlaG\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 521, - "title": "Longest Uncommon Subsequence I", - "question": "class Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n \"\"\"\n Given two strings a and b, return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence does not exist, return -1.\n An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.\n A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\n For 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:\n Input: a = \"aba\", b = \"cdc\"\n Output: 3\n Explanation: One longest uncommon subsequence is \"aba\" because \"aba\" is a subsequence of \"aba\" but not \"cdc\".\n Note that \"cdc\" is also a longest uncommon subsequence.\n Example 2:\n Input: a = \"aaa\", b = \"bbb\"\n Output: 3\n Explanation: The longest uncommon subsequences are \"aaa\" and \"bbb\".\n Example 3:\n Input: a = \"aaa\", b = \"aaa\"\n Output: -1\n Explanation: 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.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 522, - "title": "Longest Uncommon Subsequence II", - "question": "class Solution:\n def findLUSlength(self, strs: List[str]) -> int:\n \"\"\"\n 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.\n An uncommon subsequence between an array of strings is a string that is a subsequence of one string but not the others.\n A subsequence of a string s is a string that can be obtained after deleting any number of characters from s.\n For 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:\n Input: strs = [\"aba\",\"cdc\",\"eae\"]\n Output: 3\n Example 2:\n Input: strs = [\"aaa\",\"aaa\",\"aa\"]\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 523, - "title": "Continuous Subarray Sum", - "question": "class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n \"\"\"\n Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.\n A good subarray is a subarray where:\n its length is at least two, and\n the sum of the elements of the subarray is a multiple of k.\n Note that:\n A subarray is a contiguous part of the array.\n An 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:\n Input: nums = [23,2,4,6,7], k = 6\n Output: true\n Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.\n Example 2:\n Input: nums = [23,2,6,4,7], k = 6\n Output: true\n Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.\n 42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.\n Example 3:\n Input: nums = [23,2,6,4,7], k = 13\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 524, - "title": "Longest Word in Dictionary through Deleting", - "question": "class Solution:\n def findLongestWord(self, s: str, dictionary: List[str]) -> str:\n \"\"\"\n 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:\n Input: s = \"abpcplea\", dictionary = [\"ale\",\"apple\",\"monkey\",\"plea\"]\n Output: \"apple\"\n Example 2:\n Input: s = \"abpcplea\", dictionary = [\"a\",\"b\",\"c\"]\n Output: \"a\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 525, - "title": "Contiguous Array", - "question": "class Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n \"\"\"\n Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.\n Example 1:\n Input: nums = [0,1]\n Output: 2\n Explanation: [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.\n Example 2:\n Input: nums = [0,1,0]\n Output: 2\n Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 526, - "title": "Beautiful Arrangement", - "question": "class Solution:\n def countArrangement(self, n: int) -> int:\n \"\"\"\n 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:\n perm[i] is divisible by i.\n i is divisible by perm[i].\n Given an integer n, return the number of the beautiful arrangements that you can construct.\n Example 1:\n Input: n = 2\n Output: 2\n Explanation: \n The first beautiful arrangement is [1,2]:\n - perm[1] = 1 is divisible by i = 1\n - perm[2] = 2 is divisible by i = 2\n The second beautiful arrangement is [2,1]:\n - perm[1] = 2 is divisible by i = 1\n - i = 2 is divisible by perm[2] = 1\n Example 2:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1721, - "title": "Swapping Nodes in a Linked List", - "question": "class Solution:\n def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:\n \"\"\"\n You are given the head of a linked list, and an integer k.\n Return 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:\n Input: head = [1,2,3,4,5], k = 2\n Output: [1,4,3,2,5]\n Example 2:\n Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5\n Output: [7,9,6,6,8,7,3,0,9,5]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 529, - "title": "Minesweeper", - "question": "class Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n \"\"\"\n Let's play the minesweeper game (Wikipedia, online game)!\n You 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),\n digit ('1' to '8') represents how many mines are adjacent to this revealed square, and\n 'X' represents a revealed mine.\n You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E').\n Return the board after revealing this position according to the following rules:\n If a mine 'M' is revealed, then the game is over. You should change it to 'X'.\n If 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.\n If 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.\n Return the board when no more squares will be revealed.\n Example 1:\n Input: board = [[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"M\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"],[\"E\",\"E\",\"E\",\"E\",\"E\"]], click = [3,0]\n Output: [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n Example 2:\n Input: board = [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"M\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]], click = [1,2]\n Output: [[\"B\",\"1\",\"E\",\"1\",\"B\"],[\"B\",\"1\",\"X\",\"1\",\"B\"],[\"B\",\"1\",\"1\",\"1\",\"B\"],[\"B\",\"B\",\"B\",\"B\",\"B\"]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 530, - "title": "Minimum Absolute Difference in BST", - "question": "class Solution:\n def getMinimumDifference(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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:\n Input: root = [4,2,6,1,3]\n Output: 1\n Example 2:\n Input: root = [1,0,48,null,null,12,49]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 532, - "title": "K-diff Pairs in an Array", - "question": "class Solution:\n def findPairs(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array.\n A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true:\n 0 <= i, j < nums.length\n i != j\n nums[i] - nums[j] == k\n Notice that |val| denotes the absolute value of val.\n Example 1:\n Input: nums = [3,1,4,1,5], k = 2\n Output: 2\n Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).\n Although we have two 1s in the input, we should only return the number of unique pairs.\n Example 2:\n Input: nums = [1,2,3,4,5], k = 1\n Output: 4\n Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).\n Example 3:\n Input: nums = [1,3,1,5,4], k = 0\n Output: 1\n Explanation: There is one 0-diff pair in the array, (1, 1).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 535, - "title": "Encode and Decode TinyURL", - "question": "class Codec:\n def encode(self, longUrl: str) -> str:\n \"\"\"Encodes a URL to a shortened URL.\n Note: This is a companion problem to the System Design problem: Design TinyURL.\n TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL.\n There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.\n Implement the Solution class:\n Solution() Initializes the object of the system.\n String encode(String longUrl) Returns a tiny URL for the given longUrl.\n String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.\n Example 1:\n Input: url = \"https://leetcode.com/problems/design-tinyurl\"\n Output: \"https://leetcode.com/problems/design-tinyurl\"\n Explanation:\n Solution obj = new Solution();\n string tiny = obj.encode(url); // returns the encoded tiny url.\n string ans = obj.decode(tiny); // returns the original url after decoding it.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 537, - "title": "Complex Number Multiplication", - "question": "class Solution:\n def complexNumberMultiply(self, num1: str, num2: str) -> str:\n \"\"\"\n A complex number can be represented as a string on the form \"real+imaginaryi\" where:\n real is the real part and is an integer in the range [-100, 100].\n imaginary is the imaginary part and is an integer in the range [-100, 100].\n i2 == -1.\n Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.\n Example 1:\n Input: num1 = \"1+1i\", num2 = \"1+1i\"\n Output: \"0+2i\"\n Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\n Example 2:\n Input: num1 = \"1+-1i\", num2 = \"1+-1i\"\n Output: \"0+-2i\"\n Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 538, - "title": "Convert BST to Greater Tree", - "question": "class Solution:\n def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \"\"\"\n 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.\n As a reminder, a binary search tree is a tree that satisfies these constraints:\n The left subtree of a node contains only nodes with keys less than the node's key.\n The right subtree of a node contains only nodes with keys greater than the node's key.\n Both the left and right subtrees must also be binary search trees.\n Example 1:\n Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\n Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n Example 2:\n Input: root = [0,null,1]\n Output: [1,null,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 539, - "title": "Minimum Time Difference", - "question": "class Solution:\n def findMinDifference(self, timePoints: List[str]) -> int:\n \"\"\"\n 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:\n Input: timePoints = [\"23:59\",\"00:00\"]\n Output: 1\n Example 2:\n Input: timePoints = [\"00:00\",\"23:59\",\"00:00\"]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 540, - "title": "Single Element in a Sorted Array", - "question": "class Solution:\n def singleNonDuplicate(self, nums: List[int]) -> int:\n \"\"\"\n You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.\n Return the single element that appears only once.\n Your solution must run in O(log n) time and O(1) space.\n Example 1:\n Input: nums = [1,1,2,3,3,4,4,8,8]\n Output: 2\n Example 2:\n Input: nums = [3,3,7,7,10,11,11]\n Output: 10\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 541, - "title": "Reverse String II", - "question": "class Solution:\n def reverseStr(self, s: str, k: int) -> str:\n \"\"\"\n Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.\n If 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:\n Input: s = \"abcdefg\", k = 2\n Output: \"bacdfeg\"\n Example 2:\n Input: s = \"abcd\", k = 2\n Output: \"bacd\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 542, - "title": "01 Matrix", - "question": "class Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell.\n The distance between two adjacent cells is 1.\n Example 1:\n Input: mat = [[0,0,0],[0,1,0],[0,0,0]]\n Output: [[0,0,0],[0,1,0],[0,0,0]]\n Example 2:\n Input: mat = [[0,0,0],[0,1,0],[1,1,1]]\n Output: [[0,0,0],[0,1,0],[1,2,1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 543, - "title": "Diameter of Binary Tree", - "question": "class Solution:\n def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return the length of the diameter of the tree.\n The 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.\n The length of a path between two nodes is represented by the number of edges between them.\n Example 1:\n Input: root = [1,2,3,4,5]\n Output: 3\n Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].\n Example 2:\n Input: root = [1,2]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 546, - "title": "Remove Boxes", - "question": "class Solution:\n def removeBoxes(self, boxes: List[int]) -> int:\n \"\"\"\n You are given several boxes with different colors represented by different positive numbers.\n You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of k boxes, k >= 1), remove them and get k * k points.\n Return the maximum points you can get.\n Example 1:\n Input: boxes = [1,3,2,2,2,3,4,3,1]\n Output: 23\n Explanation:\n [1, 3, 2, 2, 2, 3, 4, 3, 1] \n ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) \n ----> [1, 3, 3, 3, 1] (1*1=1 points) \n ----> [1, 1] (3*3=9 points) \n ----> [] (2*2=4 points)\n Example 2:\n Input: boxes = [1,1,1]\n Output: 9\n Example 3:\n Input: boxes = [1]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 547, - "title": "Number of Provinces", - "question": "class Solution:\n def findCircleNum(self, isConnected: List[List[int]]) -> int:\n \"\"\"\n 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.\n A province is a group of directly or indirectly connected cities and no other cities outside of the group.\n You 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.\n Return the total number of provinces.\n Example 1:\n Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]\n Output: 2\n Example 2:\n Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 551, - "title": "Student Attendance Record I", - "question": "class Solution:\n def checkRecord(self, s: str) -> bool:\n \"\"\"\n 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.\n The student is eligible for an attendance award if they meet both of the following criteria:\n The student was absent ('A') for strictly fewer than 2 days total.\n The student was never late ('L') for 3 or more consecutive days.\n Return true if the student is eligible for an attendance award, or false otherwise.\n Example 1:\n Input: s = \"PPALLP\"\n Output: true\n Explanation: The student has fewer than 2 absences and was never late 3 or more consecutive days.\n Example 2:\n Input: s = \"PPALLL\"\n Output: false\n Explanation: The student was late 3 consecutive days in the last 3 days, so is not eligible for the award.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 552, - "title": "Student Attendance Record II", - "question": "class Solution:\n def checkRecord(self, n: int) -> int:\n \"\"\"\n 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.\n Any student is eligible for an attendance award if they meet both of the following criteria:\n The student was absent ('A') for strictly fewer than 2 days total.\n The student was never late ('L') for 3 or more consecutive days.\n Given an integer n, return the number of possible attendance records of length n that make a student eligible for an attendance award. The answer may be very large, so return it modulo 109 + 7.\n Example 1:\n Input: n = 2\n Output: 8\n Explanation: There are 8 records with length 2 that are eligible for an award:\n \"PP\", \"AP\", \"PA\", \"LP\", \"PL\", \"AL\", \"LA\", \"LL\"\n Only \"AA\" is not eligible because there are 2 absences (there need to be fewer than 2).\n Example 2:\n Input: n = 1\n Output: 3\n Example 3:\n Input: n = 10101\n Output: 183236316\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 553, - "title": "Optimal Division", - "question": "class Solution:\n def optimalDivision(self, nums: List[int]) -> str:\n \"\"\"\n You are given an integer array nums. The adjacent integers in nums will perform the float division.\n For example, for nums = [2,3,4], we will evaluate the expression \"2/3/4\".\n However, 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.\n Return the corresponding expression that has the maximum value in string format.\n Note: your expression should not contain redundant parenthesis.\n Example 1:\n Input: nums = [1000,100,10,2]\n Output: \"1000/(100/10/2)\"\n Explanation: 1000/(100/10/2) = 1000/((100/10)/2) = 200\n However, the bold parenthesis in \"1000/((100/10)/2)\" are redundant since they do not influence the operation priority.\n So you should return \"1000/(100/10/2)\".\n Other cases:\n 1000/(100/10)/2 = 50\n 1000/(100/(10/2)) = 50\n 1000/100/10/2 = 0.5\n 1000/100/(10/2) = 2\n Example 2:\n Input: nums = [2,3,4]\n Output: \"2/(3/4)\"\n Explanation: (2/(3/4)) = 8/3 = 2.667\n It can be shown that after trying all possibilities, we cannot get an expression with evaluation greater than 2.667\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 554, - "title": "Brick Wall", - "question": "class Solution:\n def leastBricks(self, wall: List[List[int]]) -> int:\n \"\"\"\n 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.\n Draw 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.\n Given 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:\n Input: wall = [[1,2,2,1],[3,1,2],[1,3,2],[2,4],[3,1,2],[1,3,1,1]]\n Output: 2\n Example 2:\n Input: wall = [[1],[1],[1]]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 556, - "title": "Next Greater Element III", - "question": "class Solution:\n def nextGreaterElement(self, n: int) -> int:\n \"\"\"\n 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.\n Note 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:\n Input: n = 12\n Output: 21\n Example 2:\n Input: n = 21\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 557, - "title": "Reverse Words in a String III", - "question": "class Solution:\n def reverseWords(self, s: str) -> str:\n \"\"\"\n 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:\n Input: s = \"Let's take LeetCode contest\"\n Output: \"s'teL ekat edoCteeL tsetnoc\"\n Example 2:\n Input: s = \"God Ding\"\n Output: \"doG gniD\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 560, - "title": "Subarray Sum Equals K", - "question": "class Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.\n A subarray is a contiguous non-empty sequence of elements within an array.\n Example 1:\n Input: nums = [1,1,1], k = 2\n Output: 2\n Example 2:\n Input: nums = [1,2,3], k = 3\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 561, - "title": "Array Partition", - "question": "class Solution:\n def arrayPairSum(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [1,4,3,2]\n Output: 4\n Explanation: All possible pairings (ignoring the ordering of elements) are:\n 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3\n 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3\n 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4\n So the maximum possible sum is 4.\n Example 2:\n Input: nums = [6,2,6,5,1,2]\n Output: 9\n Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 563, - "title": "Binary Tree Tilt", - "question": "class Solution:\n def findTilt(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return the sum of every tree node's tilt.\n The 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:\n Input: root = [1,2,3]\n Output: 1\n Explanation: \n Tilt of node 2 : |0-0| = 0 (no children)\n Tilt of node 3 : |0-0| = 0 (no children)\n Tilt 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)\n Sum of every tilt : 0 + 0 + 1 = 1\n Example 2:\n Input: root = [4,2,9,3,5,null,7]\n Output: 15\n Explanation: \n Tilt of node 3 : |0-0| = 0 (no children)\n Tilt of node 5 : |0-0| = 0 (no children)\n Tilt of node 7 : |0-0| = 0 (no children)\n Tilt 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)\n Tilt of node 9 : |0-7| = 7 (no left child, so sum is 0; right subtree is just right child, so sum is 7)\n Tilt 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)\n Sum of every tilt : 0 + 0 + 0 + 2 + 7 + 6 = 15\n Example 3:\n Input: root = [21,7,14,1,1,2,2,3,3]\n Output: 9\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 564, - "title": "Find the Closest Palindrome", - "question": "class Solution:\n def nearestPalindromic(self, n: str) -> str:\n \"\"\"\n 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.\n The closest is defined as the absolute difference minimized between two integers.\n Example 1:\n Input: n = \"123\"\n Output: \"121\"\n Example 2:\n Input: n = \"1\"\n Output: \"0\"\n Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 565, - "title": "Array Nesting", - "question": "class Solution:\n def arrayNesting(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].\n You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:\n The first element in s[k] starts with the selection of the element nums[k] of index = k.\n The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.\n We stop adding right before a duplicate element occurs in s[k].\n Return the longest length of a set s[k].\n Example 1:\n Input: nums = [5,4,0,3,1,6,2]\n Output: 4\n Explanation: \n nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.\n One of the longest sets s[k]:\n s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}\n Example 2:\n Input: nums = [0,1,2]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 566, - "title": "Reshape the Matrix", - "question": "class Solution:\n def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:\n \"\"\"\n 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.\n You 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.\n The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.\n If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.\n Example 1:\n Input: mat = [[1,2],[3,4]], r = 1, c = 4\n Output: [[1,2,3,4]]\n Example 2:\n Input: mat = [[1,2],[3,4]], r = 2, c = 4\n Output: [[1,2],[3,4]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 567, - "title": "Permutation in String", - "question": "class Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n \"\"\"\n Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.\n In other words, return true if one of s1's permutations is the substring of s2.\n Example 1:\n Input: s1 = \"ab\", s2 = \"eidbaooo\"\n Output: true\n Explanation: s2 contains one permutation of s1 (\"ba\").\n Example 2:\n Input: s1 = \"ab\", s2 = \"eidboaoo\"\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 572, - "title": "Subtree of Another Tree", - "question": "class Solution:\n def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:\n \"\"\"\n 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.\n A 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:\n Input: root = [3,4,5,1,2], subRoot = [4,1,2]\n Output: true\n Example 2:\n Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 575, - "title": "Distribute Candies", - "question": "class Solution:\n def distributeCandies(self, candyType: List[int]) -> int:\n \"\"\"\n 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.\n The 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.\n Given 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:\n Input: candyType = [1,1,2,2,3,3]\n Output: 3\n Explanation: Alice can only eat 6 / 2 = 3 candies. Since there are only 3 types, she can eat one of each type.\n Example 2:\n Input: candyType = [1,1,2,3]\n Output: 2\n Explanation: 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.\n Example 3:\n Input: candyType = [6,6,6,6]\n Output: 1\n Explanation: Alice can only eat 4 / 2 = 2 candies. Even though she can eat 2 candies, she only has 1 type.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 576, - "title": "Out of Boundary Paths", - "question": "class Solution:\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n \"\"\"\n 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.\n Given 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:\n Input: m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0\n Output: 6\n Example 2:\n Input: m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1\n Output: 12\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 581, - "title": "Shortest Unsorted Continuous Subarray", - "question": "class Solution:\n def findUnsortedSubarray(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.\n Return the shortest such subarray and output its length.\n Example 1:\n Input: nums = [2,6,4,8,10,9,15]\n Output: 5\n Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.\n Example 2:\n Input: nums = [1,2,3,4]\n Output: 0\n Example 3:\n Input: nums = [1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 583, - "title": "Delete Operation for Two Strings", - "question": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n \"\"\"\n Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.\n In one step, you can delete exactly one character in either string.\n Example 1:\n Input: word1 = \"sea\", word2 = \"eat\"\n Output: 2\n Explanation: You need one step to make \"sea\" to \"ea\" and another step to make \"eat\" to \"ea\".\n Example 2:\n Input: word1 = \"leetcode\", word2 = \"etco\"\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 587, - "title": "Erect the Fence", - "question": "class Solution:\n def outerTrees(self, trees: List[List[int]]) -> List[List[int]]:\n \"\"\"\n You are given an array trees where trees[i] = [xi, yi] represents the location of a tree in the garden.\n Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if all the trees are enclosed.\n Return the coordinates of trees that are exactly located on the fence perimeter. You may return the answer in any order.\n Example 1:\n Input: trees = [[1,1],[2,2],[2,0],[2,4],[3,3],[4,2]]\n Output: [[1,1],[2,0],[4,2],[3,3],[2,4]]\n Explanation: All the trees will be on the perimeter of the fence except the tree at [2, 2], which will be inside the fence.\n Example 2:\n Input: trees = [[1,2],[2,2],[4,2]]\n Output: [[4,2],[2,2],[1,2]]\n Explanation: The fence forms a line that passes through all the trees.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 591, - "title": "Tag Validator", - "question": "class Solution:\n def isValid(self, code: str) -> bool:\n \"\"\"\n Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid.\n A code snippet is valid if all the following rules hold:\n The code must be wrapped in a valid closed tag. Otherwise, the code is invalid.\n A closed tag (not necessarily valid) has exactly the following format : TAG_CONTENT. Among them, is the start tag, and is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid.\n A valid TAG_NAME only contain upper-case letters, and has length in range [1,9]. Otherwise, the TAG_NAME is invalid.\n A valid TAG_CONTENT may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched <, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the TAG_CONTENT is invalid.\n A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested.\n A < is unmatched if you cannot find a subsequent >. And when you find a < or should be parsed as TAG_NAME (not necessarily valid).\n The cdata has the following format : . The range of CDATA_CONTENT is defined as the characters between .\n CDATA_CONTENT may contain any characters. The function of cdata is to forbid the validator to parse CDATA_CONTENT, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.\n Example 1:\n Input: code = \"
This is the first line ]]>
\"\n Output: true\n Explanation: \n The code is wrapped in a closed tag :
and
. \n The TAG_NAME is valid, the TAG_CONTENT consists of some characters and cdata. \n Although CDATA_CONTENT has an unmatched start tag with invalid TAG_NAME, it should be considered as plain text, not parsed as a tag.\n So TAG_CONTENT is valid, and then the code is valid. Thus return true.\n Example 2:\n Input: code = \"
>> ![cdata[]] ]>]]>]]>>]
\"\n Output: true\n Explanation:\n We first separate the code into : start_tag|tag_content|end_tag.\n start_tag -> \"
\"\n end_tag -> \"
\"\n tag_content could also be separated into : text1|cdata|text2.\n text1 -> \">> ![cdata[]] \"\n cdata -> \"]>]]>\", where the CDATA_CONTENT is \"
]>\"\n text2 -> \"]]>>]\"\n The reason why start_tag is NOT \"
>>\" is because of the rule 6.\n The reason why cdata is NOT \"]>]]>]]>\" is because of the rule 7.\n Example 3:\n Input: code = \" \"\n Output: false\n Explanation: Unbalanced. If \"\" is closed, then \"\" must be unmatched, and vice versa.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 592, - "title": "Fraction Addition and Subtraction", - "question": "class Solution:\n def fractionAddition(self, expression: str) -> str:\n \"\"\"\n Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.\n The 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:\n Input: expression = \"-1/2+1/2\"\n Output: \"0/1\"\n Example 2:\n Input: expression = \"-1/2+1/2+1/3\"\n Output: \"1/3\"\n Example 3:\n Input: expression = \"1/3-1/2\"\n Output: \"-1/6\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 593, - "title": "Valid Square", - "question": "class Solution:\n def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:\n \"\"\"\n Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.\n The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.\n A valid square has four equal sides with positive length and four equal angles (90-degree angles).\n Example 1:\n Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]\n Output: true\n Example 2:\n Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]\n Output: false\n Example 3:\n Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 594, - "title": "Longest Harmonious Subsequence", - "question": "class Solution:\r\n def findLHS(self, nums: List[int]) -> int:\n \"\"\"\n We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.\r\n Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.\r\n A 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.\r\n Example 1:\r\n Input: nums = [1,3,2,2,5,2,3,7]\r\n Output: 5\r\n Explanation: The longest harmonious subsequence is [3,2,2,2,3].\r\n Example 2:\r\n Input: nums = [1,2,3,4]\r\n Output: 2\r\n Example 3:\r\n Input: nums = [1,1,1,1]\r\n Output: 0\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 598, - "title": "Range Addition II", - "question": "class Solution:\n def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:\n \"\"\"\n 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.\n Count and return the number of maximum integers in the matrix after performing all the operations.\n Example 1:\n Input: m = 3, n = 3, ops = [[2,2],[3,3]]\n Output: 4\n Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4.\n Example 2:\n Input: 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]]\n Output: 4\n Example 3:\n Input: m = 3, n = 3, ops = []\n Output: 9\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 599, - "title": "Minimum Index Sum of Two Lists", - "question": "class Solution:\n def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:\n \"\"\"\n Given two arrays of strings list1 and list2, find the common strings with the least index sum.\n A common string is a string that appeared in both list1 and list2.\n A 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.\n Return all the common strings with the least index sum. Return the answer in any order.\n Example 1:\n Input: list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"Piatti\",\"The Grill at Torrey Pines\",\"Hungry Hunter Steakhouse\",\"Shogun\"]\n Output: [\"Shogun\"]\n Explanation: The only common string is \"Shogun\".\n Example 2:\n Input: list1 = [\"Shogun\",\"Tapioca Express\",\"Burger King\",\"KFC\"], list2 = [\"KFC\",\"Shogun\",\"Burger King\"]\n Output: [\"Shogun\"]\n Explanation: The common string with the least index sum is \"Shogun\" with index sum = (0 + 1) = 1.\n Example 3:\n Input: list1 = [\"happy\",\"sad\",\"good\"], list2 = [\"sad\",\"happy\",\"good\"]\n Output: [\"sad\",\"happy\"]\n Explanation: 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.\n The strings with the least index sum are \"sad\" and \"happy\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 600, - "title": "Non-negative Integers without Consecutive Ones", - "question": "class Solution:\n def findIntegers(self, n: int) -> int:\n \"\"\"\n 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:\n Input: n = 5\n Output: 5\n Explanation:\n Here are the non-negative integers <= 5 with their corresponding binary representations:\n 0 : 0\n 1 : 1\n 2 : 10\n 3 : 11\n 4 : 100\n 5 : 101\n Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. \n Example 2:\n Input: n = 1\n Output: 2\n Example 3:\n Input: n = 2\n Output: 3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 605, - "title": "Can Place Flowers", - "question": "class Solution:\n def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool:\n \"\"\"\n 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.\n Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty, and an integer n, return if n new flowers can be planted in the flowerbed without violating the no-adjacent-flowers rule.\n Example 1:\n Input: flowerbed = [1,0,0,0,1], n = 1\n Output: true\n Example 2:\n Input: flowerbed = [1,0,0,0,1], n = 2\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 606, - "title": "Construct String from Binary Tree", - "question": "class Solution:\n def tree2str(self, root: Optional[TreeNode]) -> str:\n \"\"\"\n Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.\n Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.\n Example 1:\n Input: root = [1,2,3,4]\n Output: \"1(2(4))(3)\"\n Explanation: Originally, it needs to be \"1(2(4)())(3()())\", but you need to omit all the unnecessary empty parenthesis pairs. And it will be \"1(2(4))(3)\"\n Example 2:\n Input: root = [1,2,3,null,4]\n Output: \"1(2()(4))(3)\"\n Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 609, - "title": "Find Duplicate File in System", - "question": "class Solution:\n def findDuplicate(self, paths: List[str]) -> List[List[str]]:\n \"\"\"\n 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.\n A group of duplicate files consists of at least two files that have the same content.\n A 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)\"\n It 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.\n The 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:\n Input: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\",\"root 4.txt(efgh)\"]\n Output: [[\"root/a/2.txt\",\"root/c/d/4.txt\",\"root/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n Example 2:\n Input: paths = [\"root/a 1.txt(abcd) 2.txt(efgh)\",\"root/c 3.txt(abcd)\",\"root/c/d 4.txt(efgh)\"]\n Output: [[\"root/a/2.txt\",\"root/c/d/4.txt\"],[\"root/a/1.txt\",\"root/c/3.txt\"]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 611, - "title": "Valid Triangle Number", - "question": "class Solution:\n def triangleNumber(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [2,2,3,4]\n Output: 3\n Explanation: Valid combinations are: \n 2,3,4 (using the first 2)\n 2,3,4 (using the second 2)\n 2,2,3\n Example 2:\n Input: nums = [4,2,3,4]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 617, - "title": "Merge Two Binary Trees", - "question": "class Solution:\n def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:\n \"\"\"\n You are given two binary trees root1 and root2.\n Imagine 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.\n Return the merged tree.\n Note: The merging process must start from the root nodes of both trees.\n Example 1:\n Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]\n Output: [3,4,5,5,4,null,7]\n Example 2:\n Input: root1 = [1], root2 = [1,2]\n Output: [2,2]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 621, - "title": "Task Scheduler", - "question": "class Solution:\n def leastInterval(self, tasks: List[str], n: int) -> int:\n \"\"\"\n Given a characters array tasks, representing the tasks a CPU needs to do, where each letter represents a different task. Tasks could be done in any order. Each task is done in one unit of time. For each unit of time, the CPU could complete either one task or just be idle.\n However, there is a non-negative integer n that represents the cooldown period between two same tasks (the same letter in the array), that is that there must be at least n units of time between any two same tasks.\n Return the least number of units of times that the CPU will take to finish all the given tasks.\n Example 1:\n Input: tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 2\n Output: 8\n Explanation: \n A -> B -> idle -> A -> B -> idle -> A -> B\n There is at least 2 units of time between any two same tasks.\n Example 2:\n Input: tasks = [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"], n = 0\n Output: 6\n Explanation: On this case any permutation of size 6 would work since n = 0.\n [\"A\",\"A\",\"A\",\"B\",\"B\",\"B\"]\n [\"A\",\"B\",\"A\",\"B\",\"A\",\"B\"]\n [\"B\",\"B\",\"B\",\"A\",\"A\",\"A\"]\n ...\n And so on.\n Example 3:\n Input: tasks = [\"A\",\"A\",\"A\",\"A\",\"A\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\"], n = 2\n Output: 16\n Explanation: \n One possible solution is\n A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> idle -> idle -> A -> idle -> idle -> A\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 623, - "title": "Add One Row to Tree", - "question": "class Solution:\n def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:\n \"\"\"\n 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.\n Note that the root node is at depth 1.\n The adding rule is:\n Given 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.\n cur's original left subtree should be the left subtree of the new left subtree root.\n cur's original right subtree should be the right subtree of the new right subtree root.\n If 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:\n Input: root = [4,2,6,3,1,5], val = 1, depth = 2\n Output: [4,1,1,2,null,null,6,3,1,5]\n Example 2:\n Input: root = [4,2,null,3,1], val = 1, depth = 3\n Output: [4,2,null,1,1,3,null,null,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 628, - "title": "Maximum Product of Three Numbers", - "question": "class Solution:\n def maximumProduct(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, find three numbers whose product is maximum and return the maximum product.\n Example 1:\n Input: nums = [1,2,3]\n Output: 6\n Example 2:\n Input: nums = [1,2,3,4]\n Output: 24\n Example 3:\n Input: nums = [-1,-2,-3]\n Output: -6\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 629, - "title": "K Inverse Pairs Array", - "question": "class Solution:\n def kInversePairs(self, n: int, k: int) -> int:\n \"\"\"\n 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].\n Given two integers n and k, return the number of different arrays consist 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:\n Input: n = 3, k = 0\n Output: 1\n Explanation: Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pairs.\n Example 2:\n Input: n = 3, k = 1\n Output: 2\n Explanation: The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 630, - "title": "Course Schedule III", - "question": "class Solution:\n def scheduleCourse(self, courses: List[List[int]]) -> int:\n \"\"\"\n 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.\n You will start on the 1st day and you cannot take two or more courses simultaneously.\n Return the maximum number of courses that you can take.\n Example 1:\n Input: courses = [[100,200],[200,1300],[1000,1250],[2000,3200]]\n Output: 3\n Explanation: \n There are totally 4 courses, but you can take 3 courses at most:\n First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.\n Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. \n Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. \n The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.\n Example 2:\n Input: courses = [[1,2]]\n Output: 1\n Example 3:\n Input: courses = [[3,2],[4,3]]\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 632, - "title": "Smallest Range Covering Elements from K Lists", - "question": "class Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n \"\"\"\n You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists.\n We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.\n Example 1:\n Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\n Output: [20,24]\n Explanation: \n List 1: [4, 10, 15, 24,26], 24 is in range [20,24].\n List 2: [0, 9, 12, 20], 20 is in range [20,24].\n List 3: [5, 18, 22, 30], 22 is in range [20,24].\n Example 2:\n Input: nums = [[1,2,3],[1,2,3],[1,2,3]]\n Output: [1,1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 633, - "title": "Sum of Square Numbers", - "question": "class Solution:\n def judgeSquareSum(self, c: int) -> bool:\n \"\"\"\n Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.\n Example 1:\n Input: c = 5\n Output: true\n Explanation: 1 * 1 + 2 * 2 = 5\n Example 2:\n Input: c = 3\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 636, - "title": "Exclusive Time of Functions", - "question": "class Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n \"\"\"\n On a single-threaded CPU, we execute a program containing n functions. Each function has a unique ID between 0 and n-1.\n Function 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.\n You 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.\n A 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.\n Return 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:\n Input: n = 2, logs = [\"0:start:0\",\"1:start:2\",\"1:end:5\",\"0:end:6\"]\n Output: [3,4]\n Explanation:\n Function 0 starts at the beginning of time 0, then it executes 2 for units of time and reaches the end of time 1.\n Function 1 starts at the beginning of time 2, executes for 4 units of time, and ends at the end of time 5.\n Function 0 resumes execution at the beginning of time 6 and executes for 1 unit of time.\n So function 0 spends 2 + 1 = 3 units of total time executing, and function 1 spends 4 units of total time executing.\n Example 2:\n Input: n = 1, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"0:start:6\",\"0:end:6\",\"0:end:7\"]\n Output: [8]\n Explanation:\n Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\n Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\n Function 0 (initial call) resumes execution then immediately calls itself again.\n Function 0 (2nd recursive call) starts at the beginning of time 6 and executes for 1 unit of time.\n Function 0 (initial call) resumes execution at the beginning of time 7 and executes for 1 unit of time.\n So function 0 spends 2 + 4 + 1 + 1 = 8 units of total time executing.\n Example 3:\n Input: n = 2, logs = [\"0:start:0\",\"0:start:2\",\"0:end:5\",\"1:start:6\",\"1:end:6\",\"0:end:7\"]\n Output: [7,1]\n Explanation:\n Function 0 starts at the beginning of time 0, executes for 2 units of time, and recursively calls itself.\n Function 0 (recursive call) starts at the beginning of time 2 and executes for 4 units of time.\n Function 0 (initial call) resumes execution then immediately calls function 1.\n Function 1 starts at the beginning of time 6, executes 1 unit of time, and ends at the end of time 6.\n Function 0 resumes execution at the beginning of time 6 and executes for 2 units of time.\n So function 0 spends 2 + 4 + 1 = 7 units of total time executing, and function 1 spends 1 unit of total time executing.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 637, - "title": "Average of Levels in Binary Tree", - "question": "class Solution:\n def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n \"\"\"\n 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:\n Input: root = [3,9,20,null,null,15,7]\n Output: [3.00000,14.50000,11.00000]\n Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.\n Hence return [3, 14.5, 11].\n Example 2:\n Input: root = [3,9,20,15,7]\n Output: [3.00000,14.50000,11.00000]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 638, - "title": "Shopping Offers", - "question": "class Solution:\n def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:\n \"\"\"\n 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.\n You 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.\n You 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.\n Return 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:\n Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]\n Output: 14\n Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. \n In special offer 1, you can pay $5 for 3A and 0B\n In special offer 2, you can pay $10 for 1A and 2B. \n You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.\n Example 2:\n Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]\n Output: 11\n Explanation: The price of A is $2, and $3 for B, $4 for C. \n You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. \n You 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. \n You cannot add more items, though only $9 for 2A ,2B and 1C.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 639, - "title": "Decode Ways II", - "question": "class Solution:\n def numDecodings(self, s: str) -> int:\n \"\"\"\n 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\"\n To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, \"11106\" can be mapped into:\n \"AAJF\" with the grouping (1 1 10 6)\n \"KJF\" with the grouping (11 10 6)\n Note that the grouping (1 11 06) is invalid because \"06\" cannot be mapped into 'F' since \"6\" is different from \"06\".\n In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message \"1*\" may represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\". Decoding \"1*\" is equivalent to decoding any of the encoded messages it can represent.\n Given a string s consisting of digits and '*' characters, return the number of ways to decode it.\n Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\n Input: s = \"*\"\n Output: 9\n Explanation: The encoded message can represent any of the encoded messages \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", or \"9\".\n Each of these can be decoded to the strings \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", and \"I\" respectively.\n Hence, there are a total of 9 ways to decode \"*\".\n Example 2:\n Input: s = \"1*\"\n Output: 18\n Explanation: The encoded message can represent any of the encoded messages \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", or \"19\".\n Each of these encoded messages have 2 ways to be decoded (e.g. \"11\" can be decoded to \"AA\" or \"K\").\n Hence, there are a total of 9 * 2 = 18 ways to decode \"1*\".\n Example 3:\n Input: s = \"2*\"\n Output: 15\n Explanation: The encoded message can represent any of the encoded messages \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", or \"29\".\n \"21\", \"22\", \"23\", \"24\", \"25\", and \"26\" have 2 ways of being decoded, but \"27\", \"28\", and \"29\" only have 1 way.\n Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode \"2*\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 640, - "title": "Solve the Equation", - "question": "class Solution:\n def solveEquation(self, equation: str) -> str:\n \"\"\"\n 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.\n If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.\n Example 1:\n Input: equation = \"x+5-3+x=6+x-2\"\n Output: \"x=2\"\n Example 2:\n Input: equation = \"x=x\"\n Output: \"Infinite solutions\"\n Example 3:\n Input: equation = \"2x=x\"\n Output: \"x=0\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 643, - "title": "Maximum Average Subarray I", - "question": "class Solution:\n def findMaxAverage(self, nums: List[int], k: int) -> float:\n \"\"\"\n You are given an integer array nums consisting of n elements, and an integer k.\n Find 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:\n Input: nums = [1,12,-5,-6,50,3], k = 4\n Output: 12.75000\n Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75\n Example 2:\n Input: nums = [5], k = 1\n Output: 5.00000\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 645, - "title": "Set Mismatch", - "question": "class Solution:\n def findErrorNums(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n You are given an integer array nums representing the data status of this set after the error.\n Find the number that occurs twice and the number that is missing and return them in the form of an array.\n Example 1:\n Input: nums = [1,2,2,4]\n Output: [2,3]\n Example 2:\n Input: nums = [1,1]\n Output: [1,2]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 646, - "title": "Maximum Length of Pair Chain", - "question": "class Solution:\n def findLongestChain(self, pairs: List[List[int]]) -> int:\n \"\"\"\n You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.\n A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.\n Return the length longest chain which can be formed.\n You do not need to use up all the given intervals. You can select pairs in any order.\n Example 1:\n Input: pairs = [[1,2],[2,3],[3,4]]\n Output: 2\n Explanation: The longest chain is [1,2] -> [3,4].\n Example 2:\n Input: pairs = [[1,2],[7,8],[4,5]]\n Output: 3\n Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 647, - "title": "Palindromic Substrings", - "question": "class Solution:\n def countSubstrings(self, s: str) -> int:\n \"\"\"\n Given a string s, return the number of palindromic substrings in it.\n A string is a palindrome when it reads the same backward as forward.\n A substring is a contiguous sequence of characters within the string.\n Example 1:\n Input: s = \"abc\"\n Output: 3\n Explanation: Three palindromic strings: \"a\", \"b\", \"c\".\n Example 2:\n Input: s = \"aaa\"\n Output: 6\n Explanation: Six palindromic strings: \"a\", \"a\", \"a\", \"aa\", \"aa\", \"aaa\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 648, - "title": "Replace Words", - "question": "class Solution:\n def replaceWords(self, dictionary: List[str], sentence: str) -> str:\n \"\"\"\n 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 \"an\" is followed by the successor word \"other\", we can form a new word \"another\".\n Given 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.\n Return the sentence after the replacement.\n Example 1:\n Input: dictionary = [\"cat\",\"bat\",\"rat\"], sentence = \"the cattle was rattled by the battery\"\n Output: \"the cat was rat by the bat\"\n Example 2:\n Input: dictionary = [\"a\",\"b\",\"c\"], sentence = \"aadsfasf absbs bbab cadsfafs\"\n Output: \"a a b c\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 649, - "title": "Dota2 Senate", - "question": "class Solution:\n def predictPartyVictory(self, senate: str) -> str:\n \"\"\"\n In the world of Dota2, there are two parties: the Radiant and the Dire.\n The 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:\n Ban one senator's right: A senator can make another senator lose all his rights in this and all the following rounds.\n Announce 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.\n Given 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.\n The 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.\n Suppose 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:\n Input: senate = \"RD\"\n Output: \"Radiant\"\n Explanation: \n The first senator comes from Radiant and he can just ban the next senator's right in round 1. \n And the second senator can't exercise any rights anymore since his right has been banned. \n And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.\n Example 2:\n Input: senate = \"RDD\"\n Output: \"Dire\"\n Explanation: \n The first senator comes from Radiant and he can just ban the next senator's right in round 1. \n And the second senator can't exercise any rights anymore since his right has been banned. \n And the third senator comes from Dire and he can ban the first senator's right in round 1. \n And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 650, - "title": "2 Keys Keyboard", - "question": "class Solution:\n def minSteps(self, n: int) -> int:\n \"\"\"\n 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:\n Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).\n Paste: You can paste the characters which are copied last time.\n Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen.\n Example 1:\n Input: n = 3\n Output: 3\n Explanation: Initially, we have one character 'A'.\n In step 1, we use Copy All operation.\n In step 2, we use Paste operation to get 'AA'.\n In step 3, we use Paste operation to get 'AAA'.\n Example 2:\n Input: n = 1\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 652, - "title": "Find Duplicate Subtrees", - "question": "class Solution:\n def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:\n \"\"\"\n Given the root of a binary tree, return all duplicate subtrees.\n For each kind of duplicate subtrees, you only need to return the root node of any one of them.\n Two trees are duplicate if they have the same structure with the same node values.\n Example 1:\n Input: root = [1,2,3,4,null,2,4,null,null,4]\n Output: [[2,4],[4]]\n Example 2:\n Input: root = [2,1,1]\n Output: [[1]]\n Example 3:\n Input: root = [2,2,2,3,null,3,null]\n Output: [[2,3],[3]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 653, - "title": "Two Sum IV - Input is a BST", - "question": "class Solution:\n def findTarget(self, root: Optional[TreeNode], k: int) -> bool:\n \"\"\"\n 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:\n Input: root = [5,3,6,2,4,null,7], k = 9\n Output: true\n Example 2:\n Input: root = [5,3,6,2,4,null,7], k = 28\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 654, - "title": "Maximum Binary Tree", - "question": "class Solution:\n def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n \"\"\"\n You are given an integer array nums with no duplicates. A maximum binary tree can be built recursively from nums using the following algorithm:\n Create a root node whose value is the maximum value in nums.\n Recursively build the left subtree on the subarray prefix to the left of the maximum value.\n Recursively build the right subtree on the subarray suffix to the right of the maximum value.\n Return the maximum binary tree built from nums.\n Example 1:\n Input: nums = [3,2,1,6,0,5]\n Output: [6,3,5,null,2,0,null,null,1]\n Explanation: The recursive calls are as follow:\n - The largest value in [3,2,1,6,0,5] is 6. Left prefix is [3,2,1] and right suffix is [0,5].\n - The largest value in [3,2,1] is 3. Left prefix is [] and right suffix is [2,1].\n - Empty array, so no child.\n - The largest value in [2,1] is 2. Left prefix is [] and right suffix is [1].\n - Empty array, so no child.\n - Only one element, so child is a node with value 1.\n - The largest value in [0,5] is 5. Left prefix is [0] and right suffix is [].\n - Only one element, so child is a node with value 0.\n - Empty array, so no child.\n Example 2:\n Input: nums = [3,2,1]\n Output: [3,null,2,null,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 655, - "title": "Print Binary Tree", - "question": "class Solution:\n def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:\n \"\"\"\n 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:\n The height of the tree is height and the number of rows m should be equal to height + 1.\n The number of columns n should be equal to 2height+1 - 1.\n Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).\n For 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].\n Continue this process until all the nodes in the tree have been placed.\n Any empty cells should contain the empty string \"\".\n Return the constructed matrix res.\n Example 1:\n Input: root = [1,2]\n Output: \n [[\"\",\"1\",\"\"],\n [\"2\",\"\",\"\"]]\n Example 2:\n Input: root = [1,2,3,null,4]\n Output: \n [[\"\",\"\",\"\",\"1\",\"\",\"\",\"\"],\n [\"\",\"2\",\"\",\"\",\"\",\"3\",\"\"],\n [\"\",\"\",\"4\",\"\",\"\",\"\",\"\"]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 657, - "title": "Robot Return to Origin", - "question": "class Solution:\n def judgeCircle(self, moves: str) -> bool:\n \"\"\"\n 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.\n You 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).\n Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.\n Note: 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:\n Input: moves = \"UD\"\n Output: true\n Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.\n Example 2:\n Input: moves = \"LL\"\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 658, - "title": "Find K Closest Elements", - "question": "class Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n \"\"\"\n 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.\n An 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:\n Input: arr = [1,2,3,4,5], k = 4, x = 3\n Output: [1,2,3,4]\n Example 2:\n Input: arr = [1,2,3,4,5], k = 4, x = -1\n Output: [1,2,3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 659, - "title": "Split Array into Consecutive Subsequences", - "question": "class Solution:\n def isPossible(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an integer array nums that is sorted in non-decreasing order.\n Determine if it is possible to split nums into one or more subsequences such that both of the following conditions are true:\n Each subsequence is a consecutive increasing sequence (i.e. each integer is exactly one more than the previous integer).\n All subsequences have a length of 3 or more.\n Return true if you can split nums according to the above conditions, or false otherwise.\n A 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:\n Input: nums = [1,2,3,3,4,5]\n Output: true\n Explanation: nums can be split into the following subsequences:\n [1,2,3,3,4,5] --> 1, 2, 3\n [1,2,3,3,4,5] --> 3, 4, 5\n Example 2:\n Input: nums = [1,2,3,3,4,4,5,5]\n Output: true\n Explanation: nums can be split into the following subsequences:\n [1,2,3,3,4,4,5,5] --> 1, 2, 3, 4, 5\n [1,2,3,3,4,4,5,5] --> 3, 4, 5\n Example 3:\n Input: nums = [1,2,3,4,4,5]\n Output: false\n Explanation: It is impossible to split nums into consecutive increasing subsequences of length 3 or more.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 661, - "title": "Image Smoother", - "question": "class Solution:\n def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:\n \"\"\"\n An image smoother is a filter of the size 3 x 3 that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother).\n Given an m x n integer matrix img representing the grayscale of an image, return the image after applying the smoother on each cell of it.\n Example 1:\n Input: img = [[1,1,1],[1,0,1],[1,1,1]]\n Output: [[0,0,0],[0,0,0],[0,0,0]]\n Explanation:\n For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0\n For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0\n For the point (1,1): floor(8/9) = floor(0.88888889) = 0\n Example 2:\n Input: img = [[100,200,100],[200,50,200],[100,200,100]]\n Output: [[137,141,137],[141,138,141],[137,141,137]]\n Explanation:\n For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137\n For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141\n For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 662, - "title": "Maximum Width of Binary Tree", - "question": "class Solution:\n def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return the maximum width of the given tree.\n The maximum width of a tree is the maximum width among all levels.\n The 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.\n It is guaranteed that the answer will in the range of a 32-bit signed integer.\n Example 1:\n Input: root = [1,3,2,5,3,null,9]\n Output: 4\n Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).\n Example 2:\n Input: root = [1,3,2,5,null,null,9,6,null,7]\n Output: 7\n Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).\n Example 3:\n Input: root = [1,3,2,5]\n Output: 2\n Explanation: The maximum width exists in the second level with length 2 (3,2).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 664, - "title": "Strange Printer", - "question": "class Solution:\n def strangePrinter(self, s: str) -> int:\n \"\"\"\n There is a strange printer with the following two special properties:\n The printer can only print a sequence of the same character each time.\n At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.\n Given a string s, return the minimum number of turns the printer needed to print it.\n Example 1:\n Input: s = \"aaabbb\"\n Output: 2\n Explanation: Print \"aaa\" first and then print \"bbb\".\n Example 2:\n Input: s = \"aba\"\n Output: 2\n Explanation: Print \"aaa\" first and then print \"b\" from the second place of the string, which will cover the existing character 'a'.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 665, - "title": "Non-decreasing Array", - "question": "class Solution:\n def checkPossibility(self, nums: List[int]) -> bool:\n \"\"\"\n Given an array nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element.\n We 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:\n Input: nums = [4,2,3]\n Output: true\n Explanation: You could modify the first 4 to 1 to get a non-decreasing array.\n Example 2:\n Input: nums = [4,2,1]\n Output: false\n Explanation: You cannot get a non-decreasing array by modifying at most one element.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 667, - "title": "Beautiful Arrangement II", - "question": "class Solution:\n def constructArray(self, n: int, k: int) -> List[int]:\n \"\"\"\n 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:\n Suppose 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.\n Return the list answer. If there multiple valid answers, return any of them.\n Example 1:\n Input: n = 3, k = 1\n Output: [1,2,3]\n Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1\n Example 2:\n Input: n = 3, k = 2\n Output: [1,3,2]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 668, - "title": "Kth Smallest Number in Multiplication Table", - "question": "class Solution:\n def findKthNumber(self, m: int, n: int, k: int) -> int:\n \"\"\"\n 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).\n Given three integers m, n, and k, return the kth smallest element in the m x n multiplication table.\n Example 1:\n Input: m = 3, n = 3, k = 5\n Output: 3\n Explanation: The 5th smallest number is 3.\n Example 2:\n Input: m = 2, n = 3, k = 6\n Output: 6\n Explanation: The 6th smallest number is 6.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 669, - "title": "Trim a Binary Search Tree", - "question": "class Solution:\n def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:\n \"\"\"\n 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.\n Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.\n Example 1:\n Input: root = [1,0,2], low = 1, high = 2\n Output: [1,null,2]\n Example 2:\n Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3\n Output: [3,2,null,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 670, - "title": "Maximum Swap", - "question": "class Solution:\n def maximumSwap(self, num: int) -> int:\n \"\"\"\n You are given an integer num. You can swap two digits at most once to get the maximum valued number.\n Return the maximum valued number you can get.\n Example 1:\n Input: num = 2736\n Output: 7236\n Explanation: Swap the number 2 and the number 7.\n Example 2:\n Input: num = 9973\n Output: 9973\n Explanation: No swap.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 671, - "title": "Second Minimum Node In a Binary Tree", - "question": "class Solution:\n def findSecondMinimumValue(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n Given 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.\n If no such second minimum value exists, output -1 instead.\n Example 1:\n Input: root = [2,2,5,null,null,5,7]\n Output: 5\n Explanation: The smallest value is 2, the second smallest value is 5.\n Example 2:\n Input: root = [2,2,2]\n Output: -1\n Explanation: The smallest value is 2, but there isn't any second smallest value.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 672, - "title": "Bulb Switcher II", - "question": "class Solution:\n def flipLights(self, n: int, presses: int) -> int:\n \"\"\"\n 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:\n Button 1: Flips the status of all the bulbs.\n Button 2: Flips the status of all the bulbs with even labels (i.e., 2, 4, ...).\n Button 3: Flips the status of all the bulbs with odd labels (i.e., 1, 3, ...).\n Button 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, ...).\n You must make exactly presses button presses in total. For each press, you may pick any of the four buttons to press.\n Given the two integers n and presses, return the number of different possible statuses after performing all presses button presses.\n Example 1:\n Input: n = 1, presses = 1\n Output: 2\n Explanation: Status can be:\n - [off] by pressing button 1\n - [on] by pressing button 2\n Example 2:\n Input: n = 2, presses = 1\n Output: 3\n Explanation: Status can be:\n - [off, off] by pressing button 1\n - [on, off] by pressing button 2\n - [off, on] by pressing button 3\n Example 3:\n Input: n = 3, presses = 1\n Output: 4\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 673, - "title": "Number of Longest Increasing Subsequence", - "question": "class Solution:\n def findNumberOfLIS(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the number of longest increasing subsequences.\n Notice that the sequence has to be strictly increasing.\n Example 1:\n Input: nums = [1,3,5,4,7]\n Output: 2\n Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].\n Example 2:\n Input: nums = [2,2,2,2,2]\n Output: 5\n Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 674, - "title": "Longest Continuous Increasing Subsequence", - "question": "class Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n A 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:\n Input: nums = [1,3,5,4,7]\n Output: 3\n Explanation: The longest continuous increasing subsequence is [1,3,5] with length 3.\n Even though [1,3,5,7] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element\n 4.\n Example 2:\n Input: nums = [2,2,2,2,2]\n Output: 1\n Explanation: The longest continuous increasing subsequence is [2] with length 1. Note that it must be strictly\n increasing.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 675, - "title": "Cut Off Trees for Golf Event", - "question": "class Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n \"\"\"\n You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an m x n matrix. In this matrix:\n 0 means the cell cannot be walked through.\n 1 represents an empty cell that can be walked through.\n A number greater than 1 represents a tree in a cell that can be walked through, and this number is the tree's height.\n In one step, you can walk in any of the four directions: north, east, south, and west. If you are standing in a cell with a tree, you can choose whether to cut it off.\n You must cut off the trees in order from shortest to tallest. When you cut off a tree, the value at its cell becomes 1 (an empty cell).\n Starting from the point (0, 0), return the minimum steps you need to walk to cut off all the trees. If you cannot cut off all the trees, return -1.\n Note: 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:\n Input: forest = [[1,2,3],[0,0,4],[7,6,5]]\n Output: 6\n Explanation: Following the path above allows you to cut off the trees from shortest to tallest in 6 steps.\n Example 2:\n Input: forest = [[1,2,3],[0,0,0],[7,6,5]]\n Output: -1\n Explanation: The trees in the bottom row cannot be accessed as the middle row is blocked.\n Example 3:\n Input: forest = [[2,3,4],[0,0,5],[8,7,6]]\n Output: 6\n Explanation: You can follow the same path as Example 1 to cut off all the trees.\n Note that you can cut off the first tree at (0, 0) before making any steps.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 676, - "title": "Implement Magic Dictionary", - "question": "class MagicDictionary:\n def __init__(self):\n def buildDict(self, dictionary: List[str]) -> None:\n def search(self, searchWord: str) -> bool:\n \"\"\"\n Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.\n Implement the MagicDictionary class:\n MagicDictionary() Initializes the object.\n void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.\n bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.\n Example 1:\n Input\n [\"MagicDictionary\", \"buildDict\", \"search\", \"search\", \"search\", \"search\"]\n [[], [[\"hello\", \"leetcode\"]], [\"hello\"], [\"hhllo\"], [\"hell\"], [\"leetcoded\"]]\n Output\n [null, null, false, true, false, false]\n Explanation\n MagicDictionary magicDictionary = new MagicDictionary();\n magicDictionary.buildDict([\"hello\", \"leetcode\"]);\n magicDictionary.search(\"hello\"); // return False\n magicDictionary.search(\"hhllo\"); // We can change the second 'h' to 'e' to match \"hello\" so we return True\n magicDictionary.search(\"hell\"); // return False\n magicDictionary.search(\"leetcoded\"); // return False\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 677, - "title": "Map Sum Pairs", - "question": "class MapSum:\n def __init__(self):\n def insert(self, key: str, val: int) -> None:\n def sum(self, prefix: str) -> int:\n \"\"\"\n Design a map that allows you to do the following:\n Maps a string key to a given value.\n Returns the sum of the values that have a key with a prefix equal to a given string.\n Implement the MapSum class:\n MapSum() Initializes the MapSum object.\n void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one.\n int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.\n Example 1:\n Input\n [\"MapSum\", \"insert\", \"sum\", \"insert\", \"sum\"]\n [[], [\"apple\", 3], [\"ap\"], [\"app\", 2], [\"ap\"]]\n Output\n [null, null, 3, null, 5]\n Explanation\n MapSum mapSum = new MapSum();\n mapSum.insert(\"apple\", 3); \n mapSum.sum(\"ap\"); // return 3 (apple = 3)\n mapSum.insert(\"app\", 2); \n mapSum.sum(\"ap\"); // return 5 (apple + app = 3 + 2 = 5)\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 678, - "title": "Valid Parenthesis String", - "question": "class Solution:\n def checkValidString(self, s: str) -> bool:\n \"\"\"\n Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.\n The following rules define a valid string:\n Any left parenthesis '(' must have a corresponding right parenthesis ')'.\n Any right parenthesis ')' must have a corresponding left parenthesis '('.\n Left 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:\n Input: s = \"()\"\n Output: true\n Example 2:\n Input: s = \"(*)\"\n Output: true\n Example 3:\n Input: s = \"(*))\"\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 679, - "title": "24 Game", - "question": "class Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n \"\"\"\n You are given an integer array cards of length 4. You have four cards, each containing a number in the range [1, 9]. You should arrange the numbers on these cards in a mathematical expression using the operators ['+', '-', '*', '/'] and the parentheses '(' and ')' to get the value 24.\n You are restricted with the following rules:\n The division operator '/' represents real division, not integer division.\n For example, 4 / (1 - 2 / 3) = 4 / (1 / 3) = 12.\n Every operation done is between two numbers. In particular, we cannot use '-' as a unary operator.\n For example, if cards = [1, 1, 1, 1], the expression \"-1 - 1 - 1 - 1\" is not allowed.\n You cannot concatenate numbers together\n For example, if cards = [1, 2, 1, 2], the expression \"12 + 12\" is not valid.\n Return true if you can get such expression that evaluates to 24, and false otherwise.\n Example 1:\n Input: cards = [4,1,8,7]\n Output: true\n Explanation: (8-4) * (7-1) = 24\n Example 2:\n Input: cards = [1,2,1,2]\n Output: false\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 680, - "title": "Valid Palindrome II", - "question": "class Solution:\n def validPalindrome(self, s: str) -> bool:\n \"\"\"\n Given a string s, return true if the s can be palindrome after deleting at most one character from it.\n Example 1:\n Input: s = \"aba\"\n Output: true\n Example 2:\n Input: s = \"abca\"\n Output: true\n Explanation: You could delete the character 'c'.\n Example 3:\n Input: s = \"abc\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 682, - "title": "Baseball Game", - "question": "class Solution:\n def calPoints(self, operations: List[str]) -> int:\n \"\"\"\n You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.\n You 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:\n An integer x.\n Record a new score of x.\n '+'.\n Record a new score that is the sum of the previous two scores.\n 'D'.\n Record a new score that is the double of the previous score.\n 'C'.\n Invalidate the previous score, removing it from the record.\n Return the sum of all the scores on the record after applying all the operations.\n The 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:\n Input: ops = [\"5\",\"2\",\"C\",\"D\",\"+\"]\n Output: 30\n Explanation:\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].\n The total sum is 5 + 10 + 15 = 30.\n Example 2:\n Input: ops = [\"5\",\"-2\",\"4\",\"C\",\"D\",\"9\",\"+\",\"+\"]\n Output: 27\n Explanation:\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].\n The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.\n Example 3:\n Input: ops = [\"1\",\"C\"]\n Output: 0\n Explanation:\n \"1\" - Add 1 to the record, record is now [1].\n \"C\" - Invalidate and remove the previous score, record is now [].\n Since the record is empty, the total sum is 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 684, - "title": "Redundant Connection", - "question": "class Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n \"\"\"\n In this problem, a tree is an undirected graph that is connected and has no cycles.\n You 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.\n Return 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:\n Input: edges = [[1,2],[1,3],[2,3]]\n Output: [2,3]\n Example 2:\n Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\n Output: [1,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 685, - "title": "Redundant Connection II", - "question": "class Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n \"\"\"\n In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.\n The given input is a directed graph that started as a rooted tree with n nodes (with distinct values from 1 to n), with one additional directed edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed.\n The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [ui, vi] that represents a directed edge connecting nodes ui and vi, where ui is a parent of child vi.\n Return an edge that can be removed so that the resulting graph is a rooted tree of n nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.\n Example 1:\n Input: edges = [[1,2],[1,3],[2,3]]\n Output: [2,3]\n Example 2:\n Input: edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\n Output: [4,1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 686, - "title": "Repeated String Match", - "question": "class Solution:\n def repeatedStringMatch(self, a: str, b: str) -> int:\n \"\"\"\n 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\u200b\u200b\u200b\u200b\u200b\u200b to be a substring of a after repeating it, return -1.\n Notice: string \"abc\" repeated 0 times is \"\", repeated 1 time is \"abc\" and repeated 2 times is \"abcabc\".\n Example 1:\n Input: a = \"abcd\", b = \"cdabcdab\"\n Output: 3\n Explanation: We return 3 because by repeating a three times \"abcdabcdabcd\", b is a substring of it.\n Example 2:\n Input: a = \"a\", b = \"aa\"\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 687, - "title": "Longest Univalue Path", - "question": "class Solution:\n def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n The length of the path between two nodes is represented by the number of edges between them.\n Example 1:\n Input: root = [5,4,5,1,1,null,5]\n Output: 2\n Explanation: The shown image shows that the longest path of the same value (i.e. 5).\n Example 2:\n Input: root = [1,4,5,4,4,null,5]\n Output: 2\n Explanation: The shown image shows that the longest path of the same value (i.e. 4).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 688, - "title": "Knight Probability in Chessboard", - "question": "class Solution:\n def knightProbability(self, n: int, k: int, row: int, column: int) -> float:\n \"\"\"\n 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).\n A 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.\n Each 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.\n The knight continues moving until it has made exactly k moves or has moved off the chessboard.\n Return the probability that the knight remains on the board after it has stopped moving.\n Example 1:\n Input: n = 3, k = 2, row = 0, column = 0\n Output: 0.06250\n Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.\n From each of those positions, there are also two moves that will keep the knight on the board.\n The total probability the knight stays on the board is 0.0625.\n Example 2:\n Input: n = 1, k = 0, row = 0, column = 0\n Output: 1.00000\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 689, - "title": "Maximum Sum of 3 Non-Overlapping Subarrays", - "question": "class Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n \"\"\"\n Given an integer array nums and an integer k, find three non-overlapping subarrays of length k with maximum sum and return them.\n Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest one.\n Example 1:\n Input: nums = [1,2,1,2,6,7,5,1], k = 2\n Output: [0,3,5]\n Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].\n We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.\n Example 2:\n Input: nums = [1,2,1,2,1,2,1,2,1], k = 2\n Output: [0,2,4]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 690, - "title": "Employee Importance", - "question": "\n \"\"\"\nclass Employee:\n def __init__(self, id: int, importance: int, subordinates: List[int]):\n self.id = id\n self.importance = importance\n self.subordinates = subordinates\n You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.\n You are given an array of employees employees where:\n employees[i].id is the ID of the ith employee.\n employees[i].importance is the importance value of the ith employee.\n employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee.\n Given 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:\n Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1\n Output: 11\n Explanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.\n They both have an importance value of 3.\n Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11.\n Example 2:\n Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5\n Output: -3\n Explanation: Employee 5 has an importance value of -3 and has no direct subordinates.\n Thus, the total importance value of employee 5 is -3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 691, - "title": "Stickers to Spell Word", - "question": "class Solution:\n def minStickers(self, stickers: List[str], target: str) -> int:\n \"\"\"\n We are given n different types of stickers. Each sticker has a lowercase English word on it.\n You 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.\n Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.\n Note: 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:\n Input: stickers = [\"with\",\"example\",\"science\"], target = \"thehat\"\n Output: 3\n Explanation:\n We can use 2 \"with\" stickers, and 1 \"example\" sticker.\n After cutting and rearrange the letters of those stickers, we can form the target \"thehat\".\n Also, this is the minimum number of stickers necessary to form the target string.\n Example 2:\n Input: stickers = [\"notice\",\"possible\"], target = \"basicbasic\"\n Output: -1\n Explanation:\n We cannot form the target \"basicbasic\" from cutting letters from the given stickers.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 692, - "title": "Top K Frequent Words", - "question": "class Solution:\n def topKFrequent(self, words: List[str], k: int) -> List[str]:\n \"\"\"\n Given an array of strings words and an integer k, return the k most frequent strings.\n Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.\n Example 1:\n Input: words = [\"i\",\"love\",\"leetcode\",\"i\",\"love\",\"coding\"], k = 2\n Output: [\"i\",\"love\"]\n Explanation: \"i\" and \"love\" are the two most frequent words.\n Note that \"i\" comes before \"love\" due to a lower alphabetical order.\n Example 2:\n Input: words = [\"the\",\"day\",\"is\",\"sunny\",\"the\",\"the\",\"the\",\"sunny\",\"is\",\"is\"], k = 4\n Output: [\"the\",\"is\",\"sunny\",\"day\"]\n Explanation: \"the\", \"is\", \"sunny\" and \"day\" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 693, - "title": "Binary Number with Alternating Bits", - "question": "class Solution:\n def hasAlternatingBits(self, n: int) -> bool:\n \"\"\"\n Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.\n Example 1:\n Input: n = 5\n Output: true\n Explanation: The binary representation of 5 is: 101\n Example 2:\n Input: n = 7\n Output: false\n Explanation: The binary representation of 7 is: 111.\n Example 3:\n Input: n = 11\n Output: false\n Explanation: The binary representation of 11 is: 1011.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 695, - "title": "Max Area of Island", - "question": "class Solution:\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n The area of an island is the number of cells with a value 1 in the island.\n Return the maximum area of an island in grid. If there is no island, return 0.\n Example 1:\n Input: 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]]\n Output: 6\n Explanation: The answer is not 11, because the island must be connected 4-directionally.\n Example 2:\n Input: grid = [[0,0,0,0,0,0,0,0]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 696, - "title": "Count Binary Substrings", - "question": "class Solution:\n def countBinarySubstrings(self, s: str) -> int:\n \"\"\"\n 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.\n Substrings that occur multiple times are counted the number of times they occur.\n Example 1:\n Input: s = \"00110011\"\n Output: 6\n Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: \"0011\", \"01\", \"1100\", \"10\", \"0011\", and \"01\".\n Notice that some of these substrings repeat and are counted the number of times they occur.\n Also, \"00110011\" is not a valid substring because all the 0's (and 1's) are not grouped together.\n Example 2:\n Input: s = \"10101\"\n Output: 4\n Explanation: There are 4 substrings: \"10\", \"01\", \"10\", \"01\" that have equal number of consecutive 1's and 0's.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 697, - "title": "Degree of an Array", - "question": "class Solution:\n def findShortestSubArray(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.\n Example 1:\n Input: nums = [1,2,2,3,1]\n Output: 2\n Explanation: \n The input array has a degree of 2 because both elements 1 and 2 appear twice.\n Of 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]\n The shortest length is 2. So return 2.\n Example 2:\n Input: nums = [1,2,2,3,1,4,2]\n Output: 6\n Explanation: \n The degree is 3 because the element 2 is repeated 3 times.\n So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 698, - "title": "Partition to K Equal Sum Subsets", - "question": "class Solution:\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n \"\"\"\n 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:\n Input: nums = [4,3,2,3,5,2,1], k = 4\n Output: true\n Explanation: It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.\n Example 2:\n Input: nums = [1,2,3,4], k = 3\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 699, - "title": "Falling Squares", - "question": "class Solution:\n def fallingSquares(self, positions: List[List[int]]) -> List[int]:\n \"\"\"\n There are several squares being dropped onto the X-axis of a 2D plane.\n You 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.\n Each 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.\n After each square is dropped, you must record the height of the current tallest stack of squares.\n Return an integer array ans where ans[i] represents the height described above after dropping the ith square.\n Example 1:\n Input: positions = [[1,2],[2,3],[6,1]]\n Output: [2,5,5]\n Explanation:\n After the first drop, the tallest stack is square 1 with a height of 2.\n After the second drop, the tallest stack is squares 1 and 2 with a height of 5.\n After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.\n Thus, we return an answer of [2, 5, 5].\n Example 2:\n Input: positions = [[100,100],[200,100]]\n Output: [100,100]\n Explanation:\n After the first drop, the tallest stack is square 1 with a height of 100.\n After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.\n Thus, we return an answer of [100, 100].\n Note that square 2 only brushes the right side of square 1, which does not count as landing on it.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 712, - "title": "Minimum ASCII Delete Sum for Two Strings", - "question": "class Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n \"\"\"\n Given two strings s1 and s2, return the lowest ASCII sum of deleted characters to make two strings equal.\n Example 1:\n Input: s1 = \"sea\", s2 = \"eat\"\n Output: 231\n Explanation: Deleting \"s\" from \"sea\" adds the ASCII value of \"s\" (115) to the sum.\n Deleting \"t\" from \"eat\" adds 116 to the sum.\n At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.\n Example 2:\n Input: s1 = \"delete\", s2 = \"leet\"\n Output: 403\n Explanation: Deleting \"dee\" from \"delete\" to turn the string into \"let\",\n adds 100[d] + 101[e] + 101[e] to the sum.\n Deleting \"e\" from \"leet\" adds 101[e] to the sum.\n At the end, both strings are equal to \"let\", and the answer is 100+101+101+101 = 403.\n If instead we turned both strings into \"lee\" or \"eet\", we would get answers of 433 or 417, which are higher.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 713, - "title": "Subarray Product Less Than K", - "question": "class Solution:\n def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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:\n Input: nums = [10,5,2,6], k = 100\n Output: 8\n Explanation: The 8 subarrays that have product less than 100 are:\n [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]\n Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.\n Example 2:\n Input: nums = [1,2,3], k = 0\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 714, - "title": "Best Time to Buy and Sell Stock with Transaction Fee", - "question": "class Solution:\n def maxProfit(self, prices: List[int], fee: int) -> int:\n \"\"\"\n 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.\n Find 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.\n Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).\n Example 1:\n Input: prices = [1,3,2,8,4,9], fee = 2\n Output: 8\n Explanation: 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\n The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.\n Example 2:\n Input: prices = [1,3,7,5,10,3], fee = 3\n Output: 6\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 715, - "title": "Range Module", - "question": "class RangeModule:\n def __init__(self):\n def addRange(self, left: int, right: int) -> None:\n def queryRange(self, left: int, right: int) -> bool:\n def removeRange(self, left: int, right: int) -> None:\n \"\"\"\n A Range Module is a module that tracks ranges of numbers. Design a data structure to track the ranges represented as half-open intervals and query about them.\n A half-open interval [left, right) denotes all the real numbers x where left <= x < right.\n Implement the RangeModule class:\n RangeModule() Initializes the object of the data structure.\n void addRange(int left, int right) Adds the half-open interval [left, right), tracking every real number in that interval. Adding an interval that partially overlaps with currently tracked numbers should add any numbers in the interval [left, right) that are not already tracked.\n boolean queryRange(int left, int right) Returns true if every real number in the interval [left, right) is currently being tracked, and false otherwise.\n void removeRange(int left, int right) Stops tracking every real number currently being tracked in the half-open interval [left, right).\n Example 1:\n Input\n [\"RangeModule\", \"addRange\", \"removeRange\", \"queryRange\", \"queryRange\", \"queryRange\"]\n [[], [10, 20], [14, 16], [10, 14], [13, 15], [16, 17]]\n Output\n [null, null, null, true, false, true]\n Explanation\n RangeModule rangeModule = new RangeModule();\n rangeModule.addRange(10, 20);\n rangeModule.removeRange(14, 16);\n rangeModule.queryRange(10, 14); // return True,(Every number in [10, 14) is being tracked)\n rangeModule.queryRange(13, 15); // return False,(Numbers like 14, 14.03, 14.17 in [13, 15) are not being tracked)\n rangeModule.queryRange(16, 17); // return True, (The number 16 in [16, 17) is still being tracked, despite the remove operation)\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 717, - "title": "1-bit and 2-bit Characters", - "question": "class Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n \"\"\"\n We have two special characters:\n The first character can be represented by one bit 0.\n The second character can be represented by two bits (10 or 11).\n Given a binary array bits that ends with 0, return true if the last character must be a one-bit character.\n Example 1:\n Input: bits = [1,0,0]\n Output: true\n Explanation: The only way to decode it is two-bit character and one-bit character.\n So the last character is one-bit character.\n Example 2:\n Input: bits = [1,1,1,0]\n Output: false\n Explanation: The only way to decode it is two-bit character and two-bit character.\n So the last character is not one-bit character.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 718, - "title": "Maximum Length of Repeated Subarray", - "question": "class Solution:\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.\n Example 1:\n Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]\n Output: 3\n Explanation: The repeated subarray with maximum length is [3,2,1].\n Example 2:\n Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]\n Output: 5\n Explanation: The repeated subarray with maximum length is [0,0,0,0,0].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 719, - "title": "Find K-th Smallest Pair Distance", - "question": "class Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n \"\"\"\n The distance of a pair of integers a and b is defined as the absolute difference between a and b.\n Given 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:\n Input: nums = [1,3,1], k = 1\n Output: 0\n Explanation: Here are all the pairs:\n (1,3) -> 2\n (1,1) -> 0\n (3,1) -> 2\n Then the 1st smallest distance pair is (1,1), and its distance is 0.\n Example 2:\n Input: nums = [1,1,1], k = 2\n Output: 0\n Example 3:\n Input: nums = [1,6,1], k = 3\n Output: 5\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 720, - "title": "Longest Word in Dictionary", - "question": "class Solution:\n def longestWord(self, words: List[str]) -> str:\n \"\"\"\n 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.\n If 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.\n Note 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:\n Input: words = [\"w\",\"wo\",\"wor\",\"worl\",\"world\"]\n Output: \"world\"\n Explanation: The word \"world\" can be built one character at a time by \"w\", \"wo\", \"wor\", and \"worl\".\n Example 2:\n Input: words = [\"a\",\"banana\",\"app\",\"appl\",\"ap\",\"apply\",\"apple\"]\n Output: \"apple\"\n Explanation: Both \"apply\" and \"apple\" can be built from other words in the dictionary. However, \"apple\" is lexicographically smaller than \"apply\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 721, - "title": "Accounts Merge", - "question": "class Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n \"\"\"\n 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.\n Now, 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.\n After 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:\n Input: accounts = [[\"John\",\"johnsmith@mail.com\",\"john_newyork@mail.com\"],[\"John\",\"johnsmith@mail.com\",\"john00@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\n Output: [[\"John\",\"john00@mail.com\",\"john_newyork@mail.com\",\"johnsmith@mail.com\"],[\"Mary\",\"mary@mail.com\"],[\"John\",\"johnnybravo@mail.com\"]]\n Explanation:\n The first and second John's are the same person as they have the common email \"johnsmith@mail.com\".\n The third John and Mary are different people as none of their email addresses are used by other accounts.\n We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], \n ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.\n Example 2:\n Input: 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\"]]\n Output: [[\"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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 722, - "title": "Remove Comments", - "question": "class Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n \"\"\"\n 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'.\n In C++, there are two types of comments, line comments, and block comments.\n The string \"//\" denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.\n The string \"/*\" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of \"*/\" should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string \"/*/\" does not yet end the block comment, as the ending would be overlapping the beginning.\n The first effective comment takes precedence over others.\n For example, if the string \"//\" occurs in a block comment, it is ignored.\n Similarly, if the string \"/*\" occurs in a line or block comment, it is also ignored.\n If 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.\n There will be no control characters, single quote, or double quote characters.\n For example, source = \"string s = \"/* Not a comment. */\";\" will not be a test case.\n Also, nothing else such as defines or macros will interfere with the comments.\n It is guaranteed that every open block comment will eventually be closed, so \"/*\" outside of a line or block comment always starts a new comment.\n Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.\n After removing the comments from the source code, return the source code in the same format.\n Example 1:\n Input: source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]\n Output: [\"int main()\",\"{ \",\" \",\"int a, b, c;\",\"a = b + c;\",\"}\"]\n Explanation: The line by line code is visualized as below:\n /*Test program */\n int main()\n { \n // variable declaration \n int a, b, c;\n /* This is a test\n multiline \n comment for \n testing */\n a = b + c;\n }\n The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.\n The line by line output code is visualized as below:\n int main()\n { \n int a, b, c;\n a = b + c;\n }\n Example 2:\n Input: source = [\"a/*comment\", \"line\", \"more_comment*/b\"]\n Output: [\"ab\"]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 724, - "title": "Find Pivot Index", - "question": "class Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n \"\"\"\n Given an array of integers nums, calculate the pivot index of this array.\n The 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.\n If 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.\n Return the leftmost pivot index. If no such index exists, return -1.\n Example 1:\n Input: nums = [1,7,3,6,5,6]\n Output: 3\n Explanation:\n The pivot index is 3.\n Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11\n Right sum = nums[4] + nums[5] = 5 + 6 = 11\n Example 2:\n Input: nums = [1,2,3]\n Output: -1\n Explanation:\n There is no index that satisfies the conditions in the problem statement.\n Example 3:\n Input: nums = [2,1,-1]\n Output: 0\n Explanation:\n The pivot index is 0.\n Left sum = 0 (no elements to the left of index 0)\n Right sum = nums[1] + nums[2] = 1 + -1 = 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 725, - "title": "Split Linked List in Parts", - "question": "class Solution:\n def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n \"\"\"\n Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts.\n The 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.\n The 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.\n Return an array of the k parts.\n Example 1:\n Input: head = [1,2,3], k = 5\n Output: [[1],[2],[3],[],[]]\n Explanation:\n The first element output[0] has output[0].val = 1, output[0].next = null.\n The last element output[4] is null, but its string representation as a ListNode is [].\n Example 2:\n Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3\n Output: [[1,2,3,4],[5,6,7],[8,9,10]]\n Explanation:\n The 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 726, - "title": "Number of Atoms", - "question": "class Solution:\n def countOfAtoms(self, formula: str) -> str:\n \"\"\"\n Given a string formula representing a chemical formula, return the count of each atom.\n The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.\n One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow.\n For example, \"H2O\" and \"H2O2\" are possible, but \"H1O2\" is impossible.\n Two formulas are concatenated together to produce another formula.\n For example, \"H2O2He3Mg4\" is also a formula.\n A formula placed in parentheses, and a count (optionally added) is also a formula.\n For example, \"(H2O2)\" and \"(H2O2)3\" are formulas.\n Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.\n The test cases are generated so that all the values in the output fit in a 32-bit integer.\n Example 1:\n Input: formula = \"H2O\"\n Output: \"H2O\"\n Explanation: The count of elements are {'H': 2, 'O': 1}.\n Example 2:\n Input: formula = \"Mg(OH)2\"\n Output: \"H2MgO2\"\n Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.\n Example 3:\n Input: formula = \"K4(ON(SO3)2)2\"\n Output: \"K4N2O14S4\"\n Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 728, - "title": "Self Dividing Numbers", - "question": "class Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n \"\"\"\n A self-dividing number is a number that is divisible by every digit it contains.\n For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.\n A self-dividing number is not allowed to contain the digit zero.\n Given two integers left and right, return a list of all the self-dividing numbers in the range [left, right].\n Example 1:\n Input: left = 1, right = 22\n Output: [1,2,3,4,5,6,7,8,9,11,12,15,22]\n Example 2:\n Input: left = 47, right = 85\n Output: [48,55,66,77]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 729, - "title": "My Calendar I", - "question": "class MyCalendar:\n def __init__(self):\n def book(self, start: int, end: int) -> bool:\n \"\"\"\n 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.\n A double booking happens when two events have some non-empty intersection (i.e., some moment is common to both events.).\n The 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.\n Implement the MyCalendar class:\n MyCalendar() Initializes the calendar object.\n boolean 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:\n Input\n [\"MyCalendar\", \"book\", \"book\", \"book\"]\n [[], [10, 20], [15, 25], [20, 30]]\n Output\n [null, true, false, true]\n Explanation\n MyCalendar myCalendar = new MyCalendar();\n myCalendar.book(10, 20); // return True\n myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.\n myCalendar.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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 730, - "title": "Count Different Palindromic Subsequences", - "question": "class Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n \"\"\"\n 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.\n A subsequence of a string is obtained by deleting zero or more characters from the string.\n A sequence is palindromic if it is equal to the sequence reversed.\n Two sequences a1, a2, ... and b1, b2, ... are different if there is some i for which ai != bi.\n Example 1:\n Input: s = \"bccb\"\n Output: 6\n Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.\n Note that 'bcb' is counted only once, even though it occurs twice.\n Example 2:\n Input: s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"\n Output: 104860361\n Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 731, - "title": "My Calendar II", - "question": "class MyCalendarTwo:\n def __init__(self):\n def book(self, start: int, end: int) -> bool:\n \"\"\"\n You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.\n A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).\n The 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.\n Implement the MyCalendarTwo class:\n MyCalendarTwo() Initializes the calendar object.\n boolean book(int start, int end) Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false and do not add the event to the calendar.\n Example 1:\n Input\n [\"MyCalendarTwo\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\n Output\n [null, true, true, true, false, true, true]\n Explanation\n MyCalendarTwo myCalendarTwo = new MyCalendarTwo();\n myCalendarTwo.book(10, 20); // return True, The event can be booked. \n myCalendarTwo.book(50, 60); // return True, The event can be booked. \n myCalendarTwo.book(10, 40); // return True, The event can be double booked. \n myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.\n myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.\n myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in [25, 40) will be double booked with the third event, the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 732, - "title": "My Calendar III", - "question": "class MyCalendarThree:\n def __init__(self):\n def book(self, startTime: int, endTime: int) -> int:\n \"\"\"\n A k-booking happens when k events have some non-empty intersection (i.e., there is some time that is common to all k events.)\n You are given some events [startTime, endTime), after each given event, return an integer k representing the maximum k-booking between all the previous events.\n Implement the MyCalendarThree class:\n MyCalendarThree() Initializes the object.\n int book(int startTime, int endTime) Returns an integer k representing the largest integer such that there exists a k-booking in the calendar.\n Example 1:\n Input\n [\"MyCalendarThree\", \"book\", \"book\", \"book\", \"book\", \"book\", \"book\"]\n [[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]\n Output\n [null, 1, 1, 2, 3, 3, 3]\n Explanation\n MyCalendarThree myCalendarThree = new MyCalendarThree();\n myCalendarThree.book(10, 20); // return 1\n myCalendarThree.book(50, 60); // return 1\n myCalendarThree.book(10, 40); // return 2\n myCalendarThree.book(5, 15); // return 3\n myCalendarThree.book(5, 10); // return 3\n myCalendarThree.book(25, 55); // return 3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 733, - "title": "Flood Fill", - "question": "class Solution:\n def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:\n \"\"\"\n An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.\n You 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].\n To 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.\n Return the modified image after performing the flood fill.\n Example 1:\n Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2\n Output: [[2,2,2],[2,2,0],[2,0,1]]\n Explanation: 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.\n Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.\n Example 2:\n Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0\n Output: [[0,0,0],[0,0,0]]\n Explanation: The starting pixel is already colored 0, so no changes are made to the image.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 735, - "title": "Asteroid Collision", - "question": "class Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n \"\"\"\n We are given an array asteroids of integers representing asteroids in a row.\n For 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.\n Find 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:\n Input: asteroids = [5,10,-5]\n Output: [5,10]\n Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.\n Example 2:\n Input: asteroids = [8,-8]\n Output: []\n Explanation: The 8 and -8 collide exploding each other.\n Example 3:\n Input: asteroids = [10,2,-5]\n Output: [10]\n Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 736, - "title": "Parse Lisp Expression", - "question": "class Solution:\n def evaluate(self, expression: str) -> int:\n \"\"\"\n You are given a string expression representing a Lisp-like expression to return the integer value of.\n The syntax for these expressions is given as follows.\n An 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.)\n A let expression takes the form \"(let v1 e1 v2 e2 ... vn en expr)\", where let is always the string \"let\", then there are 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.\n An add expression takes the form \"(add e1 e2)\" where add is always the string \"add\", there are always two expressions e1, e2 and the result is the addition of the evaluation of e1 and the evaluation of e2.\n A mult expression takes the form \"(mult e1 e2)\" where mult is always the string \"mult\", there are always two expressions e1, e2 and the result is the multiplication of the evaluation of e1 and the evaluation of e2.\n For 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.\n Finally, there is the concept of scope. When an expression of a variable name is evaluated, within the context of that evaluation, the innermost scope (in terms of parentheses) is checked first for the value of that variable, and then outer scopes are checked sequentially. It is guaranteed that every expression is legal. Please see the examples for more details on the scope.\n Example 1:\n Input: expression = \"(let x 2 (mult x (let x 3 y 4 (add x y))))\"\n Output: 14\n Explanation: In the expression (add x y), when checking for the value of the variable x,\n we check from the innermost scope to the outermost in the context of the variable we are trying to evaluate.\n Since x = 3 is found first, the value of x is 3.\n Example 2:\n Input: expression = \"(let x 3 x 2 x)\"\n Output: 2\n Explanation: Assignment in let statements is processed sequentially.\n Example 3:\n Input: expression = \"(let x 1 y 2 x (add x y) (add x y))\"\n Output: 5\n Explanation: The first (add x y) evaluates as 3, and is assigned to x.\n The second (add x y) evaluates as 3+2 = 5.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 738, - "title": "Monotone Increasing Digits", - "question": "class Solution:\n def monotoneIncreasingDigits(self, n: int) -> int:\n \"\"\"\n An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.\n Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.\n Example 1:\n Input: n = 10\n Output: 9\n Example 2:\n Input: n = 1234\n Output: 1234\n Example 3:\n Input: n = 332\n Output: 299\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 739, - "title": "Daily Temperatures", - "question": "class Solution:\n def dailyTemperatures(self, temperatures: List[int]) -> List[int]:\n \"\"\"\n 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:\n Input: temperatures = [73,74,75,71,69,72,76,73]\n Output: [1,1,4,2,1,1,0,0]\n Example 2:\n Input: temperatures = [30,40,50,60]\n Output: [1,1,1,0]\n Example 3:\n Input: temperatures = [30,60,90]\n Output: [1,1,0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 740, - "title": "Delete and Earn", - "question": "class Solution:\n def deleteAndEarn(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Pick 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.\n Return the maximum number of points you can earn by applying the above operation some number of times.\n Example 1:\n Input: nums = [3,4,2]\n Output: 6\n Explanation: 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 = [].\n You earn a total of 6 points.\n Example 2:\n Input: nums = [2,2,3,3,3,4]\n Output: 9\n Explanation: 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 = [].\n You earn a total of 9 points.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 741, - "title": "Cherry Pickup", - "question": "class Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an n x n grid representing a field of cherries, each cell is one of three possible integers.\n 0 means the cell is empty, so you can pass through,\n 1 means the cell contains a cherry that you can pick up and pass through, or\n -1 means the cell contains a thorn that blocks your way.\n Return the maximum number of cherries you can collect by following the rules below:\n Starting at the position (0, 0) and reaching (n - 1, n - 1) by moving right or down through valid path cells (cells with value 0 or 1).\n After reaching (n - 1, n - 1), returning to (0, 0) by moving left or up through valid path cells.\n When passing through a path cell containing a cherry, you pick it up, and the cell becomes an empty cell 0.\n If there is no valid path between (0, 0) and (n - 1, n - 1), then no cherries can be collected.\n Example 1:\n Input: grid = [[0,1,-1],[1,0,-1],[1,1,1]]\n Output: 5\n Explanation: The player started at (0, 0) and went down, down, right right to reach (2, 2).\n 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].\n Then, the player went left, up, up, left to return home, picking up one more cherry.\n The total number of cherries picked up is 5, and this is the maximum possible.\n Example 2:\n Input: grid = [[1,1,-1],[1,-1,1],[-1,1,1]]\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 709, - "title": "To Lower Case", - "question": "class Solution:\n def toLowerCase(self, s: str) -> str:\n \"\"\"\n Given a string s, return the string after replacing every uppercase letter with the same lowercase letter.\n Example 1:\n Input: s = \"Hello\"\n Output: \"hello\"\n Example 2:\n Input: s = \"here\"\n Output: \"here\"\n Example 3:\n Input: s = \"LOVELY\"\n Output: \"lovely\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 743, - "title": "Network Delay Time", - "question": "class Solution:\n def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:\n \"\"\"\n 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.\n We 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:\n Input: times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2\n Output: 2\n Example 2:\n Input: times = [[1,2,1]], n = 2, k = 1\n Output: 1\n Example 3:\n Input: times = [[1,2,1]], n = 2, k = 2\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 744, - "title": "Find Smallest Letter Greater Than Target", - "question": "class Solution:\n def nextGreatestLetter(self, letters: List[str], target: str) -> str:\n \"\"\"\n 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.\n Return 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:\n Input: letters = [\"c\",\"f\",\"j\"], target = \"a\"\n Output: \"c\"\n Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'.\n Example 2:\n Input: letters = [\"c\",\"f\",\"j\"], target = \"c\"\n Output: \"f\"\n Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'.\n Example 3:\n Input: letters = [\"x\",\"x\",\"y\",\"y\"], target = \"z\"\n Output: \"x\"\n Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 745, - "title": "Prefix and Suffix Search", - "question": "class WordFilter:\n def __init__(self, words: List[str]):\n def f(self, pref: str, suff: str) -> int:\n \"\"\"\n Design a special dictionary that searches the words in it by a prefix and a suffix.\n Implement the WordFilter class:\n WordFilter(string[] words) Initializes the object with the words in the dictionary.\n f(string pref, string suff) Returns the index of the word in the dictionary, which has the prefix pref and the suffix suff. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.\n Example 1:\n Input\n [\"WordFilter\", \"f\"]\n [[[\"apple\"]], [\"a\", \"e\"]]\n Output\n [null, 0]\n Explanation\n WordFilter wordFilter = new WordFilter([\"apple\"]);\n wordFilter.f(\"a\", \"e\"); // return 0, because the word at index 0 has prefix = \"a\" and suffix = \"e\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 746, - "title": "Min Cost Climbing Stairs", - "question": "class Solution:\n def minCostClimbingStairs(self, cost: List[int]) -> int:\n \"\"\"\n 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.\n You can either start from the step with index 0, or the step with index 1.\n Return the minimum cost to reach the top of the floor.\n Example 1:\n Input: cost = [10,15,20]\n Output: 15\n Explanation: You will start at index 1.\n - Pay 15 and climb two steps to reach the top.\n The total cost is 15.\n Example 2:\n Input: cost = [1,100,1,1,1,100,1,1,100,1]\n Output: 6\n Explanation: 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.\n The total cost is 6.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 747, - "title": "Largest Number At Least Twice of Others", - "question": "class Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums where the largest integer is unique.\n Determine 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:\n Input: nums = [3,6,1,0]\n Output: 1\n Explanation: 6 is the largest integer.\n For every other number in the array x, 6 is at least twice as big as x.\n The index of value 6 is 1, so we return 1.\n Example 2:\n Input: nums = [1,2,3,4]\n Output: -1\n Explanation: 4 is less than twice the value of 3, so we return -1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 748, - "title": "Shortest Completing Word", - "question": "class Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n \"\"\"\n Given a string licensePlate and an array of strings words, find the shortest completing word in words.\n A 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.\n For example, if licensePlate = \"aBc 12c\", then it contains letters 'a', 'b' (ignoring case), and 'c' twice. Possible completing words are \"abccdef\", \"caaacab\", and \"cbca\".\n Return 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:\n Input: licensePlate = \"1s3 PSt\", words = [\"step\",\"steps\",\"stripe\",\"stepple\"]\n Output: \"steps\"\n Explanation: 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'.\n Since \"steps\" is the only word containing all the letters, that is the answer.\n Example 2:\n Input: licensePlate = \"1s3 456\", words = [\"looks\",\"pest\",\"stew\",\"show\"]\n Output: \"pest\"\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 749, - "title": "Contain Virus", - "question": "class Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n \"\"\"\n A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.\n The world is modeled as an m x n binary grid isInfected, where isInfected[i][j] == 0 represents uninfected cells, and isInfected[i][j] == 1 represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two 4-directionally adjacent cells, on the shared boundary.\n Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There will never be a tie.\n Return the number of walls used to quarantine all the infected regions. If the world will become fully infected, return the number of walls used.\n Example 1:\n Input: isInfected = [[0,1,0,0,0,0,0,1],[0,1,0,0,0,0,0,1],[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0]]\n Output: 10\n Explanation: There are 2 contaminated regions.\n On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:\n On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.\n Example 2:\n Input: isInfected = [[1,1,1],[1,0,1],[1,1,1]]\n Output: 4\n Explanation: Even though there is only one cell saved, there are 4 walls built.\n Notice that walls are only built on the shared boundary of two different cells.\n Example 3:\n Input: isInfected = [[1,1,1,0,0,0,0,0,0],[1,0,1,0,1,1,1,1,1],[1,1,1,0,0,0,0,0,0]]\n Output: 13\n Explanation: The region on the left only builds two new walls.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 752, - "title": "Open the Lock", - "question": "class Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n \"\"\"\n 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.\n The lock initially starts at '0000', a string representing the state of the 4 wheels.\n You 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.\n Given 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:\n Input: deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\"\n Output: 6\n Explanation: \n A sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\".\n Note that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid,\n because the wheels of the lock become stuck after the display becomes the dead end \"0102\".\n Example 2:\n Input: deadends = [\"8888\"], target = \"0009\"\n Output: 1\n Explanation: We can turn the last wheel in reverse to move from \"0000\" -> \"0009\".\n Example 3:\n Input: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\"\n Output: -1\n Explanation: We cannot reach the target without getting stuck.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 753, - "title": "Cracking the Safe", - "question": "class Solution:\n def crackSafe(self, n: int, k: int) -> str:\n \"\"\"\n 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].\n The 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.\n For example, the correct password is \"345\" and you enter in \"012345\":\n After typing 0, the most recent 3 digits is \"0\", which is incorrect.\n After typing 1, the most recent 3 digits is \"01\", which is incorrect.\n After typing 2, the most recent 3 digits is \"012\", which is incorrect.\n After typing 3, the most recent 3 digits is \"123\", which is incorrect.\n After typing 4, the most recent 3 digits is \"234\", which is incorrect.\n After typing 5, the most recent 3 digits is \"345\", which is correct and the safe unlocks.\n Return any string of minimum length that will unlock the safe at some point of entering it.\n Example 1:\n Input: n = 1, k = 2\n Output: \"10\"\n Explanation: The password is a single digit, so enter each digit. \"01\" would also unlock the safe.\n Example 2:\n Input: n = 2, k = 2\n Output: \"01100\"\n Explanation: 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.\n Thus \"01100\" will unlock the safe. \"10011\", and \"11001\" would also unlock the safe.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 754, - "title": "Reach a Number", - "question": "class Solution:\n def reachNumber(self, target: int) -> int:\n \"\"\"\n You are standing at position 0 on an infinite number line. There is a destination at position target.\n You can make some number of moves numMoves so that:\n On each move, you can either go left or right.\n During the ith move (starting from i == 1 to i == numMoves), you take i steps in the chosen direction.\n Given the integer target, return the minimum number of moves required (i.e., the minimum numMoves) to reach the destination.\n Example 1:\n Input: target = 2\n Output: 3\n Explanation:\n On the 1st move, we step from 0 to 1 (1 step).\n On the 2nd move, we step from 1 to -1 (2 steps).\n On the 3rd move, we step from -1 to 2 (3 steps).\n Example 2:\n Input: target = 3\n Output: 2\n Explanation:\n On the 1st move, we step from 0 to 1 (1 step).\n On the 2nd move, we step from 1 to 3 (2 steps).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 756, - "title": "Pyramid Transition Matrix", - "question": "class Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n \"\"\"\n 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.\n To 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.\n For 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.\n You start with a bottom row of blocks bottom, given as a single string, that you must use as the base of the pyramid.\n Given 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:\n Input: bottom = \"BCD\", allowed = [\"BCC\",\"CDE\",\"CEA\",\"FFF\"]\n Output: true\n Explanation: The allowed triangular patterns are shown on the right.\n Starting from the bottom (level 3), we can build \"CE\" on level 2 and then build \"A\" on level 1.\n There are three triangular patterns in the pyramid, which are \"BCC\", \"CDE\", and \"CEA\". All are allowed.\n Example 2:\n Input: bottom = \"AAAA\", allowed = [\"AAB\",\"AAC\",\"BCD\",\"BBE\",\"DEF\"]\n Output: false\n Explanation: The allowed triangular patterns are shown on the right.\n Starting 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 757, - "title": "Set Intersection Size At Least Two", - "question": "class Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n \"\"\"\n You are given a 2D integer array intervals where intervals[i] = [starti, endi] represents all the integers from starti to endi inclusively.\n A containing set is an array nums where each interval from intervals has at least two integers in nums.\n For 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.\n Return the minimum possible size of a containing set.\n Example 1:\n Input: intervals = [[1,3],[3,7],[8,9]]\n Output: 5\n Explanation: let nums = [2, 3, 4, 8, 9].\n It can be shown that there cannot be any containing array of size 4.\n Example 2:\n Input: intervals = [[1,3],[1,4],[2,5],[3,5]]\n Output: 3\n Explanation: let nums = [2, 3, 4].\n It can be shown that there cannot be any containing array of size 2.\n Example 3:\n Input: intervals = [[1,2],[2,3],[2,4],[4,5]]\n Output: 5\n Explanation: let nums = [1, 2, 3, 4, 5].\n It can be shown that there cannot be any containing array of size 4.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 761, - "title": "Special Binary String", - "question": "class Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \"\"\"\n Special binary strings are binary strings with the following two properties:\n The number of 0's is equal to the number of 1's.\n Every prefix of the binary string has at least as many 1's as 0's.\n You are given a special binary string s.\n A move consists of choosing two consecutive, non-empty, special substrings of s, and swapping them. Two strings are consecutive if the last character of the first string is exactly one index before the first character of the second string.\n Return the lexicographically largest resulting string possible after applying the mentioned operations on the string.\n Example 1:\n Input: s = \"11011000\"\n Output: \"11100100\"\n Explanation: The strings \"10\" [occuring at s[1]] and \"1100\" [at s[3]] are swapped.\n This is the lexicographically largest string possible after some number of swaps.\n Example 2:\n Input: s = \"10\"\n Output: \"10\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 429, - "title": "N-ary Tree Level Order Traversal", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n Given an n-ary tree, return the level order traversal of its nodes' values.\n Nary-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:\n Input: root = [1,null,3,2,4,null,5,6]\n Output: [[1],[3,2,4],[5,6]]\n Example 2:\n Input: 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]\n Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 430, - "title": "Flatten a Multilevel Doubly Linked List", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val, prev, next, child):\n self.val = val\n self.prev = prev\n self.next = next\n self.child = child\n 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.\n Given 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.\n Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null.\n Example 1:\n Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]\n Output: [1,2,3,7,8,11,12,9,10,4,5,6]\n Explanation: The multilevel linked list in the input is shown.\n After flattening the multilevel linked list it becomes:\n Example 2:\n Input: head = [1,2,null,3]\n Output: [1,3,2]\n Explanation: The multilevel linked list in the input is shown.\n After flattening the multilevel linked list it becomes:\n Example 3:\n Input: head = []\n Output: []\n Explanation: There could be empty list in the input.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 762, - "title": "Prime Number of Set Bits in Binary Representation", - "question": "class Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n \"\"\"\n 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.\n Recall that the number of set bits an integer has is the number of 1's present when written in binary.\n For example, 21 written in binary is 10101, which has 3 set bits.\n Example 1:\n Input: left = 6, right = 10\n Output: 4\n Explanation:\n 6 -> 110 (2 set bits, 2 is prime)\n 7 -> 111 (3 set bits, 3 is prime)\n 8 -> 1000 (1 set bit, 1 is not prime)\n 9 -> 1001 (2 set bits, 2 is prime)\n 10 -> 1010 (2 set bits, 2 is prime)\n 4 numbers have a prime number of set bits.\n Example 2:\n Input: left = 10, right = 15\n Output: 5\n Explanation:\n 10 -> 1010 (2 set bits, 2 is prime)\n 11 -> 1011 (3 set bits, 3 is prime)\n 12 -> 1100 (2 set bits, 2 is prime)\n 13 -> 1101 (3 set bits, 3 is prime)\n 14 -> 1110 (3 set bits, 3 is prime)\n 15 -> 1111 (4 set bits, 4 is not prime)\n 5 numbers have a prime number of set bits.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 763, - "title": "Partition Labels", - "question": "class Solution:\n def partitionLabels(self, s: str) -> List[int]:\n \"\"\"\n 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.\n Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.\n Return a list of integers representing the size of these parts.\n Example 1:\n Input: s = \"ababcbacadefegdehijhklij\"\n Output: [9,7,8]\n Explanation:\n The partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\n This is a partition so that each letter appears in at most one part.\n A partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits s into less parts.\n Example 2:\n Input: s = \"eccbbbbdec\"\n Output: [10]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 764, - "title": "Largest Plus Sign", - "question": "class Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the order of the largest axis-aligned plus sign of 1's contained in grid. If there is none, return 0.\n An 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:\n Input: n = 5, mines = [[4,2]]\n Output: 2\n Explanation: In the above grid, the largest plus sign can only be of order 2. One of them is shown.\n Example 2:\n Input: n = 1, mines = [[0,0]]\n Output: 0\n Explanation: There is no plus sign, so return 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 765, - "title": "Couples Holding Hands", - "question": "class Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n \"\"\"\n There are n couples sitting in 2n seats arranged in a row and want to hold hands.\n The 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).\n Return 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:\n Input: row = [0,2,1,3]\n Output: 1\n Explanation: We only need to swap the second (row[1]) and third (row[2]) person.\n Example 2:\n Input: row = [3,2,0,1]\n Output: 0\n Explanation: All couples are already seated side by side.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 427, - "title": "Construct Quad Tree", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n Given a n * n matrix grid of 0's and 1's only. We want to represent the grid with a Quad-Tree.\n Return the root of the Quad-Tree representing the grid.\n Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.\n A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:\n val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.\n isLeaf: True if the node is leaf node on the tree or False if the node has the four children.\n class 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 }\n We can construct a Quad-Tree from a two-dimensional area using the following steps:\n If 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.\n If 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.\n Recurse for each of the children with the proper sub-grid.\n If you want to know more about the Quad-Tree, you can refer to the wiki.\n Quad-Tree format:\n 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.\n It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].\n If 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:\n Input: grid = [[0,1],[1,0]]\n Output: [[0,1],[1,0],[1,1],[1,1],[1,0]]\n Explanation: The explanation of this example is shown below:\n Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree.\n Example 2:\n Input: 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]]\n Output: [[0,1],[1,1],[0,1],[1,1],[1,0],null,null,null,null,[1,0],[1,0],[1,1],[1,1]]\n Explanation: All values in the grid are not the same. We divide the grid into four sub-grids.\n The topLeft, bottomLeft and bottomRight each has the same value.\n The topRight have different values so we divide it into 4 sub-grids where each has the same value.\n Explanation is shown in the photo below:\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 558, - "title": "Logical OR of Two Binary Grids Represented as Quad-Trees", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):\n self.val = val\n self.isLeaf = isLeaf\n self.topLeft = topLeft\n self.topRight = topRight\n self.bottomLeft = bottomLeft\n self.bottomRight = bottomRight\n A Binary Matrix is a matrix in which all the elements are either 0 or 1.\n Given quadTree1 and quadTree2. quadTree1 represents a n * n binary matrix and quadTree2 represents another n * n binary matrix.\n Return 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.\n Notice that you can assign the value of a node to True or False when isLeaf is False, and both are accepted in the answer.\n A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes:\n val: True if the node represents a grid of 1's or False if the node represents a grid of 0's.\n isLeaf: True if the node is leaf node on the tree or False if the node has the four children.\n class 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 }\n We can construct a Quad-Tree from a two-dimensional area using the following steps:\n If 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.\n If 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.\n Recurse for each of the children with the proper sub-grid.\n If you want to know more about the Quad-Tree, you can refer to the wiki.\n Quad-Tree format:\n The 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.\n It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list [isLeaf, val].\n If 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:\n Input: 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]]\n Output: [[0,0],[1,1],[1,1],[1,1],[1,0]]\n Explanation: quadTree1 and quadTree2 are shown above. You can see the binary matrix which is represented by each Quad-Tree.\n If we apply logical bitwise OR on the two binary matrices we get the binary matrix below which is represented by the result Quad-Tree.\n Notice that the binary matrices shown are only for illustration, you don't have to construct the binary matrix to get the result tree.\n Example 2:\n Input: quadTree1 = [[1,0]], quadTree2 = [[1,0]]\n Output: [[1,0]]\n Explanation: Each tree represents a binary matrix of size 1*1. Each matrix contains only zero.\n The resulting matrix is of size 1*1 with also zero.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 559, - "title": "Maximum Depth of N-ary Tree", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n Given a n-ary tree, find its maximum depth.\n The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.\n Nary-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:\n Input: root = [1,null,3,2,4,null,5,6]\n Output: 3\n Example 2:\n Input: 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]\n Output: 5\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 589, - "title": "N-ary Tree Preorder Traversal", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n Given the root of an n-ary tree, return the preorder traversal of its nodes' values.\n Nary-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:\n Input: root = [1,null,3,2,4,null,5,6]\n Output: [1,3,5,6,2,4]\n Example 2:\n Input: 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]\n Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 590, - "title": "N-ary Tree Postorder Traversal", - "question": "\n \"\"\"\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n Given the root of an n-ary tree, return the postorder traversal of its nodes' values.\n Nary-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:\n Input: root = [1,null,3,2,4,null,5,6]\n Output: [5,6,3,2,4,1]\n Example 2:\n Input: 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]\n Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 766, - "title": "Toeplitz Matrix", - "question": "class Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n \"\"\"\n Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.\n A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.\n Example 1:\n Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]\n Output: true\n Explanation:\n In the above grid, the diagonals are:\n \"[9]\", \"[5, 5]\", \"[1, 1, 1]\", \"[2, 2, 2]\", \"[3, 3]\", \"[4]\".\n In each diagonal all elements are the same, so the answer is True.\n Example 2:\n Input: matrix = [[1,2],[2,2]]\n Output: false\n Explanation:\n The diagonal \"[1, 2]\" has different elements.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 767, - "title": "Reorganize String", - "question": "class Solution:\n def reorganizeString(self, s: str) -> str:\n \"\"\"\n Given a string s, rearrange the characters of s so that any two adjacent characters are not the same.\n Return any possible rearrangement of s or return \"\" if not possible.\n Example 1:\n Input: s = \"aab\"\n Output: \"aba\"\n Example 2:\n Input: s = \"aaab\"\n Output: \"\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 768, - "title": "Max Chunks To Make Sorted II", - "question": "class Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n \"\"\"\n You are given an integer array arr.\n We 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.\n Return the largest number of chunks we can make to sort the array.\n Example 1:\n Input: arr = [5,4,3,2,1]\n Output: 1\n Explanation:\n Splitting into two or more chunks will not return the required result.\n For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.\n Example 2:\n Input: arr = [2,1,3,4,4]\n Output: 4\n Explanation:\n We can split into two chunks, such as [2, 1], [3, 4, 4].\n However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 769, - "title": "Max Chunks To Make Sorted", - "question": "class Solution:\n def maxChunksToSorted(self, arr: List[int]) -> int:\n \"\"\"\n You are given an integer array arr of length n that represents a permutation of the integers in the range [0, n - 1].\n We 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.\n Return the largest number of chunks we can make to sort the array.\n Example 1:\n Input: arr = [4,3,2,1,0]\n Output: 1\n Explanation:\n Splitting into two or more chunks will not return the required result.\n For example, splitting into [4, 3], [2, 1, 0] will result in [3, 4, 0, 1, 2], which isn't sorted.\n Example 2:\n Input: arr = [1,0,2,3,4]\n Output: 4\n Explanation:\n We can split into two chunks, such as [1, 0], [2, 3, 4].\n However, splitting into [1, 0], [2], [3], [4] is the highest number of chunks possible.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 770, - "title": "Basic Calculator IV", - "question": "class Solution:\n def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]:\n \"\"\"\n Given an expression such as expression = \"e + 8 - a + 5\" and an evaluation map such as {\"e\": 1} (given in terms of evalvars = [\"e\"] and evalints = [1]), return a list of tokens representing the simplified expression, such as [\"-1*a\",\"14\"]\n An expression alternates chunks and symbols, with a space separating each chunk and symbol.\n A chunk is either an expression in parentheses, a variable, or a non-negative integer.\n A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like \"2x\" or \"-x\".\n Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction.\n For example, expression = \"1 + 2 * 3\" has an answer of [\"7\"].\n The format of the output is as follows:\n For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.\n For example, we would never write a term like \"b*a*c\", only \"a*b*c\".\n Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.\n For example, \"a*a*b*c\" has degree 4.\n The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.\n An example of a well-formatted answer is [\"-2*a*a*a\", \"3*a*a*b\", \"3*b*b\", \"4*a\", \"5*c\", \"-6\"].\n Terms (including constant terms) with coefficient 0 are not included.\n For example, an expression of \"0\" has an output of [].\n Note: You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].\n Example 1:\n Input: expression = \"e + 8 - a + 5\", evalvars = [\"e\"], evalints = [1]\n Output: [\"-1*a\",\"14\"]\n Example 2:\n Input: expression = \"e - 8 + temperature - pressure\", evalvars = [\"e\", \"temperature\"], evalints = [1, 12]\n Output: [\"-1*pressure\",\"5\"]\n Example 3:\n Input: expression = \"(e + 8) * (e - 8)\", evalvars = [], evalints = []\n Output: [\"1*e*e\",\"-64\"]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 771, - "title": "Jewels and Stones", - "question": "class Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n \"\"\"\n 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.\n Letters are case sensitive, so \"a\" is considered a different type of stone from \"A\".\n Example 1:\n Input: jewels = \"aA\", stones = \"aAAbbbb\"\n Output: 3\n Example 2:\n Input: jewels = \"z\", stones = \"ZZ\"\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 700, - "title": "Search in a Binary Search Tree", - "question": "class Solution:\n def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n \"\"\"\n You are given the root of a binary search tree (BST) and an integer val.\n Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.\n Example 1:\n Input: root = [4,2,7,1,3], val = 2\n Output: [2,1,3]\n Example 2:\n Input: root = [4,2,7,1,3], val = 5\n Output: []\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 701, - "title": "Insert into a Binary Search Tree", - "question": "class Solution:\n def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n \"\"\"\n 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.\n Notice 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:\n Input: root = [4,2,7,1,3], val = 5\n Output: [4,2,7,1,3,5]\n Explanation: Another accepted tree is:\n Example 2:\n Input: root = [40,20,60,10,30,50,70], val = 25\n Output: [40,20,60,10,30,50,70,null,null,25]\n Example 3:\n Input: root = [4,2,7,1,3,null,null,null,null,null,null], val = 5\n Output: [4,2,7,1,3,5]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 773, - "title": "Sliding Puzzle", - "question": "class Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n \"\"\"\n 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.\n The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].\n Given 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:\n Input: board = [[1,2,3],[4,0,5]]\n Output: 1\n Explanation: Swap the 0 and the 5 in one move.\n Example 2:\n Input: board = [[1,2,3],[5,4,0]]\n Output: -1\n Explanation: No number of moves will make the board solved.\n Example 3:\n Input: board = [[4,1,2],[5,0,3]]\n Output: 5\n Explanation: 5 is the smallest number of moves that solves the board.\n An example path:\n After move 0: [[4,1,2],[5,0,3]]\n After move 1: [[4,1,2],[0,5,3]]\n After move 2: [[0,1,2],[4,5,3]]\n After move 3: [[1,0,2],[4,5,3]]\n After move 4: [[1,2,0],[4,5,3]]\n After move 5: [[1,2,3],[4,5,0]]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 703, - "title": "Kth Largest Element in a Stream", - "question": "class KthLargest:\n def __init__(self, k: int, nums: List[int]):\n def add(self, val: int) -> int:\n \"\"\"\n Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.\n Implement KthLargest class:\n KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.\n int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.\n Example 1:\n Input\n [\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"]\n [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]\n Output\n [null, 4, 5, 5, 8, 8]\n Explanation\n KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\n kthLargest.add(3); // return 4\n kthLargest.add(5); // return 5\n kthLargest.add(10); // return 5\n kthLargest.add(9); // return 8\n kthLargest.add(4); // return 8\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 775, - "title": "Global and Local Inversions", - "question": "class Solution:\n def isIdealPermutation(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].\n The number of global inversions is the number of the different pairs (i, j) where:\n 0 <= i < j < n\n nums[i] > nums[j]\n The number of local inversions is the number of indices i where:\n 0 <= i < n - 1\n nums[i] > nums[i + 1]\n Return true if the number of global inversions is equal to the number of local inversions.\n Example 1:\n Input: nums = [1,0,2]\n Output: true\n Explanation: There is 1 global inversion and 1 local inversion.\n Example 2:\n Input: nums = [1,2,0]\n Output: false\n Explanation: There are 2 global inversions and 1 local inversion.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 704, - "title": "Binary Search", - "question": "class Solution:\n def search(self, nums: List[int], target: int) -> int:\n \"\"\"\n 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.\n You must write an algorithm with O(log n) runtime complexity.\n Example 1:\n Input: nums = [-1,0,3,5,9,12], target = 9\n Output: 4\n Explanation: 9 exists in nums and its index is 4\n Example 2:\n Input: nums = [-1,0,3,5,9,12], target = 2\n Output: -1\n Explanation: 2 does not exist in nums so return -1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 777, - "title": "Swap Adjacent in LR String", - "question": "class Solution:\n def canTransform(self, start: str, end: str) -> bool:\n \"\"\"\n 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:\n Input: start = \"RXXLRXRXL\", end = \"XRLXXRRLX\"\n Output: true\n Explanation: We can transform start to end following these steps:\n RXXLRXRXL ->\n XRXLRXRXL ->\n XRLXRXRXL ->\n XRLXXRRXL ->\n XRLXXRRLX\n Example 2:\n Input: start = \"X\", end = \"L\"\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 778, - "title": "Swim in Rising Water", - "question": "class Solution:\n def swimInWater(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an n x n integer matrix grid where each value grid[i][j] represents the elevation at that point (i, j).\n The 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.\n Return 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:\n Input: grid = [[0,2],[1,3]]\n Output: 3\n Explanation:\n At time 0, you are in grid location (0, 0).\n You cannot go anywhere else because 4-directionally adjacent neighbors have a higher elevation than t = 0.\n You cannot reach point (1, 1) until time 3.\n When the depth of water is 3, we can swim anywhere inside the grid.\n Example 2:\n Input: 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]]\n Output: 16\n Explanation: The final route is shown.\n We need to wait until time 16 so that (0, 0) and (4, 4) are connected.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 779, - "title": "K-th Symbol in Grammar", - "question": "class Solution:\n def kthGrammar(self, n: int, k: int) -> int:\n \"\"\"\n 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.\n For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.\n Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.\n Example 1:\n Input: n = 1, k = 1\n Output: 0\n Explanation: row 1: 0\n Example 2:\n Input: n = 2, k = 1\n Output: 0\n Explanation: \n row 1: 0\n row 2: 01\n Example 3:\n Input: n = 2, k = 2\n Output: 1\n Explanation: \n row 1: 0\n row 2: 01\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 780, - "title": "Reaching Points", - "question": "class Solution:\n def reachingPoints(self, sx: int, sy: int, tx: int, ty: int) -> bool:\n \"\"\"\n 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.\n The allowed operation on some point (x, y) is to convert it to either (x, x + y) or (x + y, y).\n Example 1:\n Input: sx = 1, sy = 1, tx = 3, ty = 5\n Output: true\n Explanation:\n One series of moves that transforms the starting point to the target is:\n (1, 1) -> (1, 2)\n (1, 2) -> (3, 2)\n (3, 2) -> (3, 5)\n Example 2:\n Input: sx = 1, sy = 1, tx = 2, ty = 2\n Output: false\n Example 3:\n Input: sx = 1, sy = 1, tx = 1, ty = 1\n Output: true\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 781, - "title": "Rabbits in Forest", - "question": "class Solution:\n def numRabbits(self, answers: List[int]) -> int:\n \"\"\"\n 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.\n Given the array answers, return the minimum number of rabbits that could be in the forest.\n Example 1:\n Input: answers = [1,1,2]\n Output: 5\n Explanation:\n The two rabbits that answered \"1\" could both be the same color, say red.\n The rabbit that answered \"2\" can't be red or the answers would be inconsistent.\n Say the rabbit that answered \"2\" was blue.\n Then there should be 2 other blue rabbits in the forest that didn't answer into the array.\n The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.\n Example 2:\n Input: answers = [10,10,10]\n Output: 11\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 782, - "title": "Transform to Chessboard", - "question": "class Solution:\n def movesToChessboard(self, board: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.\n A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.\n Example 1:\n Input: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\n Output: 2\n Explanation: One potential sequence of moves is shown.\n The first move swaps the first and second column.\n The second move swaps the second and third row.\n Example 2:\n Input: board = [[0,1],[1,0]]\n Output: 0\n Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.\n Example 3:\n Input: board = [[1,0],[1,0]]\n Output: -1\n Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 783, - "title": "Minimum Distance Between BST Nodes", - "question": "class Solution:\n def minDiffInBST(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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:\n Input: root = [4,2,6,1,3]\n Output: 1\n Example 2:\n Input: root = [1,0,48,null,null,12,49]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 784, - "title": "Letter Case Permutation", - "question": "class Solution:\n def letterCasePermutation(self, s: str) -> List[str]:\n \"\"\"\n Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.\n Return a list of all possible strings we could create. Return the output in any order.\n Example 1:\n Input: s = \"a1b2\"\n Output: [\"a1b2\",\"a1B2\",\"A1b2\",\"A1B2\"]\n Example 2:\n Input: s = \"3z4\"\n Output: [\"3z4\",\"3Z4\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 785, - "title": "Is Graph Bipartite?", - "question": "class Solution:\n def isBipartite(self, graph: List[List[int]]) -> bool:\n \"\"\"\n 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:\n There are no self-edges (graph[u] does not contain u).\n There are no parallel edges (graph[u] does not contain duplicate values).\n If v is in graph[u], then u is in graph[v] (the graph is undirected).\n The graph may not be connected, meaning there may be two nodes u and v such that there is no path between them.\n A 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.\n Return true if and only if it is bipartite.\n Example 1:\n Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]\n Output: false\n Explanation: There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.\n Example 2:\n Input: graph = [[1,3],[0,2],[1,3],[0,2]]\n Output: true\n Explanation: We can partition the nodes into two sets: {0, 2} and {1, 3}.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 786, - "title": "K-th Smallest Prime Fraction", - "question": "class Solution:\n def kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]:\n \"\"\"\n You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.\n For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].\n Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].\n Example 1:\n Input: arr = [1,2,3,5], k = 3\n Output: [2,5]\n Explanation: The fractions to be considered in sorted order are:\n 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.\n The third fraction is 2/5.\n Example 2:\n Input: arr = [1,7], k = 1\n Output: [1,7]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 787, - "title": "Cheapest Flights Within K Stops", - "question": "class Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:\n \"\"\"\n 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.\n You 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:\n Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1\n Output: 700\n Explanation:\n The graph is shown above.\n The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.\n Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.\n Example 2:\n Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1\n Output: 200\n Explanation:\n The graph is shown above.\n The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.\n Example 3:\n Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0\n Output: 500\n Explanation:\n The graph is shown above.\n The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 788, - "title": "Rotated Digits", - "question": "class Solution:\n def rotatedDigits(self, n: int) -> int:\n \"\"\"\n 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.\n A number is valid if each digit remains a digit after rotation. For example:\n 0, 1, and 8 rotate to themselves,\n 2 and 5 rotate to each other (in this case they are rotated in a different direction, in other words, 2 or 5 gets mirrored),\n 6 and 9 rotate to each other, and\n the rest of the numbers do not rotate to any other number and become invalid.\n Given an integer n, return the number of good integers in the range [1, n].\n Example 1:\n Input: n = 10\n Output: 4\n Explanation: There are four good numbers in the range [1, 10] : 2, 5, 6, 9.\n Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.\n Example 2:\n Input: n = 1\n Output: 0\n Example 3:\n Input: n = 2\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 789, - "title": "Escape The Ghosts", - "question": "class Solution:\n def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:\n \"\"\"\n 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.\n Each 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.\n You 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.\n Return true if it is possible to escape regardless of how the ghosts move, otherwise return false.\n Example 1:\n Input: ghosts = [[1,0],[0,3]], target = [0,1]\n Output: true\n Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.\n Example 2:\n Input: ghosts = [[1,0]], target = [2,0]\n Output: false\n Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.\n Example 3:\n Input: ghosts = [[2,0]], target = [1,0]\n Output: false\n Explanation: The ghost can reach the target at the same time as you.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 790, - "title": "Domino and Tromino Tiling", - "question": "class Solution:\n def numTilings(self, n: int) -> int:\n \"\"\"\n You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.\n Given 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.\n In 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:\n Input: n = 3\n Output: 5\n Explanation: The five different ways are show above.\n Example 2:\n Input: n = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 791, - "title": "Custom Sort String", - "question": "class Solution:\n def customSortString(self, order: str, s: str) -> str:\n \"\"\"\n You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.\n Permute 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.\n Return any permutation of s that satisfies this property.\n Example 1:\n Input: order = \"cba\", s = \"abcd\"\n Output: \"cbad\"\n Explanation: \n \"a\", \"b\", \"c\" appear in order, so the order of \"a\", \"b\", \"c\" should be \"c\", \"b\", and \"a\". \n Since \"d\" does not appear in order, it can be at any position in the returned string. \"dcba\", \"cdba\", \"cbda\" are also valid outputs.\n Example 2:\n Input: order = \"cbafg\", s = \"abcd\"\n Output: \"cbad\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 792, - "title": "Number of Matching Subsequences", - "question": "class Solution:\n def numMatchingSubseq(self, s: str, words: List[str]) -> int:\n \"\"\"\n Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.\n A 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 For example, \"ace\" is a subsequence of \"abcde\".\n Example 1:\n Input: s = \"abcde\", words = [\"a\",\"bb\",\"acd\",\"ace\"]\n Output: 3\n Explanation: There are three strings in words that are a subsequence of s: \"a\", \"acd\", \"ace\".\n Example 2:\n Input: s = \"dsahjpjauf\", words = [\"ahjpjau\",\"ja\",\"ahbwzgqnuk\",\"tnmlanowax\"]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 793, - "title": "Preimage Size of Factorial Zeroes Function", - "question": "class Solution:\n def preimageSizeFZF(self, k: int) -> int:\n \"\"\"\n Let f(x) be the number of zeroes at the end of x!. Recall that x! = 1 * 2 * 3 * ... * x and by convention, 0! = 1.\n For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has two zeroes at the end.\n Given an integer k, return the number of non-negative integers x have the property that f(x) = k.\n Example 1:\n Input: k = 0\n Output: 5\n Explanation: 0!, 1!, 2!, 3!, and 4! end with k = 0 zeroes.\n Example 2:\n Input: k = 5\n Output: 0\n Explanation: There is no x such that x! ends in k = 5 zeroes.\n Example 3:\n Input: k = 3\n Output: 5\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 794, - "title": "Valid Tic-Tac-Toe State", - "question": "class Solution:\n def validTicTacToe(self, board: List[str]) -> bool:\n \"\"\"\n 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.\n The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.\n Here are the rules of Tic-Tac-Toe:\n Players take turns placing characters into empty squares ' '.\n The first player always places 'X' characters, while the second player always places 'O' characters.\n 'X' and 'O' characters are always placed into empty squares, never filled ones.\n The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\n The game also ends if all squares are non-empty.\n No more moves can be played if the game is over.\n Example 1:\n Input: board = [\"O \",\" \",\" \"]\n Output: false\n Explanation: The first player always plays \"X\".\n Example 2:\n Input: board = [\"XOX\",\" X \",\" \"]\n Output: false\n Explanation: Players take turns making moves.\n Example 3:\n Input: board = [\"XOX\",\"O O\",\"XOX\"]\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 795, - "title": "Number of Subarrays with Bounded Maximum", - "question": "class Solution:\n def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:\n \"\"\"\n 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].\n The test cases are generated so that the answer will fit in a 32-bit integer.\n Example 1:\n Input: nums = [2,1,4,3], left = 2, right = 3\n Output: 3\n Explanation: There are three subarrays that meet the requirements: [2], [2, 1], [3].\n Example 2:\n Input: nums = [2,9,2,5,6], left = 2, right = 8\n Output: 7\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 796, - "title": "Rotate String", - "question": "class Solution:\n def rotateString(self, s: str, goal: str) -> bool:\n \"\"\"\n Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.\n A shift on s consists of moving the leftmost character of s to the rightmost position.\n For example, if s = \"abcde\", then it will be \"bcdea\" after one shift.\n Example 1:\n Input: s = \"abcde\", goal = \"cdeab\"\n Output: true\n Example 2:\n Input: s = \"abcde\", goal = \"abced\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 797, - "title": "All Paths From Source to Target", - "question": "class Solution:\n def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n The 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:\n Input: graph = [[1,2],[3],[3],[]]\n Output: [[0,1,3],[0,2,3]]\n Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.\n Example 2:\n Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]\n Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 798, - "title": "Smallest Rotation with Highest Score", - "question": "class Solution:\n def bestRotation(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n For 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].\n Return 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:\n Input: nums = [2,3,1,4,0]\n Output: 3\n Explanation: Scores for each k are listed below: \n k = 0, nums = [2,3,1,4,0], score 2\n k = 1, nums = [3,1,4,0,2], score 3\n k = 2, nums = [1,4,0,2,3], score 3\n k = 3, nums = [4,0,2,3,1], score 4\n k = 4, nums = [0,2,3,1,4], score 3\n So we should choose k = 3, which has the highest score.\n Example 2:\n Input: nums = [1,3,0,2,4]\n Output: 0\n Explanation: nums will always have 3 points no matter how it shifts.\n So we will choose the smallest k, which is 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 799, - "title": "Champagne Tower", - "question": "class Solution:\n def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:\n \"\"\"\n 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.\r\n Then, 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.)\r\n For 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.\r\n Now 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.)\r\n Example 1:\r\n Input: poured = 1, query_row = 1, query_glass = 1\r\n Output: 0.00000\r\n Explanation: 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.\r\n Example 2:\r\n Input: poured = 2, query_row = 1, query_glass = 1\r\n Output: 0.50000\r\n Explanation: 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.\r\n Example 3:\r\n Input: poured = 100000009, query_row = 33, query_glass = 17\r\n Output: 1.00000\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 705, - "title": "Design HashSet", - "question": "class MyHashSet:\n def __init__(self):\n def add(self, key: int) -> None:\n def remove(self, key: int) -> None:\n def contains(self, key: int) -> bool:\n \"\"\"\n Design a HashSet without using any built-in hash table libraries.\n Implement MyHashSet class:\n void add(key) Inserts the value key into the HashSet.\n bool contains(key) Returns whether the value key exists in the HashSet or not.\n void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.\n Example 1:\n Input\n [\"MyHashSet\", \"add\", \"add\", \"contains\", \"contains\", \"add\", \"contains\", \"remove\", \"contains\"]\n [[], [1], [2], [1], [3], [2], [2], [2], [2]]\n Output\n [null, null, null, true, false, null, true, null, false]\n Explanation\n MyHashSet myHashSet = new MyHashSet();\n myHashSet.add(1); // set = [1]\n myHashSet.add(2); // set = [1, 2]\n myHashSet.contains(1); // return True\n myHashSet.contains(3); // return False, (not found)\n myHashSet.add(2); // set = [1, 2]\n myHashSet.contains(2); // return True\n myHashSet.remove(2); // set = [1]\n myHashSet.contains(2); // return False, (already removed)\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 706, - "title": "Design HashMap", - "question": "class MyHashMap:\n def __init__(self):\n def put(self, key: int, value: int) -> None:\n def get(self, key: int) -> int:\n def remove(self, key: int) -> None:\n \"\"\"\n Design a HashMap without using any built-in hash table libraries.\n Implement the MyHashMap class:\n MyHashMap() initializes the object with an empty map.\n void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.\n int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.\n void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.\n Example 1:\n Input\n [\"MyHashMap\", \"put\", \"put\", \"get\", \"get\", \"put\", \"get\", \"remove\", \"get\"]\n [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]\n Output\n [null, null, null, 1, -1, null, 1, null, -1]\n Explanation\n MyHashMap myHashMap = new MyHashMap();\n myHashMap.put(1, 1); // The map is now [[1,1]]\n myHashMap.put(2, 2); // The map is now [[1,1], [2,2]]\n myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]]\n myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]]\n myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value)\n myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]]\n myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]]\n myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 801, - "title": "Minimum Swaps To Make Sequences Increasing", - "question": "class Solution:\n def minSwap(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n 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].\n For 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].\n Return 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.\n An array arr is strictly increasing if and only if arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1].\n Example 1:\n Input: nums1 = [1,3,5,4], nums2 = [1,2,3,7]\n Output: 1\n Explanation: \n Swap nums1[3] and nums2[3]. Then the sequences are:\n nums1 = [1, 3, 5, 7] and nums2 = [1, 2, 3, 4]\n which are both strictly increasing.\n Example 2:\n Input: nums1 = [0,3,5,8,9], nums2 = [2,1,4,6,9]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 802, - "title": "Find Eventual Safe States", - "question": "class Solution:\n def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:\n \"\"\"\n 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].\n A 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).\n Return an array containing all the safe nodes of the graph. The answer should be sorted in ascending order.\n Example 1:\n Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]]\n Output: [2,4,5,6]\n Explanation: The given graph is shown above.\n Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.\n Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.\n Example 2:\n Input: graph = [[1,2,3,4],[1,2],[3,4],[0,4],[]]\n Output: [4]\n Explanation:\n Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 803, - "title": "Bricks Falling When Hit", - "question": "class Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an m x n binary grid, where each 1 represents a brick and 0 represents an empty space. A brick is stable if:\n It is directly connected to the top of the grid, or\n At least one other brick in its four adjacent cells is stable.\n You are also given an array hits, which is a sequence of erasures we want to apply. Each time we want to erase the brick at the location hits[i] = (rowi, coli). The brick on that location (if it exists) will disappear. Some other bricks may no longer be stable because of that erasure and will fall. Once a brick falls, it is immediately erased from the grid (i.e., it does not land on other stable bricks).\n Return an array result, where each result[i] is the number of bricks that will fall after the ith erasure is applied.\n Note that an erasure may refer to a location with no brick, and if it does, no bricks drop.\n Example 1:\n Input: grid = [[1,0,0,0],[1,1,1,0]], hits = [[1,0]]\n Output: [2]\n Explanation: Starting with the grid:\n [[1,0,0,0],\n [1,1,1,0]]\n We erase the underlined brick at (1,0), resulting in the grid:\n [[1,0,0,0],\n [0,1,1,0]]\n The two underlined bricks are no longer stable as they are no longer connected to the top nor adjacent to another stable brick, so they will fall. The resulting grid is:\n [[1,0,0,0],\n [0,0,0,0]]\n Hence the result is [2].\n Example 2:\n Input: grid = [[1,0,0,0],[1,1,0,0]], hits = [[1,1],[1,0]]\n Output: [0,0]\n Explanation: Starting with the grid:\n [[1,0,0,0],\n [1,1,0,0]]\n We erase the underlined brick at (1,1), resulting in the grid:\n [[1,0,0,0],\n [1,0,0,0]]\n All remaining bricks are still stable, so no bricks fall. The grid remains the same:\n [[1,0,0,0],\n [1,0,0,0]]\n Next, we erase the underlined brick at (1,0), resulting in the grid:\n [[1,0,0,0],\n [0,0,0,0]]\n Once again, all remaining bricks are still stable, so no bricks fall.\n Hence the result is [0,0].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 804, - "title": "Unique Morse Code Words", - "question": "class Solution:\n def uniqueMorseRepresentations(self, words: List[str]) -> int:\n \"\"\"\n 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.\n For convenience, the full table for the 26 letters of the English alphabet is given below:\n [\".-\",\"-...\",\"-.-.\",\"-..\",\".\",\"..-.\",\"--.\",\"....\",\"..\",\".---\",\"-.-\",\".-..\",\"--\",\"-.\",\"---\",\".--.\",\"--.-\",\".-.\",\"...\",\"-\",\"..-\",\"...-\",\".--\",\"-..-\",\"-.--\",\"--..\"]\n Given an array of strings words where each word can be written as a concatenation of the Morse code of each letter.\n For example, \"cab\" can be written as \"-.-..--...\", which is the concatenation of \"-.-.\", \".-\", and \"-...\". We will call such a concatenation the transformation of a word.\n Return the number of different transformations among all words we have.\n Example 1:\n Input: words = [\"gin\",\"zen\",\"gig\",\"msg\"]\n Output: 2\n Explanation: The transformation of each word is:\n \"gin\" -> \"--...-.\"\n \"zen\" -> \"--...-.\"\n \"gig\" -> \"--...--.\"\n \"msg\" -> \"--...--.\"\n There are 2 different transformations: \"--...-.\" and \"--...--.\".\n Example 2:\n Input: words = [\"a\"]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 805, - "title": "Split Array With Same Average", - "question": "class Solution:\n def splitArraySameAverage(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an integer array nums.\n You should move each element of nums into one of the two arrays A and B such that A and B are non-empty, and average(A) == average(B).\n Return true if it is possible to achieve that and false otherwise.\n Note that for an array arr, average(arr) is the sum of all the elements of arr over the length of arr.\n Example 1:\n Input: nums = [1,2,3,4,5,6,7,8]\n Output: true\n Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.\n Example 2:\n Input: nums = [3,1]\n Output: false\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 806, - "title": "Number of Lines To Write String", - "question": "class Solution:\n def numberOfLines(self, widths: List[int], s: str) -> List[int]:\n \"\"\"\n 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.\n You 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.\n Return an array result of length 2 where:\n result[0] is the total number of lines.\n result[1] is the width of the last line in pixels.\n Example 1:\n Input: 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\"\n Output: [3,60]\n Explanation: You can write s as follows:\n abcdefghij // 100 pixels wide\n klmnopqrst // 100 pixels wide\n uvwxyz // 60 pixels wide\n There are a total of 3 lines, and the last line is 60 pixels wide.\n Example 2:\n Input: 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\"\n Output: [2,4]\n Explanation: You can write s as follows:\n bbbcccdddaa // 98 pixels wide\n a // 4 pixels wide\n There are a total of 2 lines, and the last line is 4 pixels wide.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 807, - "title": "Max Increase to Keep City Skyline", - "question": "class Solution:\n def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n A city's skyline is the 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.\n We 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.\n Return 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:\n Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]\n Output: 35\n Explanation: The building heights are shown in the center of the above image.\n The skylines when viewed from each cardinal direction are drawn in red.\n The grid after increasing the height of buildings without affecting skylines is:\n gridNew = [ [8, 4, 8, 7],\n [7, 4, 7, 7],\n [9, 4, 8, 7],\n [3, 3, 3, 3] ]\n Example 2:\n Input: grid = [[0,0,0],[0,0,0],[0,0,0]]\n Output: 0\n Explanation: Increasing the height of any building will result in the skyline changing.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 808, - "title": "Soup Servings", - "question": "class Solution:\n def soupServings(self, n: int) -> float:\n \"\"\"\n 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:\n Serve 100 ml of soup A and 0 ml of soup B,\n Serve 75 ml of soup A and 25 ml of soup B,\n Serve 50 ml of soup A and 50 ml of soup B, and\n Serve 25 ml of soup A and 75 ml of soup B.\n When 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.\n Note that we do not have an operation where all 100 ml's of soup B are used first.\n Return 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:\n Input: n = 50\n Output: 0.62500\n Explanation: If we choose the first two operations, A will become empty first.\n For the third operation, A and B will become empty at the same time.\n For the fourth operation, B will become empty first.\n So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.\n Example 2:\n Input: n = 100\n Output: 0.71875\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 809, - "title": "Expressive Words", - "question": "class Solution:\n def expressiveWords(self, s: str, words: List[str]) -> int:\n \"\"\"\n Sometimes people repeat letters to represent extra feeling. For example:\n \"hello\" -> \"heeellooo\"\n \"hi\" -> \"hiiii\"\n In these strings like \"heeellooo\", we have groups of adjacent letters that are all the same: \"h\", \"eee\", \"ll\", \"ooo\".\n You 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.\n For 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.\n Return the number of query strings that are stretchy.\n Example 1:\n Input: s = \"heeellooo\", words = [\"hello\", \"hi\", \"helo\"]\n Output: 1\n Explanation: \n We can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\n We can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not size 3 or more.\n Example 2:\n Input: s = \"zzzzzyyyyy\", words = [\"zzyy\",\"zy\",\"zyy\"]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 810, - "title": "Chalkboard XOR Game", - "question": "class Solution:\n def xorGame(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an array of integers nums represents the numbers written on a chalkboard.\n Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become 0, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is 0.\n Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to 0, then that player wins.\n Return true if and only if Alice wins the game, assuming both players play optimally.\n Example 1:\n Input: nums = [1,1,2]\n Output: false\n Explanation: \n Alice has two choices: erase 1 or erase 2. \n If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. \n If Alice erases 2 first, now nums become [1, 1]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose.\n Example 2:\n Input: nums = [0,1]\n Output: true\n Example 3:\n Input: nums = [1,2,3]\n Output: true\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 811, - "title": "Subdomain Visit Count", - "question": "class Solution:\n def subdomainVisits(self, cpdomains: List[str]) -> List[str]:\n \"\"\"\n 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.\n A 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.\n For example, \"9001 discuss.leetcode.com\" is a count-paired domain that indicates that discuss.leetcode.com was visited 9001 times.\n Given 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:\n Input: cpdomains = [\"9001 discuss.leetcode.com\"]\n Output: [\"9001 leetcode.com\",\"9001 discuss.leetcode.com\",\"9001 com\"]\n Explanation: We only have one website domain: \"discuss.leetcode.com\".\n As discussed above, the subdomain \"leetcode.com\" and \"com\" will also be visited. So they will all be visited 9001 times.\n Example 2:\n Input: cpdomains = [\"900 google.mail.com\", \"50 yahoo.com\", \"1 intel.mail.com\", \"5 wiki.org\"]\n Output: [\"901 mail.com\",\"50 yahoo.com\",\"900 google.mail.com\",\"5 wiki.org\",\"5 org\",\"1 intel.mail.com\",\"951 com\"]\n Explanation: We will visit \"google.mail.com\" 900 times, \"yahoo.com\" 50 times, \"intel.mail.com\" once and \"wiki.org\" 5 times.\n For the subdomains, we will visit \"mail.com\" 900 + 1 = 901 times, \"com\" 900 + 50 + 1 = 951 times, and \"org\" 5 times.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 812, - "title": "Largest Triangle Area", - "question": "class Solution:\n def largestTriangleArea(self, points: List[List[int]]) -> float:\n \"\"\"\n 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:\n Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]\n Output: 2.00000\n Explanation: The five points are shown in the above figure. The red triangle is the largest.\n Example 2:\n Input: points = [[1,0],[0,0],[0,1]]\n Output: 0.50000\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 813, - "title": "Largest Sum of Averages", - "question": "class Solution:\n def largestSumOfAverages(self, nums: List[int], k: int) -> float:\n \"\"\"\n 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.\n Note that the partition must use every integer in nums, and that the score is not necessarily an integer.\n Return 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:\n Input: nums = [9,1,2,3,9], k = 3\n Output: 20.00000\n Explanation: \n The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.\n We could have also partitioned nums into [9, 1], [2], [3, 9], for example.\n That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.\n Example 2:\n Input: nums = [1,2,3,4,5,6,7], k = 4\n Output: 20.50000\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 814, - "title": "Binary Tree Pruning", - "question": "class Solution:\n def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \"\"\"\n 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.\n A subtree of a node node is node plus every node that is a descendant of node.\n Example 1:\n Input: root = [1,null,0,0,1]\n Output: [1,null,0,null,1]\n Explanation: \n Only the red nodes satisfy the property \"every subtree not containing a 1\".\n The diagram on the right represents the answer.\n Example 2:\n Input: root = [1,0,1,0,0,0,1]\n Output: [1,null,1,null,1]\n Example 3:\n Input: root = [1,1,0,1,1,0,1,0]\n Output: [1,1,0,1,1,null,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 815, - "title": "Bus Routes", - "question": "class Solution:\n def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:\n \"\"\"\n You are given an array routes representing bus routes where routes[i] is a bus route that the ith bus repeats forever.\n For example, if routes[0] = [1, 5, 7], this means that the 0th bus travels in the sequence 1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ... forever.\n You will start at the bus stop source (You are not on any bus initially), and you want to go to the bus stop target. You can travel between bus stops by buses only.\n Return the least number of buses you must take to travel from source to target. Return -1 if it is not possible.\n Example 1:\n Input: routes = [[1,2,7],[3,6,7]], source = 1, target = 6\n Output: 2\n Explanation: The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.\n Example 2:\n Input: routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12\n Output: -1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 816, - "title": "Ambiguous Coordinates", - "question": "class Solution:\n def ambiguousCoordinates(self, s: str) -> List[str]:\n \"\"\"\n 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.\n For example, \"(1, 3)\" becomes s = \"(13)\" and \"(2, 0.5)\" becomes s = \"(205)\".\n Return a list of strings representing all possibilities for what our original coordinates could have been.\n Our 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\".\n The 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:\n Input: s = \"(123)\"\n Output: [\"(1, 2.3)\",\"(1, 23)\",\"(1.2, 3)\",\"(12, 3)\"]\n Example 2:\n Input: s = \"(0123)\"\n Output: [\"(0, 1.23)\",\"(0, 12.3)\",\"(0, 123)\",\"(0.1, 2.3)\",\"(0.1, 23)\",\"(0.12, 3)\"]\n Explanation: 0.0, 00, 0001 or 00.01 are not allowed.\n Example 3:\n Input: s = \"(00011)\"\n Output: [\"(0, 0.011)\",\"(0.001, 1)\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 817, - "title": "Linked List Components", - "question": "class Solution:\n def numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:\n \"\"\"\n 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.\n Return the number of connected components in nums where two values are connected if they appear consecutively in the linked list.\n Example 1:\n Input: head = [0,1,2,3], nums = [0,1,3]\n Output: 2\n Explanation: 0 and 1 are connected, so [0, 1] and [3] are the two connected components.\n Example 2:\n Input: head = [0,1,2,3,4], nums = [0,3,1,4]\n Output: 2\n Explanation: 0 and 1 are connected, 3 and 4 are connected, so [0, 1] and [3, 4] are the two connected components.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 818, - "title": "Race Car", - "question": "class Solution:\n def racecar(self, target: int) -> int:\n \"\"\"\n 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):\n When you get an instruction 'A', your car does the following:\n position += speed\n speed *= 2\n When you get an instruction 'R', your car does the following:\n If your speed is positive then speed = -1\n otherwise speed = 1\n Your position stays the same.\n For example, after commands \"AAR\", your car goes to positions 0 --> 1 --> 3 --> 3, and your speed goes to 1 --> 2 --> 4 --> -1.\n Given a target position target, return the length of the shortest sequence of instructions to get there.\n Example 1:\n Input: target = 3\n Output: 2\n Explanation: \n The shortest instruction sequence is \"AA\".\n Your position goes from 0 --> 1 --> 3.\n Example 2:\n Input: target = 6\n Output: 5\n Explanation: \n The shortest instruction sequence is \"AAARA\".\n Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 819, - "title": "Most Common Word", - "question": "class Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n \"\"\"\n 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.\n The words in paragraph are case-insensitive and the answer should be returned in lowercase.\n Example 1:\n Input: paragraph = \"Bob hit a ball, the hit BALL flew far after it was hit.\", banned = [\"hit\"]\n Output: \"ball\"\n Explanation: \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. \n Note that words in the paragraph are not case sensitive,\n that punctuation is ignored (even if adjacent to words, such as \"ball,\"), \n and that \"hit\" isn't the answer even though it occurs more because it is banned.\n Example 2:\n Input: paragraph = \"a.\", banned = []\n Output: \"a\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 707, - "title": "Design Linked List", - "question": "class MyLinkedList:\n def __init__(self):\n def get(self, index: int) -> int:\n def addAtHead(self, val: int) -> None:\n def addAtTail(self, val: int) -> None:\n def addAtIndex(self, index: int, val: int) -> None:\n def deleteAtIndex(self, index: int) -> None:\n \"\"\"\n Design your implementation of the linked list. You can choose to use a singly or doubly linked list.\n A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.\n If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.\n Implement the MyLinkedList class:\n MyLinkedList() Initializes the MyLinkedList object.\n int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.\n void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.\n void addAtTail(int val) Append a node of value val as the last element of the linked list.\n void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.\n void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.\n Example 1:\n Input\n [\"MyLinkedList\", \"addAtHead\", \"addAtTail\", \"addAtIndex\", \"get\", \"deleteAtIndex\", \"get\"]\n [[], [1], [3], [1, 2], [1], [1], [1]]\n Output\n [null, null, null, null, 2, null, 3]\n Explanation\n MyLinkedList myLinkedList = new MyLinkedList();\n myLinkedList.addAtHead(1);\n myLinkedList.addAtTail(3);\n myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3\n myLinkedList.get(1); // return 2\n myLinkedList.deleteAtIndex(1); // now the linked list is 1->3\n myLinkedList.get(1); // return 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 820, - "title": "Short Encoding of Words", - "question": "class Solution:\n def minimumLengthEncoding(self, words: List[str]) -> int:\n \"\"\"\n A valid encoding of an array of words is any reference string s and array of indices indices such that:\n words.length == indices.length\n The reference string s ends with the '#' character.\n For 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].\n Given an array of words, return the length of the shortest reference string s possible of any valid encoding of words.\n Example 1:\n Input: words = [\"time\", \"me\", \"bell\"]\n Output: 10\n Explanation: A valid encoding would be s = \"time#bell#\" and indices = [0, 2, 5].\n words[0] = \"time\", the substring of s starting from indices[0] = 0 to the next '#' is underlined in \"time#bell#\"\n words[1] = \"me\", the substring of s starting from indices[1] = 2 to the next '#' is underlined in \"time#bell#\"\n words[2] = \"bell\", the substring of s starting from indices[2] = 5 to the next '#' is underlined in \"time#bell#\"\n Example 2:\n Input: words = [\"t\"]\n Output: 2\n Explanation: A valid encoding would be s = \"t#\" and indices = [0].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 821, - "title": "Shortest Distance to a Character", - "question": "class Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n \"\"\"\n 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.\n The distance between two indices i and j is abs(i - j), where abs is the absolute value function.\n Example 1:\n Input: s = \"loveleetcode\", c = \"e\"\n Output: [3,2,1,0,1,0,0,1,2,2,1,0]\n Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).\n The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.\n The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.\n For 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.\n The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.\n Example 2:\n Input: s = \"aaab\", c = \"b\"\n Output: [3,2,1,0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 822, - "title": "Card Flipping Game", - "question": "class Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n \"\"\"\n 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).\n After flipping the cards, an integer is considered good if it is facing down on some card and not facing up on any card.\n Return the minimum possible good integer after flipping the cards. If there are no good integers, return 0.\n Example 1:\n Input: fronts = [1,2,4,4,7], backs = [1,3,4,1,3]\n Output: 2\n Explanation:\n If 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].\n 2 is the minimum good integer as it appears facing down but not facing up.\n It can be shown that 2 is the minimum possible good integer obtainable after flipping some cards.\n Example 2:\n Input: fronts = [1], backs = [1]\n Output: 0\n Explanation:\n There are no good integers no matter how we flip the cards, so we return 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 823, - "title": "Binary Trees With Factors", - "question": "class Solution:\n def numFactoredBinaryTrees(self, arr: List[int]) -> int:\n \"\"\"\n Given an array of unique integers, arr, where each integer arr[i] is strictly greater than 1.\n We 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.\n Return the number of binary trees we can make. The answer may be too large so return the answer modulo 109 + 7.\n Example 1:\n Input: arr = [2,4]\n Output: 3\n Explanation: We can make these trees: [2], [4], [4, 2, 2]\n Example 2:\n Input: arr = [2,4,5,10]\n Output: 7\n Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 824, - "title": "Goat Latin", - "question": "class Solution:\n def toGoatLatin(self, sentence: str) -> str:\n \"\"\"\n You are given a string sentence that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only.\n We 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:\n If a word begins with a vowel ('a', 'e', 'i', 'o', or 'u'), append \"ma\" to the end of the word.\n For example, the word \"apple\" becomes \"applema\".\n If a word begins with a consonant (i.e., not a vowel), remove the first letter and append it to the end, then add \"ma\".\n For example, the word \"goat\" becomes \"oatgma\".\n Add one letter 'a' to the end of each word per its word index in the sentence, starting with 1.\n For example, the first word gets \"a\" added to the end, the second word gets \"aa\" added to the end, and so on.\n Return the final sentence representing the conversion from sentence to Goat Latin.\n Example 1:\n Input: sentence = \"I speak Goat Latin\"\n Output: \"Imaa peaksmaaa oatGmaaaa atinLmaaaaa\"\n Example 2:\n Input: sentence = \"The quick brown fox jumped over the lazy dog\"\n Output: \"heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 825, - "title": "Friends Of Appropriate Ages", - "question": "class Solution:\n def numFriendRequests(self, ages: List[int]) -> int:\n \"\"\"\n 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.\n A Person x will not send a friend request to a person y (x != y) if any of the following conditions is true:\n age[y] <= 0.5 * age[x] + 7\n age[y] > age[x]\n age[y] > 100 && age[x] < 100\n Otherwise, x will send a friend request to y.\n Note 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.\n Return the total number of friend requests made.\n Example 1:\n Input: ages = [16,16]\n Output: 2\n Explanation: 2 people friend request each other.\n Example 2:\n Input: ages = [16,17,18]\n Output: 2\n Explanation: Friend requests are made 17 -> 16, 18 -> 17.\n Example 3:\n Input: ages = [20,30,100,110,120]\n Output: 3\n Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 826, - "title": "Most Profit Assigning Work", - "question": "class Solution:\n def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:\n \"\"\"\n You have n jobs and m workers. You are given three arrays: difficulty, profit, and worker where:\n difficulty[i] and profit[i] are the difficulty and the profit of the ith job, and\n worker[j] is the ability of jth worker (i.e., the jth worker can only complete a job with difficulty at most worker[j]).\n Every worker can be assigned at most one job, but one job can be completed multiple times.\n For 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.\n Return the maximum profit we can achieve after assigning the workers to the jobs.\n Example 1:\n Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]\n Output: 100\n Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get a profit of [20,20,30,30] separately.\n Example 2:\n Input: difficulty = [85,47,57], profit = [24,66,99], worker = [40,25,25]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 827, - "title": "Making A Large Island", - "question": "class Solution:\n def largestIsland(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an n x n binary matrix grid. You are allowed to change at most one 0 to be 1.\r\n Return the size of the largest island in grid after applying this operation.\r\n An island is a 4-directionally connected group of 1s.\r\n Example 1:\r\n Input: grid = [[1,0],[0,1]]\r\n Output: 3\r\n Explanation: Change one 0 to 1 and connect two 1s, then we get an island with area = 3.\r\n Example 2:\r\n Input: grid = [[1,1],[1,0]]\r\n Output: 4\r\n Explanation: Change the 0 to 1 and make the island bigger, only one island with area = 4.\r\n Example 3:\r\n Input: grid = [[1,1],[1,1]]\r\n Output: 4\r\n Explanation: Can't change any 0 to 1, only one island with area = 4.\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 828, - "title": "Count Unique Characters of All Substrings of a Given String", - "question": "class Solution:\n def uniqueLetterString(self, s: str) -> int:\n \"\"\"\n Let's define a function countUniqueChars(s) that returns the number of unique characters on s.\n For 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.\n Given 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.\n Notice that some substrings can be repeated so in this case you have to count the repeated ones too.\n Example 1:\n Input: s = \"ABC\"\n Output: 10\n Explanation: All possible substrings are: \"A\",\"B\",\"C\",\"AB\",\"BC\" and \"ABC\".\n Every substring is composed with only unique letters.\n Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10\n Example 2:\n Input: s = \"ABA\"\n Output: 8\n Explanation: The same as example 1, except countUniqueChars(\"ABA\") = 1.\n Example 3:\n Input: s = \"LEETCODE\"\n Output: 92\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 829, - "title": "Consecutive Numbers Sum", - "question": "class Solution:\n def consecutiveNumbersSum(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the number of ways you can write n as the sum of consecutive positive integers.\n Example 1:\n Input: n = 5\n Output: 2\n Explanation: 5 = 2 + 3\n Example 2:\n Input: n = 9\n Output: 3\n Explanation: 9 = 4 + 5 = 2 + 3 + 4\n Example 3:\n Input: n = 15\n Output: 4\n Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 830, - "title": "Positions of Large Groups", - "question": "class Solution:\n def largeGroupPositions(self, s: str) -> List[List[int]]:\n \"\"\"\n In a string s of lowercase letters, these letters form consecutive groups of the same character.\n For example, a string like s = \"abbxxxxzyy\" has the groups \"a\", \"bb\", \"xxxx\", \"z\", and \"yy\".\n A 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].\n A group is considered large if it has 3 or more characters.\n Return the intervals of every large group sorted in increasing order by start index.\n Example 1:\n Input: s = \"abbxxxxzzy\"\n Output: [[3,6]]\n Explanation: \"xxxx\" is the only large group with start index 3 and end index 6.\n Example 2:\n Input: s = \"abc\"\n Output: []\n Explanation: We have groups \"a\", \"b\", and \"c\", none of which are large groups.\n Example 3:\n Input: s = \"abcdddeeeeaabbbcd\"\n Output: [[3,5],[6,9],[12,14]]\n Explanation: The large groups are \"ddd\", \"eeee\", and \"bbb\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 831, - "title": "Masking Personal Information", - "question": "class Solution:\n def maskPII(self, s: str) -> str:\n \"\"\"\n 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.\n Email address:\n An email address is:\n A name consisting of uppercase and lowercase English letters, followed by\n The '@' symbol, followed by\n The domain consisting of uppercase and lowercase English letters with a dot '.' somewhere in the middle (not the first or last character).\n To mask an email:\n The uppercase letters in the name and domain must be converted to lowercase letters.\n The middle letters of the name (i.e., all but the first and last letters) must be replaced by 5 asterisks \"*****\".\n Phone number:\n A phone number is formatted as follows:\n The phone number contains 10-13 digits.\n The last 10 digits make up the local number.\n The remaining 0-3 digits, in the beginning, make up the country code.\n Separation characters from the set {'+', '-', '(', ')', ' '} separate the above digits in some way.\n To mask a phone number:\n Remove all separation characters.\n The 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:\n Input: s = \"LeetCode@LeetCode.com\"\n Output: \"l*****e@leetcode.com\"\n Explanation: s is an email address.\n The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\n Example 2:\n Input: s = \"AB@qq.com\"\n Output: \"a*****b@qq.com\"\n Explanation: s is an email address.\n The name and domain are converted to lowercase, and the middle of the name is replaced by 5 asterisks.\n Note that even though \"ab\" is 2 characters, it still must have 5 asterisks in the middle.\n Example 3:\n Input: s = \"1(234)567-890\"\n Output: \"***-***-7890\"\n Explanation: s is a phone number.\n There are 10 digits, so the local number is 10 digits and the country code is 0 digits.\n Thus, the resulting masked number is \"***-***-7890\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 641, - "title": "Design Circular Deque", - "question": "class MyCircularDeque:\n def __init__(self, k: int):\n def insertFront(self, value: int) -> bool:\n def insertLast(self, value: int) -> bool:\n def deleteFront(self) -> bool:\n def deleteLast(self) -> bool:\n def getFront(self) -> int:\n def getRear(self) -> int:\n def isEmpty(self) -> bool:\n def isFull(self) -> bool:\n \"\"\"\n Design your implementation of the circular double-ended queue (deque).\n Implement the MyCircularDeque class:\n MyCircularDeque(int k) Initializes the deque with a maximum size of k.\n boolean insertFront() Adds an item at the front of Deque. Returns true if the operation is successful, or false otherwise.\n boolean insertLast() Adds an item at the rear of Deque. Returns true if the operation is successful, or false otherwise.\n boolean deleteFront() Deletes an item from the front of Deque. Returns true if the operation is successful, or false otherwise.\n boolean deleteLast() Deletes an item from the rear of Deque. Returns true if the operation is successful, or false otherwise.\n int getFront() Returns the front item from the Deque. Returns -1 if the deque is empty.\n int getRear() Returns the last item from Deque. Returns -1 if the deque is empty.\n boolean isEmpty() Returns true if the deque is empty, or false otherwise.\n boolean isFull() Returns true if the deque is full, or false otherwise.\n Example 1:\n Input\n [\"MyCircularDeque\", \"insertLast\", \"insertLast\", \"insertFront\", \"insertFront\", \"getRear\", \"isFull\", \"deleteLast\", \"insertFront\", \"getFront\"]\n [[3], [1], [2], [3], [4], [], [], [], [4], []]\n Output\n [null, true, true, true, false, 2, true, true, true, 4]\n Explanation\n MyCircularDeque myCircularDeque = new MyCircularDeque(3);\n myCircularDeque.insertLast(1); // return True\n myCircularDeque.insertLast(2); // return True\n myCircularDeque.insertFront(3); // return True\n myCircularDeque.insertFront(4); // return False, the queue is full.\n myCircularDeque.getRear(); // return 2\n myCircularDeque.isFull(); // return True\n myCircularDeque.deleteLast(); // return True\n myCircularDeque.insertFront(4); // return True\n myCircularDeque.getFront(); // return 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 622, - "title": "Design Circular Queue", - "question": "class MyCircularQueue:\n def __init__(self, k: int):\n def enQueue(self, value: int) -> bool:\n def deQueue(self) -> bool:\n def Front(self) -> int:\n def Rear(self) -> int:\n def isEmpty(self) -> bool:\n def isFull(self) -> bool:\n \"\"\"\n Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called \"Ring Buffer\".\n One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.\n Implement the MyCircularQueue class:\n MyCircularQueue(k) Initializes the object with the size of the queue to be k.\n int Front() Gets the front item from the queue. If the queue is empty, return -1.\n int Rear() Gets the last item from the queue. If the queue is empty, return -1.\n boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.\n boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.\n boolean isEmpty() Checks whether the circular queue is empty or not.\n boolean isFull() Checks whether the circular queue is full or not.\n You must solve the problem without using the built-in queue data structure in your programming language. \n Example 1:\n Input\n [\"MyCircularQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"enQueue\", \"Rear\", \"isFull\", \"deQueue\", \"enQueue\", \"Rear\"]\n [[3], [1], [2], [3], [4], [], [], [], [4], []]\n Output\n [null, true, true, true, false, 3, true, true, true, 4]\n Explanation\n MyCircularQueue myCircularQueue = new MyCircularQueue(3);\n myCircularQueue.enQueue(1); // return True\n myCircularQueue.enQueue(2); // return True\n myCircularQueue.enQueue(3); // return True\n myCircularQueue.enQueue(4); // return False\n myCircularQueue.Rear(); // return 3\n myCircularQueue.isFull(); // return True\n myCircularQueue.deQueue(); // return True\n myCircularQueue.enQueue(4); // return True\n myCircularQueue.Rear(); // return 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 832, - "title": "Flipping an Image", - "question": "class Solution:\n def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.\n To flip an image horizontally means that each row of the image is reversed.\n For example, flipping [1,1,0] horizontally results in [0,1,1].\n To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.\n For example, inverting [0,1,1] results in [1,0,0].\n Example 1:\n Input: image = [[1,1,0],[1,0,1],[0,0,0]]\n Output: [[1,0,0],[0,1,0],[1,1,1]]\n Explanation: First reverse each row: [[0,1,1],[1,0,1],[0,0,0]].\n Then, invert the image: [[1,0,0],[0,1,0],[1,1,1]]\n Example 2:\n Input: image = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]\n Output: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n Explanation: First reverse each row: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]].\n Then invert the image: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 833, - "title": "Find And Replace in String", - "question": "class Solution:\n def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:\n \"\"\"\n 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.\n To complete the ith replacement operation:\n Check if the substring sources[i] occurs at index indices[i] in the original string s.\n If it does not occur, do nothing.\n Otherwise if it does occur, replace that substring with targets[i].\n For example, if s = \"abcd\", indices[i] = 0, sources[i] = \"ab\", and targets[i] = \"eee\", then the result of this replacement will be \"eeecd\".\n All 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.\n For example, a testcase with s = \"abc\", indices = [0, 1], and sources = [\"ab\",\"bc\"] will not be generated because the \"ab\" and \"bc\" replacements overlap.\n Return the resulting string after performing all replacement operations on s.\n A substring is a contiguous sequence of characters in a string.\n Example 1:\n Input: s = \"abcd\", indices = [0, 2], sources = [\"a\", \"cd\"], targets = [\"eee\", \"ffff\"]\n Output: \"eeebffff\"\n Explanation:\n \"a\" occurs at index 0 in s, so we replace it with \"eee\".\n \"cd\" occurs at index 2 in s, so we replace it with \"ffff\".\n Example 2:\n Input: s = \"abcd\", indices = [0, 2], sources = [\"ab\",\"ec\"], targets = [\"eee\",\"ffff\"]\n Output: \"eeecd\"\n Explanation:\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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 834, - "title": "Sum of Distances in Tree", - "question": "class Solution:\n def sumOfDistancesInTree(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n You 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.\n Return 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:\n Input: n = 6, edges = [[0,1],[0,2],[2,3],[2,4],[2,5]]\n Output: [8,12,6,10,10,10]\n Explanation: The tree is shown above.\n We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5)\n equals 1 + 1 + 2 + 2 + 2 = 8.\n Hence, answer[0] = 8, and so on.\n Example 2:\n Input: n = 1, edges = []\n Output: [0]\n Example 3:\n Input: n = 2, edges = [[1,0]]\n Output: [1,1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 835, - "title": "Image Overlap", - "question": "class Solution:\n def largestOverlap(self, img1: List[List[int]], img2: List[List[int]]) -> int:\n \"\"\"\n 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.\n We 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.\n Note also that a translation does not include any kind of rotation. Any 1 bits that are translated outside of the matrix borders are erased.\n Return the largest possible overlap.\n Example 1:\n Input: img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]\n Output: 3\n Explanation: We translate img1 to right by 1 unit and down by 1 unit.\n The number of positions that have a 1 in both images is 3 (shown in red).\n Example 2:\n Input: img1 = [[1]], img2 = [[1]]\n Output: 1\n Example 3:\n Input: img1 = [[0]], img2 = [[0]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 836, - "title": "Rectangle Overlap", - "question": "class Solution:\n def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:\n \"\"\"\n An axis-aligned rectangle is represented as a list [x1, y1, x2, y2], where (x1, y1) is the coordinate of its bottom-left corner, and (x2, y2) is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis.\n Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.\n Given two axis-aligned rectangles rec1 and rec2, return true if they overlap, otherwise return false.\n Example 1:\n Input: rec1 = [0,0,2,2], rec2 = [1,1,3,3]\n Output: true\n Example 2:\n Input: rec1 = [0,0,1,1], rec2 = [1,0,2,1]\n Output: false\n Example 3:\n Input: rec1 = [0,0,1,1], rec2 = [2,2,3,3]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 837, - "title": "New 21 Game", - "question": "class Solution:\n def new21Game(self, n: int, k: int, maxPts: int) -> float:\n \"\"\"\n Alice plays the following game, loosely based on the card game \"21\".\n Alice 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.\n Alice stops drawing numbers when she gets k or more points.\n Return the probability that Alice has n or fewer points.\n Answers within 10-5 of the actual answer are considered accepted.\n Example 1:\n Input: n = 10, k = 1, maxPts = 10\n Output: 1.00000\n Explanation: Alice gets a single card, then stops.\n Example 2:\n Input: n = 6, k = 1, maxPts = 10\n Output: 0.60000\n Explanation: Alice gets a single card, then stops.\n In 6 out of 10 possibilities, she is at or below 6 points.\n Example 3:\n Input: n = 21, k = 17, maxPts = 10\n Output: 0.73278\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 838, - "title": "Push Dominoes", - "question": "class Solution:\n def pushDominoes(self, dominoes: str) -> str:\n \"\"\"\n 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.\n After 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.\n When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces.\n For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino.\n You are given a string dominoes representing the initial state where:\n dominoes[i] = 'L', if the ith domino has been pushed to the left,\n dominoes[i] = 'R', if the ith domino has been pushed to the right, and\n dominoes[i] = '.', if the ith domino has not been pushed.\n Return a string representing the final state.\n Example 1:\n Input: dominoes = \"RR.L\"\n Output: \"RR.L\"\n Explanation: The first domino expends no additional force on the second domino.\n Example 2:\n Input: dominoes = \".L.R...LR..L..\"\n Output: \"LL.RR.LLRRLL..\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 839, - "title": "Similar String Groups", - "question": "class Solution:\n def numSimilarGroups(self, strs: List[str]) -> int:\n \"\"\"\n Two strings X and Y are similar if we can swap two letters (in different positions) of X, so that it equals Y. Also two strings X and Y are similar if they are equal.\n For example, \"tars\" and \"rats\" are similar (swapping at positions 0 and 2), and \"rats\" and \"arts\" are similar, but \"star\" is not similar to \"tars\", \"rats\", or \"arts\".\n Together, these form two connected groups by similarity: {\"tars\", \"rats\", \"arts\"} and {\"star\"}. Notice that \"tars\" and \"arts\" are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.\n We are given a list strs of strings where every string in strs is an anagram of every other string in strs. How many groups are there?\n Example 1:\n Input: strs = [\"tars\",\"rats\",\"arts\",\"star\"]\n Output: 2\n Example 2:\n Input: strs = [\"omv\",\"ovm\"]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 840, - "title": "Magic Squares In Grid", - "question": "class Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Given a row x col grid of integers, how many 3 x 3 \"magic square\" subgrids are there? (Each subgrid is contiguous).\n Example 1:\n Input: grid = [[4,3,8,4],[9,5,1,9],[2,7,6,2]]\n Output: 1\n Explanation: \n The following subgrid is a 3 x 3 magic square:\n while this one is not:\n In total, there is only one magic square inside the given grid.\n Example 2:\n Input: grid = [[8]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 841, - "title": "Keys and Rooms", - "question": "class Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n \"\"\"\n 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.\n When 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.\n Given 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:\n Input: rooms = [[1],[2],[3],[]]\n Output: true\n Explanation: \n We visit room 0 and pick up key 1.\n We then visit room 1 and pick up key 2.\n We then visit room 2 and pick up key 3.\n We then visit room 3.\n Since we were able to visit every room, we return true.\n Example 2:\n Input: rooms = [[1,3],[3,0,1],[2],[0]]\n Output: false\n Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 842, - "title": "Split Array into Fibonacci Sequence", - "question": "class Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n \"\"\"\n You are given a string of digits num, such as \"123456579\". We can split it into a Fibonacci-like sequence [123, 456, 579].\n Formally, a Fibonacci-like sequence is a list f of non-negative integers such that:\n 0 <= f[i] < 231, (that is, each integer fits in a 32-bit signed integer type),\n f.length >= 3, and\n f[i] + f[i + 1] == f[i + 2] for all 0 <= i < f.length - 2.\n Note that when splitting the string into pieces, each piece must not have extra leading zeroes, except if the piece is the number 0 itself.\n Return any Fibonacci-like sequence split from num, or return [] if it cannot be done.\n Example 1:\n Input: num = \"1101111\"\n Output: [11,0,11,11]\n Explanation: The output [110, 1, 111] would also be accepted.\n Example 2:\n Input: num = \"112358130\"\n Output: []\n Explanation: The task is impossible.\n Example 3:\n Input: num = \"0123\"\n Output: []\n Explanation: Leading zeroes are not allowed, so \"01\", \"2\", \"3\" is not valid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 843, - "title": "Guess the Word", - "question": " \"\"\"\n 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.\n You 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\n an integer representing the number of exact matches (value and position) of your guess to the secret word.\n There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word).\n For 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.\n The 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:\n Input: secret = \"acckzz\", words = [\"acckzz\",\"ccbazz\",\"eiowzz\",\"abcczz\"], allowedGuesses = 10\n Output: You guessed the secret word correctly.\n Explanation:\n master.guess(\"aaaaaa\") returns -1, because \"aaaaaa\" is not in wordlist.\n master.guess(\"acckzz\") returns 6, because \"acckzz\" is secret and has all 6 matches.\n master.guess(\"ccbazz\") returns 3, because \"ccbazz\" has 3 matches.\n master.guess(\"eiowzz\") returns 2, because \"eiowzz\" has 2 matches.\n master.guess(\"abcczz\") returns 4, because \"abcczz\" has 4 matches.\n We made 5 calls to master.guess, and one of them was the secret, so we pass the test case.\n Example 2:\n Input: secret = \"hamada\", words = [\"hamada\",\"khaled\"], allowedGuesses = 10\n Output: You guessed the secret word correctly.\n Explanation: Since there are two words, you can guess both.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 844, - "title": "Backspace String Compare", - "question": "class Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n \"\"\"\n Given two strings s and t, return true if they are equal when both are typed into empty text editors. '#' means a backspace character.\n Note that after backspacing an empty text, the text will continue empty.\n Example 1:\n Input: s = \"ab#c\", t = \"ad#c\"\n Output: true\n Explanation: Both s and t become \"ac\".\n Example 2:\n Input: s = \"ab##\", t = \"c#d#\"\n Output: true\n Explanation: Both s and t become \"\".\n Example 3:\n Input: s = \"a#c\", t = \"b\"\n Output: false\n Explanation: s becomes \"c\" while t becomes \"b\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 845, - "title": "Longest Mountain in Array", - "question": "class Solution:\n def longestMountain(self, arr: List[int]) -> int:\n \"\"\"\n You may recall that an array arr is a mountain array if and only if:\n arr.length >= 3\n There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:\n arr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n Given 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:\n Input: arr = [2,1,4,7,3,2,5]\n Output: 5\n Explanation: The largest mountain is [1,4,7,3,2] which has length 5.\n Example 2:\n Input: arr = [2,2,2]\n Output: 0\n Explanation: There is no mountain.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 846, - "title": "Hand of Straights", - "question": "class Solution:\n def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n \"\"\"\n 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.\n Given 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:\n Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3\n Output: true\n Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]\n Example 2:\n Input: hand = [1,2,3,4,5], groupSize = 4\n Output: false\n Explanation: Alice's hand can not be rearranged into groups of 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 847, - "title": "Shortest Path Visiting All Nodes", - "question": "class Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n \"\"\"\n You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.\n Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.\n Example 1:\n Input: graph = [[1,2,3],[0],[0],[0]]\n Output: 4\n Explanation: One possible path is [1,0,2,0,3]\n Example 2:\n Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]\n Output: 4\n Explanation: One possible path is [0,1,4,2,3]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 848, - "title": "Shifting Letters", - "question": "class Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n \"\"\"\n You are given a string s of lowercase English letters and an integer array shifts of the same length.\n Call the shift() of a letter, the next letter in the alphabet, (wrapping around so that 'z' becomes 'a').\n For example, shift('a') = 'b', shift('t') = 'u', and shift('z') = 'a'.\n Now for each shifts[i] = x, we want to shift the first i + 1 letters of s, x times.\n Return the final string after all such shifts to s are applied.\n Example 1:\n Input: s = \"abc\", shifts = [3,5,9]\n Output: \"rpl\"\n Explanation: We start with \"abc\".\n After shifting the first 1 letters of s by 3, we have \"dbc\".\n After shifting the first 2 letters of s by 5, we have \"igc\".\n After shifting the first 3 letters of s by 9, we have \"rpl\", the answer.\n Example 2:\n Input: s = \"aaa\", shifts = [1,2,3]\n Output: \"gfd\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 849, - "title": "Maximize Distance to Closest Person", - "question": "class Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n \"\"\"\n 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).\n There is at least one empty seat, and at least one person sitting.\n Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. \n Return that maximum distance to the closest person.\n Example 1:\n Input: seats = [1,0,0,0,1,0,1]\n Output: 2\n Explanation: \n If Alex sits in the second open seat (i.e. seats[2]), then the closest person has distance 2.\n If Alex sits in any other open seat, the closest person has distance 1.\n Thus, the maximum distance to the closest person is 2.\n Example 2:\n Input: seats = [1,0,0,0]\n Output: 3\n Explanation: \n If Alex sits in the last seat (i.e. seats[3]), the closest person is 3 seats away.\n This is the maximum distance possible, so the answer is 3.\n Example 3:\n Input: seats = [0,1]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 850, - "title": "Rectangle Area II", - "question": "class Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n \"\"\"\n 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.\n Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.\n Return the total area. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\n Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]\n Output: 6\n Explanation: A total area of 6 is covered by all three rectangles, as illustrated in the picture.\n From (1,1) to (2,2), the green and red rectangles overlap.\n From (1,0) to (2,3), all three rectangles overlap.\n Example 2:\n Input: rectangles = [[0,0,1000000000,1000000000]]\n Output: 49\n Explanation: The answer is 1018 modulo (109 + 7), which is 49.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 851, - "title": "Loud and Rich", - "question": "class Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n \"\"\"\n 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.\n You 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).\n Return 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:\n Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]\n Output: [5,5,2,5,4,5,6,7]\n Explanation: \n answer[0] = 5.\n Person 5 has more money than 3, which has more money than 1, which has more money than 0.\n The 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.\n answer[7] = 7.\n Among 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.\n The other answers can be filled out with similar reasoning.\n Example 2:\n Input: richer = [], quiet = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 852, - "title": "Peak Index in a Mountain Array", - "question": "class Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n \"\"\"\n An array arr a mountain if the following properties hold:\n arr.length >= 3\n There exists some i with 0 < i < arr.length - 1 such that:\n arr[0] < arr[1] < ... < arr[i - 1] < arr[i] \n arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n Given 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].\n You must solve it in O(log(arr.length)) time complexity.\n Example 1:\n Input: arr = [0,1,0]\n Output: 1\n Example 2:\n Input: arr = [0,2,1,0]\n Output: 1\n Example 3:\n Input: arr = [0,10,5,2]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 853, - "title": "Car Fleet", - "question": "class Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n \"\"\"\n There are n cars going to the same destination along a one-lane road. The destination is target miles away.\n You 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).\n A 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).\n A 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.\n If a car catches up to a car fleet right at the destination point, it will still be considered as one car fleet.\n Return the number of car fleets that will arrive at the destination.\n Example 1:\n Input: target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]\n Output: 3\n Explanation:\n The cars starting at 10 (speed 2) and 8 (speed 4) become a fleet, meeting each other at 12.\n The car starting at 0 does not catch up to any other car, so it is a fleet by itself.\n The 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.\n Note that no other cars meet these fleets before the destination, so the answer is 3.\n Example 2:\n Input: target = 10, position = [3], speed = [3]\n Output: 1\n Explanation: There is only one car, hence there is only one fleet.\n Example 3:\n Input: target = 100, position = [0,2,4], speed = [4,2,1]\n Output: 1\n Explanation:\n The cars starting at 0 (speed 4) and 2 (speed 2) become a fleet, meeting each other at 4. The fleet moves at speed 2.\n Then, 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 854, - "title": "K-Similar Strings", - "question": "class Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n \"\"\"\n Strings s1 and s2 are k-similar (for some non-negative integer k) if we can swap the positions of two letters in s1 exactly k times so that the resulting string equals s2.\n Given two anagrams s1 and s2, return the smallest k for which s1 and s2 are k-similar.\n Example 1:\n Input: s1 = \"ab\", s2 = \"ba\"\n Output: 1\n Explanation: The two string are 1-similar because we can use one swap to change s1 to s2: \"ab\" --> \"ba\".\n Example 2:\n Input: s1 = \"abc\", s2 = \"bca\"\n Output: 2\n Explanation: The two strings are 2-similar because we can use two swaps to change s1 to s2: \"abc\" --> \"bac\" --> \"bca\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 855, - "title": "Exam Room", - "question": "class ExamRoom:\n def __init__(self, n: int):\n def seat(self) -> int:\n def leave(self, p: int) -> None:\n \"\"\"\n There is an exam room with n seats in a single row labeled from 0 to n - 1.\n When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits at seat number 0.\n Design a class that simulates the mentioned exam room.\n Implement the ExamRoom class:\n ExamRoom(int n) Initializes the object of the exam room with the number of the seats n.\n int seat() Returns the label of the seat at which the next student will set.\n void leave(int p) Indicates that the student sitting at seat p will leave the room. It is guaranteed that there will be a student sitting at seat p.\n Example 1:\n Input\n [\"ExamRoom\", \"seat\", \"seat\", \"seat\", \"seat\", \"leave\", \"seat\"]\n [[10], [], [], [], [], [4], []]\n Output\n [null, 0, 9, 4, 2, null, 5]\n Explanation\n ExamRoom examRoom = new ExamRoom(10);\n examRoom.seat(); // return 0, no one is in the room, then the student sits at seat number 0.\n examRoom.seat(); // return 9, the student sits at the last seat number 9.\n examRoom.seat(); // return 4, the student sits at the last seat number 4.\n examRoom.seat(); // return 2, the student sits at the last seat number 2.\n examRoom.leave(4);\n examRoom.seat(); // return 5, the student sits at the last seat number 5.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 856, - "title": "Score of Parentheses", - "question": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n \"\"\"\n Given a balanced parentheses string s, return the score of the string.\n The score of a balanced parentheses string is based on the following rule:\n \"()\" has score 1.\n AB 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:\n Input: s = \"()\"\n Output: 1\n Example 2:\n Input: s = \"(())\"\n Output: 2\n Example 3:\n Input: s = \"()()\"\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 857, - "title": "Minimum Cost to Hire K Workers", - "question": "class Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n \"\"\"\n 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.\n We 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:\n Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group.\n Every worker in the paid group must be paid at least their minimum wage expectation.\n Given 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:\n Input: quality = [10,20,5], wage = [70,50,30], k = 2\n Output: 105.00000\n Explanation: We pay 70 to 0th worker and 35 to 2nd worker.\n Example 2:\n Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], k = 3\n Output: 30.66667\n Explanation: We pay 4 to 0th worker, 13.33333 to 2nd and 3rd workers separately.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 858, - "title": "Mirror Reflection", - "question": "class Solution:\n def mirrorReflection(self, p: int, q: int) -> int:\n \"\"\"\n 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.\n The 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.\n Given the two integers p and q, return the number of the receptor that the ray meets first.\n The test cases are guaranteed so that the ray will meet a receptor eventually.\n Example 1:\n Input: p = 2, q = 1\n Output: 2\n Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.\n Example 2:\n Input: p = 3, q = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 859, - "title": "Buddy Strings", - "question": "class Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n \"\"\"\n 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.\n Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].\n For example, swapping at indices 0 and 2 in \"abcd\" results in \"cbad\".\n Example 1:\n Input: s = \"ab\", goal = \"ba\"\n Output: true\n Explanation: You can swap s[0] = 'a' and s[1] = 'b' to get \"ba\", which is equal to goal.\n Example 2:\n Input: s = \"ab\", goal = \"ab\"\n Output: false\n Explanation: The only letters you can swap are s[0] = 'a' and s[1] = 'b', which results in \"ba\" != goal.\n Example 3:\n Input: s = \"aa\", goal = \"aa\"\n Output: true\n Explanation: You can swap s[0] = 'a' and s[1] = 'a' to get \"aa\", which is equal to goal.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 860, - "title": "Lemonade Change", - "question": "class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \"\"\"\n 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.\n Note that you do not have any change in hand at first.\n Given 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:\n Input: bills = [5,5,5,10,20]\n Output: true\n Explanation: \n From the first 3 customers, we collect three $5 bills in order.\n From the fourth customer, we collect a $10 bill and give back a $5.\n From the fifth customer, we give a $10 bill and a $5 bill.\n Since all customers got correct change, we output true.\n Example 2:\n Input: bills = [5,5,10,10,20]\n Output: false\n Explanation: \n From the first two customers in order, we collect two $5 bills.\n For the next two customers in order, we collect a $10 bill and give back a $5 bill.\n For the last customer, we can not give the change of $15 back because we only have two $10 bills.\n Since not every customer received the correct change, the answer is false.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 861, - "title": "Score After Flipping Matrix", - "question": "class Solution:\n def matrixScore(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n binary matrix grid.\n A 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).\n Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.\n Return the highest possible score after making any number of moves (including zero moves).\n Example 1:\n Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\n Output: 39\n Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39\n Example 2:\n Input: grid = [[0]]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 862, - "title": "Shortest Subarray with Sum at Least K", - "question": "class Solution:\n def shortestSubarray(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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.\n A subarray is a contiguous part of an array.\n Example 1:\n Input: nums = [1], k = 1\n Output: 1\n Example 2:\n Input: nums = [1,2], k = 4\n Output: -1\n Example 3:\n Input: nums = [2,-1,2], k = 3\n Output: 3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 863, - "title": "All Nodes Distance K in Binary Tree", - "question": "class Solution:\n def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:\n \"\"\"\n 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.\n You can return the answer in any order.\n Example 1:\n Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2\n Output: [7,4,1]\n Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.\n Example 2:\n Input: root = [1], target = 1, k = 3\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 710, - "title": "Random Pick with Blacklist", - "question": "class Solution:\n def __init__(self, n: int, blacklist: List[int]):\n def pick(self) -> int:\n \"\"\"\n 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.\n Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.\n Implement the Solution class:\n Solution(int n, int[] blacklist) Initializes the object with the integer n and the blacklisted integers blacklist.\n int pick() Returns a random integer in the range [0, n - 1] and not in blacklist.\n Example 1:\n Input\n [\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n [[7, [2, 3, 5]], [], [], [], [], [], [], []]\n Output\n [null, 0, 4, 1, 6, 1, 0, 4]\n Explanation\n Solution solution = new Solution(7, [2, 3, 5]);\n solution.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).\n solution.pick(); // return 4\n solution.pick(); // return 1\n solution.pick(); // return 6\n solution.pick(); // return 1\n solution.pick(); // return 0\n solution.pick(); // return 4\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 864, - "title": "Shortest Path to Get All Keys", - "question": "class Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n \"\"\"\n You are given an m x n grid grid where:\n '.' is an empty cell.\n '#' is a wall.\n '@' is the starting point.\n Lowercase letters represent keys.\n Uppercase letters represent locks.\n You 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.\n If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.\n For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.\n Return the lowest number of moves to acquire all keys. If it is impossible, return -1.\n Example 1:\n Input: grid = [\"@.a..\",\"###.#\",\"b.A.B\"]\n Output: 8\n Explanation: Note that the goal is to obtain all the keys not to open all the locks.\n Example 2:\n Input: grid = [\"@..aA\",\"..B#.\",\"....b\"]\n Output: 6\n Example 3:\n Input: grid = [\"@Aa\"]\n Output: -1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 865, - "title": "Smallest Subtree with all the Deepest Nodes", - "question": "class Solution:\n def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:\n \"\"\"\n Given the root of a binary tree, the depth of each node is the shortest distance to the root.\n Return the smallest subtree such that it contains all the deepest nodes in the original tree.\n A node is called the deepest if it has the largest depth possible among any node in the entire tree.\n The subtree of a node is a tree consisting of that node, plus the set of all descendants of that node.\n Example 1:\n Input: root = [3,5,1,6,2,0,8,null,null,7,4]\n Output: [2,7,4]\n Explanation: We return the node with value 2, colored in yellow in the diagram.\n The nodes coloured in blue are the deepest nodes of the tree.\n Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.\n Example 2:\n Input: root = [1]\n Output: [1]\n Explanation: The root is the deepest node in the tree.\n Example 3:\n Input: root = [0,1,3,null,2]\n Output: [2]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 866, - "title": "Prime Palindrome", - "question": "class Solution:\n def primePalindrome(self, n: int) -> int:\n \"\"\"\n Given an integer n, return the smallest prime palindrome greater than or equal to n.\n An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime number.\n For example, 2, 3, 5, 7, 11, and 13 are all primes.\n An integer is a palindrome if it reads the same from left to right as it does from right to left.\n For example, 101 and 12321 are palindromes.\n The test cases are generated so that the answer always exists and is in the range [2, 2 * 108].\n Example 1:\n Input: n = 6\n Output: 7\n Example 2:\n Input: n = 8\n Output: 11\n Example 3:\n Input: n = 13\n Output: 101\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 867, - "title": "Transpose Matrix", - "question": "class Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Given a 2D integer array matrix, return the transpose of matrix.\n The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.\n Example 1:\n Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]\n Output: [[1,4,7],[2,5,8],[3,6,9]]\n Example 2:\n Input: matrix = [[1,2,3],[4,5,6]]\n Output: [[1,4],[2,5],[3,6]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 868, - "title": "Binary Gap", - "question": "class Solution:\n def binaryGap(self, n: int) -> int:\n \"\"\"\n Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n. If there are no two adjacent 1's, return 0.\n Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions. For example, the two 1's in \"1001\" have a distance of 3.\n Example 1:\n Input: n = 22\n Output: 2\n Explanation: 22 in binary is \"10110\".\n The first adjacent pair of 1's is \"10110\" with a distance of 2.\n The second adjacent pair of 1's is \"10110\" with a distance of 1.\n The answer is the largest of these two distances, which is 2.\n Note that \"10110\" is not a valid pair since there is a 1 separating the two 1's underlined.\n Example 2:\n Input: n = 8\n Output: 0\n Explanation: 8 in binary is \"1000\".\n There are not any adjacent pairs of 1's in the binary representation of 8, so we return 0.\n Example 3:\n Input: n = 5\n Output: 2\n Explanation: 5 in binary is \"101\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 869, - "title": "Reordered Power of 2", - "question": "class Solution:\n def reorderedPowerOf2(self, n: int) -> bool:\n \"\"\"\n 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.\n Return true if and only if we can do this so that the resulting number is a power of two.\n Example 1:\n Input: n = 1\n Output: true\n Example 2:\n Input: n = 10\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 870, - "title": "Advantage Shuffle", - "question": "class Solution:\n def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:\n \"\"\"\n 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].\n Return any permutation of nums1 that maximizes its advantage with respect to nums2.\n Example 1:\n Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11]\n Output: [2,11,7,15]\n Example 2:\n Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11]\n Output: [24,32,8,12]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 871, - "title": "Minimum Number of Refueling Stops", - "question": "class Solution:\n def minRefuelStops(self, target: int, startFuel: int, stations: List[List[int]]) -> int:\n \"\"\"\n A car travels from a starting position to a destination which is target miles east of the starting position.\n There 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.\n The 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.\n Return the minimum number of refueling stops the car must make in order to reach its destination. If it cannot reach the destination, return -1.\n Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there. If the car reaches the destination with 0 fuel left, it is still considered to have arrived.\n Example 1:\n Input: target = 1, startFuel = 1, stations = []\n Output: 0\n Explanation: We can reach the target without refueling.\n Example 2:\n Input: target = 100, startFuel = 1, stations = [[10,100]]\n Output: -1\n Explanation: We can not reach the target (or even the first gas station).\n Example 3:\n Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]\n Output: 2\n Explanation: We start with 10 liters of fuel.\n We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.\n Then, we drive from position 10 to position 60 (expending 50 liters of fuel),\n and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.\n We made 2 refueling stops along the way, so we return 2.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 470, - "title": "Implement Rand10() Using Rand7()", - "question": "class Solution:\n def rand10(self):\n \"\"\"\n :rtype: int\n Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.\n Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().\n Example 1:\n Input: n = 1\n Output: [2]\n Example 2:\n Input: n = 2\n Output: [2,8]\n Example 3:\n Input: n = 3\n Output: [3,8,10]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 872, - "title": "Leaf-Similar Trees", - "question": "class Solution:\n def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n \"\"\"\n Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.\n For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).\n Two binary trees are considered leaf-similar if their leaf value sequence is the same.\n Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.\n Example 1:\n Input: 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]\n Output: true\n Example 2:\n Input: root1 = [1,2,3], root2 = [1,3,2]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 873, - "title": "Length of Longest Fibonacci Subsequence", - "question": "class Solution:\n def lenLongestFibSubseq(self, arr: List[int]) -> int:\n \"\"\"\n A sequence x1, x2, ..., xn is Fibonacci-like if:\n n >= 3\n xi + xi+1 == xi+2 for all i + 2 <= n\n Given 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.\n A 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:\n Input: arr = [1,2,3,4,5,6,7,8]\n Output: 5\n Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].\n Example 2:\n Input: arr = [1,3,7,11,12,14,18]\n Output: 3\n Explanation: The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 874, - "title": "Walking Robot Simulation", - "question": "class Solution:\n def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:\n \"\"\"\n 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.\n 1 <= k <= 9: Move forward k units, one unit at a time.\n Some 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.\n Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).\n Note:\n North means +Y direction.\n East means +X direction.\n South means -Y direction.\n West means -X direction.\n Example 1:\n Input: commands = [4,-1,3], obstacles = []\n Output: 25\n Explanation: The robot starts at (0, 0):\n 1. Move north 4 units to (0, 4).\n 2. Turn right.\n 3. Move east 3 units to (3, 4).\n The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away.\n Example 2:\n Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]\n Output: 65\n Explanation: The robot starts at (0, 0):\n 1. Move north 4 units to (0, 4).\n 2. Turn right.\n 3. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4).\n 4. Turn left.\n 5. Move north 4 units to (1, 8).\n The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away.\n Example 3:\n Input: commands = [6,-1,-1,6], obstacles = []\n Output: 36\n Explanation: The robot starts at (0, 0):\n 1. Move north 6 units to (0, 6).\n 2. Turn right.\n 3. Turn right.\n 4. Move south 6 units to (0, 0).\n The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 875, - "title": "Koko Eating Bananas", - "question": "class Solution:\n def minEatingSpeed(self, piles: List[int], h: int) -> int:\n \"\"\"\n 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.\n Koko 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.\n Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.\n Return the minimum integer k such that she can eat all the bananas within h hours.\n Example 1:\n Input: piles = [3,6,7,11], h = 8\n Output: 4\n Example 2:\n Input: piles = [30,11,23,4,20], h = 5\n Output: 30\n Example 3:\n Input: piles = [30,11,23,4,20], h = 6\n Output: 23\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 876, - "title": "Middle of the Linked List", - "question": "class Solution:\n def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a singly linked list, return the middle node of the linked list.\n If there are two middle nodes, return the second middle node.\n Example 1:\n Input: head = [1,2,3,4,5]\n Output: [3,4,5]\n Explanation: The middle node of the list is node 3.\n Example 2:\n Input: head = [1,2,3,4,5,6]\n Output: [4,5,6]\n Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 877, - "title": "Stone Game", - "question": "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n \"\"\"\n 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].\n The 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.\n Alice 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.\n Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.\n Example 1:\n Input: piles = [5,3,4,5]\n Output: true\n Explanation: \n Alice starts first, and can only take the first 5 or the last 5.\n Say she takes the first 5, so that the row becomes [3, 4, 5].\n If Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.\n If Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.\n This demonstrated that taking the first 5 was a winning move for Alice, so we return true.\n Example 2:\n Input: piles = [3,7,2,3]\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 878, - "title": "Nth Magical Number", - "question": "class Solution:\n def nthMagicalNumber(self, n: int, a: int, b: int) -> int:\n \"\"\"\n A positive integer is magical if it is divisible by either a or b.\n Given the three integers n, a, and b, return the nth magical number. Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\n Input: n = 1, a = 2, b = 3\n Output: 2\n Example 2:\n Input: n = 4, a = 2, b = 3\n Output: 6\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 879, - "title": "Profitable Schemes", - "question": "class Solution:\n def profitableSchemes(self, n: int, minProfit: int, group: List[int], profit: List[int]) -> int:\n \"\"\"\n There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can't participate in another crime.\n Let's call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.\n Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\n Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]\n Output: 2\n Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.\n In total, there are 2 schemes.\n Example 2:\n Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]\n Output: 7\n Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.\n There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 528, - "title": "Random Pick with Weight", - "question": "class Solution:\n def __init__(self, w: List[int]):\n def pickIndex(self) -> int:\n \"\"\"\n You are given a 0-indexed array of positive integers w where w[i] describes the weight of the ith index.\n You 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).\n For 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:\n Input\n [\"Solution\",\"pickIndex\"]\n [[[1]],[]]\n Output\n [null,0]\n Explanation\n Solution solution = new Solution([1]);\n solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.\n Example 2:\n Input\n [\"Solution\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\",\"pickIndex\"]\n [[[1,3]],[],[],[],[],[]]\n Output\n [null,1,1,1,1,0]\n Explanation\n Solution solution = new Solution([1, 3]);\n solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.\n solution.pickIndex(); // return 1\n solution.pickIndex(); // return 1\n solution.pickIndex(); // return 1\n solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.\n Since this is a randomization problem, multiple answers are allowed.\n All 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 ......\n and so on.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 519, - "title": "Random Flip Matrix", - "question": "class Solution:\n def __init__(self, m: int, n: int):\n def flip(self) -> List[int]:\n def reset(self) -> None:\n \"\"\"\n 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.\n Optimize 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.\n Implement the Solution class:\n Solution(int m, int n) Initializes the object with the size of the binary matrix m and n.\n int[] flip() Returns a random index [i, j] of the matrix where matrix[i][j] == 0 and flips it to 1.\n void reset() Resets all the values of the matrix to be 0.\n Example 1:\n Input\n [\"Solution\", \"flip\", \"flip\", \"flip\", \"reset\", \"flip\"]\n [[3, 1], [], [], [], [], []]\n Output\n [null, [1, 0], [2, 0], [0, 0], null, [2, 0]]\n Explanation\n Solution solution = new Solution(3, 1);\n solution.flip(); // return [1, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\n solution.flip(); // return [2, 0], Since [1,0] was returned, [2,0] and [0,0]\n solution.flip(); // return [0, 0], Based on the previously returned indices, only [0,0] can be returned.\n solution.reset(); // All the values are reset to 0 and can be returned.\n solution.flip(); // return [2, 0], [0,0], [1,0], and [2,0] should be equally likely to be returned.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 497, - "title": "Random Point in Non-overlapping Rectangles", - "question": "class Solution:\n def __init__(self, rects: List[List[int]]):\n def pick(self) -> List[int]:\n \"\"\"\n 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.\n Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.\n Note that an integer point is a point that has integer coordinates.\n Implement the Solution class:\n Solution(int[][] rects) Initializes the object with the given rectangles rects.\n int[] pick() Returns a random integer point [u, v] inside the space covered by one of the given rectangles.\n Example 1:\n Input\n [\"Solution\", \"pick\", \"pick\", \"pick\", \"pick\", \"pick\"]\n [[[[-2, -2, 1, 1], [2, 2, 4, 6]]], [], [], [], [], []]\n Output\n [null, [1, -2], [1, -1], [-1, -2], [-2, -2], [0, 0]]\n Explanation\n Solution solution = new Solution([[-2, -2, 1, 1], [2, 2, 4, 6]]);\n solution.pick(); // return [1, -2]\n solution.pick(); // return [1, -1]\n solution.pick(); // return [-1, -2]\n solution.pick(); // return [-2, -2]\n solution.pick(); // return [0, 0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 478, - "title": "Generate Random Point in a Circle", - "question": "class Solution:\n def __init__(self, radius: float, x_center: float, y_center: float):\n def randPoint(self) -> List[float]:\n \"\"\"\n 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.\n Implement the Solution class:\n Solution(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).\n randPoint() 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:\n Input\n [\"Solution\", \"randPoint\", \"randPoint\", \"randPoint\"]\n [[1.0, 0.0, 0.0], [], [], []]\n Output\n [null, [-0.02493, -0.38077], [0.82314, 0.38945], [0.36572, 0.17248]]\n Explanation\n Solution solution = new Solution(1.0, 0.0, 0.0);\n solution.randPoint(); // return [-0.02493, -0.38077]\n solution.randPoint(); // return [0.82314, 0.38945]\n solution.randPoint(); // return [0.36572, 0.17248]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 880, - "title": "Decoded String at Index", - "question": "class Solution:\n def decodeAtIndex(self, s: str, k: int) -> str:\n \"\"\"\n 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:\n If the character read is a letter, that letter is written onto the tape.\n If the character read is a digit d, the entire current tape is repeatedly written d - 1 more times in total.\n Given an integer k, return the kth letter (1-indexed) in the decoded string.\n Example 1:\n Input: s = \"leet2code3\", k = 10\n Output: \"o\"\n Explanation: The decoded string is \"leetleetcodeleetleetcodeleetleetcode\".\n The 10th letter in the string is \"o\".\n Example 2:\n Input: s = \"ha22\", k = 5\n Output: \"h\"\n Explanation: The decoded string is \"hahahaha\".\n The 5th letter is \"h\".\n Example 3:\n Input: s = \"a2345678999999999999999\", k = 1\n Output: \"a\"\n Explanation: The decoded string is \"a\" repeated 8301530446056247680 times.\n The 1st letter is \"a\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 881, - "title": "Boats to Save People", - "question": "class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n \"\"\"\n 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.\n Return the minimum number of boats to carry every given person.\n Example 1:\n Input: people = [1,2], limit = 3\n Output: 1\n Explanation: 1 boat (1, 2)\n Example 2:\n Input: people = [3,2,2,1], limit = 3\n Output: 3\n Explanation: 3 boats (1, 2), (2) and (3)\n Example 3:\n Input: people = [3,5,3,4], limit = 5\n Output: 4\n Explanation: 4 boats (3), (3), (4), (5)\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 882, - "title": "Reachable Nodes In Subdivided Graph", - "question": "class Solution:\n def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int:\n \"\"\"\n You are given an undirected graph (the \"original graph\") with n nodes labeled from 0 to n - 1. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge.\n The graph is given as a 2D array of edges where edges[i] = [ui, vi, cnti] indicates that there is an edge between nodes ui and vi in the original graph, and cnti is the total number of new nodes that you will subdivide the edge into. Note that cnti == 0 means you will not subdivide the edge.\n To subdivide the edge [ui, vi], replace it with (cnti + 1) new edges and cnti new nodes. The new nodes are x1, x2, ..., xcnti, and the new edges are [ui, x1], [x1, x2], [x2, x3], ..., [xcnti-1, xcnti], [xcnti, vi].\n In this new graph, you want to know how many nodes are reachable from the node 0, where a node is reachable if the distance is maxMoves or less.\n Given the original graph and maxMoves, return the number of nodes that are reachable from node 0 in the new graph.\n Example 1:\n Input: edges = [[0,1,10],[0,2,1],[1,2,2]], maxMoves = 6, n = 3\n Output: 13\n Explanation: The edge subdivisions are shown in the image above.\n The nodes that are reachable are highlighted in yellow.\n Example 2:\n Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], maxMoves = 10, n = 4\n Output: 23\n Example 3:\n Input: edges = [[1,2,4],[1,4,5],[1,3,1],[2,3,4],[3,4,5]], maxMoves = 17, n = 5\n Output: 1\n Explanation: Node 0 is disconnected from the rest of the graph, so only node 0 is reachable.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 883, - "title": "Projection Area of 3D Shapes", - "question": "class Solution:\n def projectionArea(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Each value v = grid[i][j] represents a tower of v cubes placed on top of the cell (i, j).\n We view the projection of these cubes onto the xy, yz, and zx planes.\n A 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.\n Return the total area of all three projections.\n Example 1:\n Input: grid = [[1,2],[3,4]]\n Output: 17\n Explanation: Here are the three projections (\"shadows\") of the shape made with each axis-aligned plane.\n Example 2:\n Input: grid = [[2]]\n Output: 5\n Example 3:\n Input: grid = [[1,0],[0,2]]\n Output: 8\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 884, - "title": "Uncommon Words from Two Sentences", - "question": "class Solution:\n def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:\n \"\"\"\n A sentence is a string of single-space separated words where each word consists only of lowercase letters.\n A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.\n Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.\n Example 1:\n Input: s1 = \"this apple is sweet\", s2 = \"this apple is sour\"\n Output: [\"sweet\",\"sour\"]\n Example 2:\n Input: s1 = \"apple apple\", s2 = \"banana\"\n Output: [\"banana\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 885, - "title": "Spiral Matrix III", - "question": "class Solution:\n def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:\n \"\"\"\n You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.\n You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.\n Return an array of coordinates representing the positions of the grid in the order you visited them.\n Example 1:\n Input: rows = 1, cols = 4, rStart = 0, cStart = 0\n Output: [[0,0],[0,1],[0,2],[0,3]]\n Example 2:\n Input: rows = 5, cols = 6, rStart = 1, cStart = 4\n Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 886, - "title": "Possible Bipartition", - "question": "class Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n \"\"\"\n 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.\n Given 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:\n Input: n = 4, dislikes = [[1,2],[1,3],[2,4]]\n Output: true\n Explanation: The first group has [1,4], and the second group has [2,3].\n Example 2:\n Input: n = 3, dislikes = [[1,2],[1,3],[2,3]]\n Output: false\n Explanation: We need at least 3 groups to divide them. We cannot put them in two groups.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 887, - "title": "Super Egg Drop", - "question": "class Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n \"\"\"\n You are given k identical eggs and you have access to a building with n floors labeled from 1 to n.\n You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\n Each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\n Return the minimum number of moves that you need to determine with certainty what the value of f is.\n Example 1:\n Input: k = 1, n = 2\n Output: 2\n Explanation: \n Drop the egg from floor 1. If it breaks, we know that f = 0.\n Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1.\n If it does not break, then we know f = 2.\n Hence, we need at minimum 2 moves to determine with certainty what the value of f is.\n Example 2:\n Input: k = 2, n = 6\n Output: 3\n Example 3:\n Input: k = 3, n = 14\n Output: 4\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 888, - "title": "Fair Candy Swap", - "question": "class Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n \"\"\"\n 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.\n Since 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.\n Return 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:\n Input: aliceSizes = [1,1], bobSizes = [2,2]\n Output: [1,2]\n Example 2:\n Input: aliceSizes = [1,2], bobSizes = [2,3]\n Output: [1,2]\n Example 3:\n Input: aliceSizes = [2], bobSizes = [1,3]\n Output: [2,3]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 889, - "title": "Construct Binary Tree from Preorder and Postorder Traversal", - "question": "class Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n \"\"\"\n 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.\n If there exist multiple answers, you can return any of them.\n Example 1:\n Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]\n Output: [1,2,3,4,5,6,7]\n Example 2:\n Input: preorder = [1], postorder = [1]\n Output: [1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 890, - "title": "Find and Replace Pattern", - "question": "class Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n \"\"\"\n 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.\n A 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.\n Recall 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:\n Input: words = [\"abc\",\"deq\",\"mee\",\"aqq\",\"dkd\",\"ccc\"], pattern = \"abb\"\n Output: [\"mee\",\"aqq\"]\n Explanation: \"mee\" matches the pattern because there is a permutation {a -> m, b -> e, ...}. \n \"ccc\" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.\n Example 2:\n Input: words = [\"a\",\"b\",\"c\"], pattern = \"a\"\n Output: [\"a\",\"b\",\"c\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 891, - "title": "Sum of Subsequence Widths", - "question": "class Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n \"\"\"\n The width of a sequence is the difference between the maximum and minimum elements in the sequence.\n Given 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.\n A 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:\n Input: nums = [2,1,3]\n Output: 6\n Explanation: The subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].\n The corresponding widths are 0, 0, 0, 1, 1, 2, 2.\n The sum of these widths is 6.\n Example 2:\n Input: nums = [2]\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 892, - "title": "Surface Area of 3D Shapes", - "question": "class Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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).\n After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes.\n Return the total surface area of the resulting shapes.\n Note: The bottom face of each shape counts toward its surface area.\n Example 1:\n Input: grid = [[1,2],[3,4]]\n Output: 34\n Example 2:\n Input: grid = [[1,1,1],[1,0,1],[1,1,1]]\n Output: 32\n Example 3:\n Input: grid = [[2,2,2],[2,1,2],[2,2,2]]\n Output: 46\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 893, - "title": "Groups of Special-Equivalent Strings", - "question": "class Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n \"\"\"\n You are given an array of strings of the same length words.\n In one move, you can swap any two even indexed characters or any two odd indexed characters of a string words[i].\n Two strings words[i] and words[j] are special-equivalent if after any number of moves, words[i] == words[j].\n For example, words[i] = \"zzxy\" and words[j] = \"xyzz\" are special-equivalent because we may make the moves \"zzxy\" -> \"xzzy\" -> \"xyzz\".\n A group of special-equivalent strings from words is a non-empty subset of words such that:\n Every pair of strings in the group are special equivalent, and\n The 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).\n Return the number of groups of special-equivalent strings from words.\n Example 1:\n Input: words = [\"abcd\",\"cdab\",\"cbad\",\"xyzz\",\"zzxy\",\"zzyx\"]\n Output: 3\n Explanation: \n One 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.\n The other two groups are [\"xyzz\", \"zzxy\"] and [\"zzyx\"].\n Note that in particular, \"zzxy\" is not special equivalent to \"zzyx\".\n Example 2:\n Input: words = [\"abc\",\"acb\",\"bac\",\"bca\",\"cab\",\"cba\"]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 894, - "title": "All Possible Full Binary Trees", - "question": "class Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n \"\"\"\n 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.\n Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.\n A full binary tree is a binary tree where each node has exactly 0 or 2 children.\n Example 1:\n Input: n = 7\n Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]\n Example 2:\n Input: n = 3\n Output: [[0,0,0]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 895, - "title": "Maximum Frequency Stack", - "question": "class FreqStack:\n def __init__(self):\n def push(self, val: int) -> None:\n def pop(self) -> int:\n \"\"\"\n Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.\n Implement the FreqStack class:\n FreqStack() constructs an empty frequency stack.\n void push(int val) pushes an integer val onto the top of the stack.\n int pop() removes and returns the most frequent element in the stack.\n If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.\n Example 1:\n Input\n [\"FreqStack\", \"push\", \"push\", \"push\", \"push\", \"push\", \"push\", \"pop\", \"pop\", \"pop\", \"pop\"]\n [[], [5], [7], [5], [7], [4], [5], [], [], [], []]\n Output\n [null, null, null, null, null, null, null, 5, 7, 5, 4]\n Explanation\n FreqStack freqStack = new FreqStack();\n freqStack.push(5); // The stack is [5]\n freqStack.push(7); // The stack is [5,7]\n freqStack.push(5); // The stack is [5,7,5]\n freqStack.push(7); // The stack is [5,7,5,7]\n freqStack.push(4); // The stack is [5,7,5,7,4]\n freqStack.push(5); // The stack is [5,7,5,7,4,5]\n freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].\n freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].\n freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes [5,7,4].\n freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 896, - "title": "Monotonic Array", - "question": "class Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n \"\"\"\n An array is monotonic if it is either monotone increasing or monotone decreasing.\n An 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].\n Given an integer array nums, return true if the given array is monotonic, or false otherwise.\n Example 1:\n Input: nums = [1,2,2,3]\n Output: true\n Example 2:\n Input: nums = [6,5,4,4]\n Output: true\n Example 3:\n Input: nums = [1,3,2]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 897, - "title": "Increasing Order Search Tree", - "question": "class Solution:\n def increasingBST(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 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:\n Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]\n Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]\n Example 2:\n Input: root = [5,1,7]\n Output: [1,null,5,null,7]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 898, - "title": "Bitwise ORs of Subarrays", - "question": "class Solution:\n def subarrayBitwiseORs(self, arr: List[int]) -> int:\n \"\"\"\n Given an integer array arr, return the number of distinct bitwise ORs of all the non-empty subarrays of arr.\n The 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.\n A subarray is a contiguous non-empty sequence of elements within an array.\n Example 1:\n Input: arr = [0]\n Output: 1\n Explanation: There is only one possible result: 0.\n Example 2:\n Input: arr = [1,1,2]\n Output: 3\n Explanation: The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].\n These yield the results 1, 1, 2, 1, 3, 3.\n There are 3 unique values, so the answer is 3.\n Example 3:\n Input: arr = [1,2,4]\n Output: 6\n Explanation: The possible results are 1, 2, 3, 4, 6, and 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 899, - "title": "Orderly Queue", - "question": "class Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n \"\"\"\n 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..\n Return the lexicographically smallest string you could have after applying the mentioned step any number of moves.\n Example 1:\n Input: s = \"cba\", k = 1\n Output: \"acb\"\n Explanation: \n In the first move, we move the 1st character 'c' to the end, obtaining the string \"bac\".\n In the second move, we move the 1st character 'b' to the end, obtaining the final result \"acb\".\n Example 2:\n Input: s = \"baaca\", k = 3\n Output: \"aaabc\"\n Explanation: \n In the first move, we move the 1st character 'b' to the end, obtaining the string \"aacab\".\n In the second move, we move the 3rd character 'c' to the end, obtaining the final result \"aaabc\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 900, - "title": "RLE Iterator", - "question": "class RLEIterator:\n def __init__(self, encoding: List[int]):\n def next(self, n: int) -> int:\n \"\"\"\n We can use run-length encoding (i.e., RLE) to encode a sequence of integers. In a run-length encoded array of even length encoding (0-indexed), for all even i, encoding[i] tells us the number of times that the non-negative integer value encoding[i + 1] is repeated in the sequence.\n For example, the sequence arr = [8,8,8,5,5] can be encoded to be encoding = [3,8,2,5]. encoding = [3,8,0,9,2,5] and encoding = [2,8,1,8,2,5] are also valid RLE of arr.\n Given a run-length encoded array, design an iterator that iterates through it.\n Implement the RLEIterator class:\n RLEIterator(int[] encoded) Initializes the object with the encoded array encoded.\n int next(int n) Exhausts the next n elements and returns the last element exhausted in this way. If there is no element left to exhaust, return -1 instead.\n Example 1:\n Input\n [\"RLEIterator\", \"next\", \"next\", \"next\", \"next\"]\n [[[3, 8, 0, 9, 2, 5]], [2], [1], [1], [2]]\n Output\n [null, 8, 8, 5, -1]\n Explanation\n RLEIterator rLEIterator = new RLEIterator([3, 8, 0, 9, 2, 5]); // This maps to the sequence [8,8,8,5,5].\n rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now [8, 5, 5].\n rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now [5, 5].\n rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now [5].\n rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5,\n but the second term did not exist. Since the last term exhausted does not exist, we return -1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 901, - "title": "Online Stock Span", - "question": "class StockSpanner:\n def __init__(self):\n def next(self, price: int) -> int:\n \"\"\"\n Design an algorithm that collects daily price quotes for some stock and returns the span of that stock's price for the current day.\n The span of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.\n For example, if the prices of the stock in the last four days is [7,2,1,2] and the price of the stock today is 2, then the span of today is 4 because starting from today, the price of the stock was less than or equal 2 for 4 consecutive days.\n Also, if the prices of the stock in the last four days is [7,34,1,2] and the price of the stock today is 8, then the span of today is 3 because starting from today, the price of the stock was less than or equal 8 for 3 consecutive days.\n Implement the StockSpanner class:\n StockSpanner() Initializes the object of the class.\n int next(int price) Returns the span of the stock's price given that today's price is price.\n Example 1:\n Input\n [\"StockSpanner\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\", \"next\"]\n [[], [100], [80], [60], [70], [60], [75], [85]]\n Output\n [null, 1, 1, 1, 2, 1, 4, 6]\n Explanation\n StockSpanner stockSpanner = new StockSpanner();\n stockSpanner.next(100); // return 1\n stockSpanner.next(80); // return 1\n stockSpanner.next(60); // return 1\n stockSpanner.next(70); // return 2\n stockSpanner.next(60); // return 1\n stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.\n stockSpanner.next(85); // return 6\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 902, - "title": "Numbers At Most N Given Digit Set", - "question": "class Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n \"\"\"\n Given an array of digits which is sorted in non-decreasing order. You can write numbers using each digits[i] as many times as we want. For example, if digits = ['1','3','5'], we may write numbers such as '13', '551', and '1351315'.\n Return the number of positive integers that can be generated that are less than or equal to a given integer n.\n Example 1:\n Input: digits = [\"1\",\"3\",\"5\",\"7\"], n = 100\n Output: 20\n Explanation: \n The 20 numbers that can be written are:\n 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.\n Example 2:\n Input: digits = [\"1\",\"4\",\"9\"], n = 1000000000\n Output: 29523\n Explanation: \n We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers,\n 81 four digit numbers, 243 five digit numbers, 729 six digit numbers,\n 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers.\n In total, this is 29523 integers that can be written using the digits array.\n Example 3:\n Input: digits = [\"7\"], n = 8\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 903, - "title": "Valid Permutations for DI Sequence", - "question": "class Solution:\n def numPermsDISequence(self, s: str) -> int:\n \"\"\"\n You are given a string s of length n where s[i] is either:\n 'D' means decreasing, or\n 'I' means increasing.\n A 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:\n If s[i] == 'D', then perm[i] > perm[i + 1], and\n If s[i] == 'I', then perm[i] < perm[i + 1].\n Return the number of valid permutations perm. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\n Input: s = \"DID\"\n Output: 5\n Explanation: The 5 valid permutations of (0, 1, 2, 3) are:\n (1, 0, 3, 2)\n (2, 0, 3, 1)\n (2, 1, 3, 0)\n (3, 0, 2, 1)\n (3, 1, 2, 0)\n Example 2:\n Input: s = \"D\"\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 904, - "title": "Fruit Into Baskets", - "question": "class Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n \"\"\"\n 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.\n You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:\n You 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.\n Starting 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.\n Once you reach a tree with fruit that cannot fit in your baskets, you must stop.\n Given the integer array fruits, return the maximum number of fruits you can pick.\n Example 1:\n Input: fruits = [1,2,1]\n Output: 3\n Explanation: We can pick from all 3 trees.\n Example 2:\n Input: fruits = [0,1,2,2]\n Output: 3\n Explanation: We can pick from trees [1,2,2].\n If we had started at the first tree, we would only pick from trees [0,1].\n Example 3:\n Input: fruits = [1,2,3,2,2]\n Output: 4\n Explanation: We can pick from trees [2,3,2,2].\n If we had started at the first tree, we would only pick from trees [1,2].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 905, - "title": "Sort Array By Parity", - "question": "class Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n \"\"\"\n Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.\n Return any array that satisfies this condition.\n Example 1:\n Input: nums = [3,1,2,4]\n Output: [2,4,3,1]\n Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.\n Example 2:\n Input: nums = [0]\n Output: [0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 906, - "title": "Super Palindromes", - "question": "class Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n \"\"\"\n Let's say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.\n Given 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:\n Input: left = \"4\", right = \"1000\"\n Output: 4\n Explanation: 4, 9, 121, and 484 are superpalindromes.\n Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.\n Example 2:\n Input: left = \"1\", right = \"2\"\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 907, - "title": "Sum of Subarray Minimums", - "question": "class Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n \"\"\"\n 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:\n Input: arr = [3,1,2,4]\n Output: 17\n Explanation: \n Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. \n Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.\n Sum is 17.\n Example 2:\n Input: arr = [11,81,94,43,3]\n Output: 444\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 908, - "title": "Smallest Range I", - "question": "class Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an integer array nums and an integer k.\n In 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.\n The score of nums is the difference between the maximum and minimum elements in nums.\n Return the minimum score of nums after applying the mentioned operation at most once for each index in it.\n Example 1:\n Input: nums = [1], k = 0\n Output: 0\n Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n Example 2:\n Input: nums = [0,10], k = 2\n Output: 6\n Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n Example 3:\n Input: nums = [1,3,6], k = 3\n Output: 0\n Explanation: Change nums to be [4, 4, 4]. The score is max(nums) - min(nums) = 4 - 4 = 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 909, - "title": "Snakes and Ladders", - "question": "class Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n \"\"\"\n 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.\n You start on square 1 of the board. In each move, starting from square curr, do the following:\n Choose a destination square next with a label in the range [curr + 1, min(curr + 6, n2)].\n This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board.\n If next has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to next.\n The game ends when you reach the square n2.\n A 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.\n Note 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.\n For example, suppose the board is [[-1,4],[-1,3]], and on the first move, your destination square is 2. You follow the ladder to square 3, but do not follow the subsequent ladder to 4.\n Return 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:\n Input: 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]]\n Output: 4\n Explanation: \n In the beginning, you start at square 1 (at row 5, column 0).\n You decide to move to square 2 and must take the ladder to square 15.\n You then decide to move to square 17 and must take the snake to square 13.\n You then decide to move to square 14 and must take the ladder to square 35.\n You then decide to move to square 36, ending the game.\n This is the lowest possible number of moves to reach the last square, so return 4.\n Example 2:\n Input: board = [[-1,-1],[-1,3]]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 910, - "title": "Smallest Range II", - "question": "class Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an integer array nums and an integer k.\n For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.\n The score of nums is the difference between the maximum and minimum elements in nums.\n Return the minimum score of nums after changing the values at each index.\n Example 1:\n Input: nums = [1], k = 0\n Output: 0\n Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.\n Example 2:\n Input: nums = [0,10], k = 2\n Output: 6\n Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.\n Example 3:\n Input: nums = [1,3,6], k = 3\n Output: 3\n Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 911, - "title": "Online Election", - "question": "class TopVotedCandidate:\n def __init__(self, persons: List[int], times: List[int]):\n def q(self, t: int) -> int:\n \"\"\"\n You are given two integer arrays persons and times. In an election, the ith vote was cast for persons[i] at time times[i].\n For each query at a time t, find the person that was leading the election at time t. Votes cast at time t will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins.\n Implement the TopVotedCandidate class:\n TopVotedCandidate(int[] persons, int[] times) Initializes the object with the persons and times arrays.\n int q(int t) Returns the number of the person that was leading the election at time t according to the mentioned rules.\n Example 1:\n Input\n [\"TopVotedCandidate\", \"q\", \"q\", \"q\", \"q\", \"q\", \"q\"]\n [[[0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]], [3], [12], [25], [15], [24], [8]]\n Output\n [null, 0, 1, 1, 0, 0, 1]\n Explanation\n TopVotedCandidate topVotedCandidate = new TopVotedCandidate([0, 1, 1, 0, 0, 1, 0], [0, 5, 10, 15, 20, 25, 30]);\n topVotedCandidate.q(3); // return 0, At time 3, the votes are [0], and 0 is leading.\n topVotedCandidate.q(12); // return 1, At time 12, the votes are [0,1,1], and 1 is leading.\n topVotedCandidate.q(25); // return 1, At time 25, the votes are [0,1,1,0,0,1], and 1 is leading (as ties go to the most recent vote.)\n topVotedCandidate.q(15); // return 0\n topVotedCandidate.q(24); // return 0\n topVotedCandidate.q(8); // return 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 912, - "title": "Sort an Array", - "question": "class Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n \"\"\"\n Given an array of integers nums, sort the array in ascending order and return it.\n You 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:\n Input: nums = [5,2,3,1]\n Output: [1,2,3,5]\n Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).\n Example 2:\n Input: nums = [5,1,1,2,0,0]\n Output: [0,0,1,1,2,5]\n Explanation: Note that the values of nums are not necessairly unique.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 913, - "title": "Cat and Mouse", - "question": "class Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n \"\"\"\n A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns.\n The graph is given as follows: graph[a] is a list of all nodes b such that ab is an edge of the graph.\n The mouse starts at node 1 and goes first, the cat starts at node 2 and goes second, and there is a hole at node 0.\n During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in graph[1].\n Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)\n Then, the game can end in three ways:\n If ever the Cat occupies the same node as the Mouse, the Cat wins.\n If ever the Mouse reaches the Hole, the Mouse wins.\n If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.\n Given a graph, and assuming both players play optimally, return\n 1 if the mouse wins the game,\n 2 if the cat wins the game, or\n 0 if the game is a draw.\n Example 1:\n Input: graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\n Output: 0\n Example 2:\n Input: graph = [[1,3],[0],[3],[0,2]]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 914, - "title": "X of a Kind in a Deck of Cards", - "question": "class Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \"\"\"\n You are given an integer array deck where deck[i] represents the number written on the ith card.\n Partition the cards into one or more groups such that:\n Each group has exactly x cards where x > 1, and\n All the cards in one group have the same integer written on them.\n Return true if such partition is possible, or false otherwise.\n Example 1:\n Input: deck = [1,2,3,4,4,3,2,1]\n Output: true\n Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].\n Example 2:\n Input: deck = [1,1,1,2,2,2,3,3]\n Output: false\n Explanation: No possible partition.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 915, - "title": "Partition Array into Disjoint Intervals", - "question": "class Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, partition it into two (contiguous) subarrays left and right so that:\n Every element in left is less than or equal to every element in right.\n left and right are non-empty.\n left has the smallest possible size.\n Return the length of left after such a partitioning.\n Test cases are generated such that partitioning exists.\n Example 1:\n Input: nums = [5,0,3,8,6]\n Output: 3\n Explanation: left = [5,0,3], right = [8,6]\n Example 2:\n Input: nums = [1,1,1,0,6,12]\n Output: 4\n Explanation: left = [1,1,1,0], right = [6,12]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 916, - "title": "Word Subsets", - "question": "class Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n \"\"\"\n You are given two string arrays words1 and words2.\n A string b is a subset of string a if every letter in b occurs in a including multiplicity.\n For example, \"wrr\" is a subset of \"warrior\" but is not a subset of \"world\".\n A string a from words1 is universal if for every string b in words2, b is a subset of a.\n Return an array of all the universal strings in words1. You may return the answer in any order.\n Example 1:\n Input: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"e\",\"o\"]\n Output: [\"facebook\",\"google\",\"leetcode\"]\n Example 2:\n Input: words1 = [\"amazon\",\"apple\",\"facebook\",\"google\",\"leetcode\"], words2 = [\"l\",\"e\"]\n Output: [\"apple\",\"google\",\"leetcode\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 917, - "title": "Reverse Only Letters", - "question": "class Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n \"\"\"\n Given a string s, reverse the string according to the following rules:\n All the characters that are not English letters remain in the same position.\n All the English letters (lowercase or uppercase) should be reversed.\n Return s after reversing it.\n Example 1:\n Input: s = \"ab-cd\"\n Output: \"dc-ba\"\n Example 2:\n Input: s = \"a-bC-dEf-ghIj\"\n Output: \"j-Ih-gfE-dCba\"\n Example 3:\n Input: s = \"Test1ng-Leet=code-Q!\"\n Output: \"Qedo1ct-eeLg=ntse-T!\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 918, - "title": "Maximum Sum Circular Subarray", - "question": "class Solution:\n def maxSubarraySumCircular(self, nums: List[int]) -> int:\n \"\"\"\n Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.\n A 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].\n A 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:\n Input: nums = [1,-2,3,-2]\n Output: 3\n Explanation: Subarray [3] has maximum sum 3.\n Example 2:\n Input: nums = [5,-3,5]\n Output: 10\n Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10.\n Example 3:\n Input: nums = [-3,-2,-3]\n Output: -2\n Explanation: Subarray [-2] has maximum sum -2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 919, - "title": "Complete Binary Tree Inserter", - "question": "class CBTInserter:\n def __init__(self, root: Optional[TreeNode]):\n def insert(self, val: int) -> int:\n def get_root(self) -> Optional[TreeNode]:\n \"\"\"\n A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.\n Design an algorithm to insert a new node to a complete binary tree keeping it complete after the insertion.\n Implement the CBTInserter class:\n CBTInserter(TreeNode root) Initializes the data structure with the root of the complete binary tree.\n int insert(int v) Inserts a TreeNode into the tree with value Node.val == val so that the tree remains complete, and returns the value of the parent of the inserted TreeNode.\n TreeNode get_root() Returns the root node of the tree.\n Example 1:\n Input\n [\"CBTInserter\", \"insert\", \"insert\", \"get_root\"]\n [[[1, 2]], [3], [4], []]\n Output\n [null, 1, 2, [1, 2, 3, 4]]\n Explanation\n CBTInserter cBTInserter = new CBTInserter([1, 2]);\n cBTInserter.insert(3); // return 1\n cBTInserter.insert(4); // return 2\n cBTInserter.get_root(); // return [1, 2, 3, 4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 920, - "title": "Number of Music Playlists", - "question": "class Solution:\n def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:\n \"\"\"\n 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:\n Every song is played at least once.\n A song can only be played again only if k other songs have been played.\n Given 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:\n Input: n = 3, goal = 3, k = 1\n Output: 6\n Explanation: There are 6 possible playlists: [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], and [3, 2, 1].\n Example 2:\n Input: n = 2, goal = 3, k = 0\n Output: 6\n Explanation: There are 6 possible playlists: [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2, 1], [2, 1, 2], and [1, 2, 2].\n Example 3:\n Input: n = 2, goal = 3, k = 1\n Output: 2\n Explanation: There are 2 possible playlists: [1, 2, 1] and [2, 1, 2].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 921, - "title": "Minimum Add to Make Parentheses Valid", - "question": "class Solution:\n def minAddToMakeValid(self, s: str) -> int:\n \"\"\"\n A parentheses string is valid if and only if:\n It is the empty string,\n It can be written as AB (A concatenated with B), where A and B are valid strings, or\n It can be written as (A), where A is a valid string.\n You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string.\n For example, if s = \"()))\", you can insert an opening parenthesis to be \"(()))\" or a closing parenthesis to be \"())))\".\n Return the minimum number of moves required to make s valid.\n Example 1:\n Input: s = \"())\"\n Output: 1\n Example 2:\n Input: s = \"(((\"\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 922, - "title": "Sort Array By Parity II", - "question": "class Solution:\n def sortArrayByParityII(self, nums: List[int]) -> List[int]:\n \"\"\"\n Given an array of integers nums, half of the integers in nums are odd, and the other half are even.\n Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.\n Return any answer array that satisfies this condition.\n Example 1:\n Input: nums = [4,2,5,7]\n Output: [4,5,2,7]\n Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.\n Example 2:\n Input: nums = [2,3]\n Output: [2,3]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 923, - "title": "3Sum With Multiplicity", - "question": "class Solution:\n def threeSumMulti(self, arr: List[int], target: int) -> int:\n \"\"\"\n 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.\n As the answer can be very large, return it modulo 109 + 7.\n Example 1:\n Input: arr = [1,1,2,2,3,3,4,4,5,5], target = 8\n Output: 20\n Explanation: \n Enumerating by the values (arr[i], arr[j], arr[k]):\n (1, 2, 5) occurs 8 times;\n (1, 3, 4) occurs 8 times;\n (2, 2, 4) occurs 2 times;\n (2, 3, 3) occurs 2 times.\n Example 2:\n Input: arr = [1,1,2,2,2,2], target = 5\n Output: 12\n Explanation: \n arr[i] = 1, arr[j] = arr[k] = 2 occurs 12 times:\n We choose one 1 from [1,1] in 2 ways,\n and two 2s from [2,2,2,2] in 6 ways.\n Example 3:\n Input: arr = [2,1,3], target = 6\n Output: 1\n Explanation: (1, 2, 3) occured one time in the array so we return 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 924, - "title": "Minimize Malware Spread", - "question": "class Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n \"\"\"\n You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.\n Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove exactly one node from initial.\n Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\n Note that if a node was removed from the initial list of infected nodes, it might still be infected later due to the malware spread.\n Example 1:\n Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\n Output: 0\n Example 2:\n Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]\n Output: 0\n Example 3:\n Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 925, - "title": "Long Pressed Name", - "question": "class Solution:\n def isLongPressedName(self, name: str, typed: str) -> bool:\n \"\"\"\n 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.\n You 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:\n Input: name = \"alex\", typed = \"aaleex\"\n Output: true\n Explanation: 'a' and 'e' in 'alex' were long pressed.\n Example 2:\n Input: name = \"saeed\", typed = \"ssaaedd\"\n Output: false\n Explanation: 'e' must have been pressed twice, but it was not in the typed output.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 926, - "title": "Flip String to Monotone Increasing", - "question": "class Solution:\n def minFlipsMonoIncr(self, s: str) -> int:\n \"\"\"\n 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).\n You are given a binary string s. You can flip s[i] changing it from 0 to 1 or from 1 to 0.\n Return the minimum number of flips to make s monotone increasing.\n Example 1:\n Input: s = \"00110\"\n Output: 1\n Explanation: We flip the last digit to get 00111.\n Example 2:\n Input: s = \"010110\"\n Output: 2\n Explanation: We flip to get 011111, or alternatively 000111.\n Example 3:\n Input: s = \"00011000\"\n Output: 2\n Explanation: We flip to get 00000000.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 927, - "title": "Three Equal Parts", - "question": "class Solution:\n def threeEqualParts(self, arr: List[int]) -> List[int]:\n \"\"\"\n You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.\n If it is possible, return any [i, j] with i + 1 < j, such that:\n arr[0], arr[1], ..., arr[i] is the first part,\n arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and\n arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.\n All three parts have equal binary values.\n If it is not possible, return [-1, -1].\n Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.\n Example 1:\n Input: arr = [1,0,1,0,1]\n Output: [0,3]\n Example 2:\n Input: arr = [1,1,0,1,1]\n Output: [-1,-1]\n Example 3:\n Input: arr = [1,1,0,0,1]\n Output: [0,2]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 928, - "title": "Minimize Malware Spread II", - "question": "class Solution:\n def minMalwareSpread(self, graph: List[List[int]], initial: List[int]) -> int:\n \"\"\"\n You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.\n Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.\n Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.\n We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.\n Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.\n Example 1:\n Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]\n Output: 0\n Example 2:\n Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]\n Output: 1\n Example 3:\n Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 929, - "title": "Unique Email Addresses", - "question": "class Solution:\n def numUniqueEmails(self, emails: List[str]) -> int:\n \"\"\"\n 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 '+'.\n For example, in \"alice@leetcode.com\", \"alice\" is the local name, and \"leetcode.com\" is the domain name.\n If 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.\n For example, \"alice.z@leetcode.com\" and \"alicez@leetcode.com\" forward to the same email address.\n If 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.\n For example, \"m.y+name@email.com\" will be forwarded to \"my@email.com\".\n It is possible to use both of these rules at the same time.\n Given 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:\n Input: emails = [\"test.email+alex@leetcode.com\",\"test.e.mail+bob.cathy@leetcode.com\",\"testemail+david@lee.tcode.com\"]\n Output: 2\n Explanation: \"testemail@leetcode.com\" and \"testemail@lee.tcode.com\" actually receive mails.\n Example 2:\n Input: emails = [\"a@leetcode.com\",\"b@leetcode.com\",\"c@leetcode.com\"]\n Output: 3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 930, - "title": "Binary Subarrays With Sum", - "question": "class Solution:\r\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n \"\"\"\n Given a binary array nums and an integer goal, return the number of non-empty subarrays with a sum goal.\r\n A subarray is a contiguous part of the array.\r\n Example 1:\r\n Input: nums = [1,0,1,0,1], goal = 2\r\n Output: 4\r\n Explanation: The 4 subarrays are bolded and underlined below:\r\n [1,0,1,0,1]\r\n [1,0,1,0,1]\r\n [1,0,1,0,1]\r\n [1,0,1,0,1]\r\n Example 2:\r\n Input: nums = [0,0,0,0,0], goal = 0\r\n Output: 15\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 931, - "title": "Minimum Falling Path Sum", - "question": "class Solution:\n def minFallingPathSum(self, matrix: List[List[int]]) -> int:\n \"\"\"\n Given an n x n array of integers matrix, return the minimum sum of any falling path through matrix.\n A 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:\n Input: matrix = [[2,1,3],[6,5,4],[7,8,9]]\n Output: 13\n Explanation: There are two falling paths with a minimum sum as shown.\n Example 2:\n Input: matrix = [[-19,57],[-40,-5]]\n Output: -59\n Explanation: The falling path with a minimum sum is shown.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 932, - "title": "Beautiful Array", - "question": "class Solution:\n def beautifulArray(self, n: int) -> List[int]:\n \"\"\"\n An array nums of length n is beautiful if:\n nums is a permutation of the integers in the range [1, n].\n For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j].\n Given 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:\n Input: n = 4\n Output: [2,1,4,3]\n Example 2:\n Input: n = 5\n Output: [3,1,2,5,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 933, - "title": "Number of Recent Calls", - "question": "class RecentCounter:\n def __init__(self):\n def ping(self, t: int) -> int:\n \"\"\"\n You have a RecentCounter class which counts the number of recent requests within a certain time frame.\n Implement the RecentCounter class:\n RecentCounter() Initializes the counter with zero recent requests.\n int ping(int t) Adds a new request at time t, where t represents some time in milliseconds, and returns the number of requests that has happened in the past 3000 milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].\n It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.\n Example 1:\n Input\n [\"RecentCounter\", \"ping\", \"ping\", \"ping\", \"ping\"]\n [[], [1], [100], [3001], [3002]]\n Output\n [null, 1, 2, 3, 3]\n Explanation\n RecentCounter recentCounter = new RecentCounter();\n recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1\n recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2\n recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3\n recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 934, - "title": "Shortest Bridge", - "question": "class Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an n x n binary matrix grid where 1 represents land and 0 represents water.\n An island is a 4-directionally connected group of 1's not connected to any other 1's. There are exactly two islands in grid.\n You may change 0's to 1's to connect the two islands to form one island.\n Return the smallest number of 0's you must flip to connect the two islands.\n Example 1:\n Input: grid = [[0,1],[1,0]]\n Output: 1\n Example 2:\n Input: grid = [[0,1,0],[0,0,0],[0,0,1]]\n Output: 2\n Example 3:\n Input: 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]]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 935, - "title": "Knight Dialer", - "question": "class Solution:\n def knightDialer(self, n: int) -> int:\n \"\"\"\n 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 diagaram:\n A chess knight can move as indicated in the chess diagram below:\n We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell).\n Given an integer n, return how many distinct phone numbers of length n we can dial.\n You 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.\n As the answer may be very large, return the answer modulo 109 + 7.\n Example 1:\n Input: n = 1\n Output: 10\n Explanation: We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.\n Example 2:\n Input: n = 2\n Output: 20\n Explanation: All the valid number we can dial are [04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94]\n Example 3:\n Input: n = 3131\n Output: 136006598\n Explanation: Please take care of the mod.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 936, - "title": "Stamping The Sequence", - "question": "class Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n \"\"\"\n You are given two strings stamp and target. Initially, there is a string s of length target.length with all s[i] == '?'.\n In one turn, you can place stamp over s and replace every letter in the s with the corresponding letter from stamp.\n For example, if stamp = \"abc\" and target = \"abcba\", then s is \"?????\" initially. In one turn you can:\n place stamp at index 0 of s to obtain \"abc??\",\n place stamp at index 1 of s to obtain \"?abc?\", or\n place stamp at index 2 of s to obtain \"??abc\".\n Note 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).\n We want to convert s to target using at most 10 * target.length turns.\n Return 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:\n Input: stamp = \"abc\", target = \"ababc\"\n Output: [0,2]\n Explanation: Initially s = \"?????\".\n - Place stamp at index 0 to get \"abc??\".\n - Place stamp at index 2 to get \"ababc\".\n [1,0,2] would also be accepted as an answer, as well as some other answers.\n Example 2:\n Input: stamp = \"abca\", target = \"aabcaca\"\n Output: [3,0,1]\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 937, - "title": "Reorder Data in Log Files", - "question": "class Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n \"\"\"\n You are given an array of logs. Each log is a space-delimited string of words, where the first word is the identifier.\n There are two types of logs:\n Letter-logs: All words (except the identifier) consist of lowercase English letters.\n Digit-logs: All words (except the identifier) consist of digits.\n Reorder these logs so that:\n The letter-logs come before all digit-logs.\n The letter-logs are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.\n The digit-logs maintain their relative ordering.\n Return the final order of the logs.\n Example 1:\n Input: logs = [\"dig1 8 1 5 1\",\"let1 art can\",\"dig2 3 6\",\"let2 own kit dig\",\"let3 art zero\"]\n Output: [\"let1 art can\",\"let3 art zero\",\"let2 own kit dig\",\"dig1 8 1 5 1\",\"dig2 3 6\"]\n Explanation:\n The letter-log contents are all different, so their ordering is \"art can\", \"art zero\", \"own kit dig\".\n The digit-logs have a relative order of \"dig1 8 1 5 1\", \"dig2 3 6\".\n Example 2:\n Input: logs = [\"a1 9 2 3 1\",\"g1 act car\",\"zo4 4 7\",\"ab1 off key dog\",\"a8 act zoo\"]\n Output: [\"g1 act car\",\"a8 act zoo\",\"ab1 off key dog\",\"a1 9 2 3 1\",\"zo4 4 7\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 938, - "title": "Range Sum of BST", - "question": "class Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n \"\"\"\n 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:\n Input: root = [10,5,15,3,7,null,18], low = 7, high = 15\n Output: 32\n Explanation: Nodes 7, 10, and 15 are in the range [7, 15]. 7 + 10 + 15 = 32.\n Example 2:\n Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10\n Output: 23\n Explanation: Nodes 6, 7, and 10 are in the range [6, 10]. 6 + 7 + 10 = 23.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 939, - "title": "Minimum Area Rectangle", - "question": "class Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n \"\"\"\n You are given an array of points in the X-Y plane points where points[i] = [xi, yi].\n Return 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:\n Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\n Output: 4\n Example 2:\n Input: points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 940, - "title": "Distinct Subsequences II", - "question": "class Solution:\n def distinctSubseqII(self, s: str) -> int:\n \"\"\"\n 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.\n A 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:\n Input: s = \"abc\"\n Output: 7\n Explanation: The 7 distinct subsequences are \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", and \"abc\".\n Example 2:\n Input: s = \"aba\"\n Output: 6\n Explanation: The 6 distinct subsequences are \"a\", \"b\", \"ab\", \"aa\", \"ba\", and \"aba\".\n Example 3:\n Input: s = \"aaa\"\n Output: 3\n Explanation: The 3 distinct subsequences are \"a\", \"aa\" and \"aaa\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 941, - "title": "Valid Mountain Array", - "question": "class Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n \"\"\"\n Given an array of integers arr, return true if and only if it is a valid mountain array.\n Recall that arr is a mountain array if and only if:\n arr.length >= 3\n There exists some i with 0 < i < arr.length - 1 such that:\n arr[0] < arr[1] < ... < arr[i - 1] < arr[i] \n arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n Example 1:\n Input: arr = [2,1]\n Output: false\n Example 2:\n Input: arr = [3,5,5]\n Output: false\n Example 3:\n Input: arr = [0,3,2,1]\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 942, - "title": "DI String Match", - "question": "class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n \"\"\"\n 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:\n s[i] == 'I' if perm[i] < perm[i + 1], and\n s[i] == 'D' if perm[i] > perm[i + 1].\n Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return any of them.\n Example 1:\n Input: s = \"IDID\"\n Output: [0,4,1,3,2]\n Example 2:\n Input: s = \"III\"\n Output: [0,1,2,3]\n Example 3:\n Input: s = \"DDI\"\n Output: [3,2,0,1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 943, - "title": "Find the Shortest Superstring", - "question": "class Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n \"\"\"\n Given an array of strings words, return the smallest string that contains each string in words as a substring. If there are multiple valid strings of the smallest length, return any of them.\n You may assume that no string in words is a substring of another string in words.\n Example 1:\n Input: words = [\"alex\",\"loves\",\"leetcode\"]\n Output: \"alexlovesleetcode\"\n Explanation: All permutations of \"alex\",\"loves\",\"leetcode\" would also be accepted.\n Example 2:\n Input: words = [\"catg\",\"ctaagt\",\"gcta\",\"ttca\",\"atgcatc\"]\n Output: \"gctaagttcatgcatc\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 944, - "title": "Delete Columns to Make Sorted", - "question": "class Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n \"\"\"\n You are given an array of n strings strs, all of the same length.\n The strings can be arranged such that there is one on each line, making a grid.\n For example, strs = [\"abc\", \"bce\", \"cae\"] can be arranged as follows:\n abc\n bce\n cae\n You 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.\n Return the number of columns that you will delete.\n Example 1:\n Input: strs = [\"cba\",\"daf\",\"ghi\"]\n Output: 1\n Explanation: The grid looks as follows:\n cba\n daf\n ghi\n Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column.\n Example 2:\n Input: strs = [\"a\",\"b\"]\n Output: 0\n Explanation: The grid looks as follows:\n a\n b\n Column 0 is the only column and is sorted, so you will not delete any columns.\n Example 3:\n Input: strs = [\"zyx\",\"wvu\",\"tsr\"]\n Output: 3\n Explanation: The grid looks as follows:\n zyx\n wvu\n tsr\n All 3 columns are not sorted, so you will delete all 3.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 945, - "title": "Minimum Increment to Make Array Unique", - "question": "class Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Return the minimum number of moves to make every value in nums unique.\n The test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\n Input: nums = [1,2,2]\n Output: 1\n Explanation: After 1 move, the array could be [1, 2, 3].\n Example 2:\n Input: nums = [3,2,1,2,1,7]\n Output: 6\n Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].\n It can be shown with 5 or less moves that it is impossible for the array to have all unique values.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 946, - "title": "Validate Stack Sequences", - "question": "class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n \"\"\"\n 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:\n Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]\n Output: true\n Explanation: We might do the following sequence:\n push(1), push(2), push(3), push(4),\n pop() -> 4,\n push(5),\n pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1\n Example 2:\n Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]\n Output: false\n Explanation: 1 cannot be popped before 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 947, - "title": "Most Stones Removed with Same Row or Column", - "question": "class Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n \"\"\"\n On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may have at most one stone.\n A stone can be removed if it shares either the same row or the same column as another stone that has not been removed.\n Given 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:\n Input: stones = [[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]]\n Output: 5\n Explanation: One way to remove 5 stones is as follows:\n 1. Remove stone [2,2] because it shares the same row as [2,1].\n 2. Remove stone [2,1] because it shares the same column as [0,1].\n 3. Remove stone [1,2] because it shares the same row as [1,0].\n 4. Remove stone [1,0] because it shares the same column as [0,0].\n 5. Remove stone [0,1] because it shares the same row as [0,0].\n Stone [0,0] cannot be removed since it does not share a row/column with another stone still on the plane.\n Example 2:\n Input: stones = [[0,0],[0,2],[1,1],[2,0],[2,2]]\n Output: 3\n Explanation: One way to make 3 moves is as follows:\n 1. Remove stone [2,2] because it shares the same row as [2,0].\n 2. Remove stone [2,0] because it shares the same column as [0,0].\n 3. Remove stone [0,2] because it shares the same row as [0,0].\n Stones [0,0] and [1,1] cannot be removed since they do not share a row/column with another stone still on the plane.\n Example 3:\n Input: stones = [[0,0]]\n Output: 0\n Explanation: [0,0] is the only stone on the plane, so you cannot remove it.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 948, - "title": "Bag of Tokens", - "question": "class Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n \"\"\"\n You have an initial power of power, an initial score of 0, and a bag of tokens where tokens[i] is the value of the ith token (0-indexed).\n Your goal is to maximize your total score by potentially playing each token in one of two ways:\n If your current power is at least tokens[i], you may play the ith token face up, losing tokens[i] power and gaining 1 score.\n If your current score is at least 1, you may play the ith token face down, gaining tokens[i] power and losing 1 score.\n Each token may be played at most once and in any order. You do not have to play all the tokens.\n Return the largest possible score you can achieve after playing any number of tokens.\n Example 1:\n Input: tokens = [100], power = 50\n Output: 0\n Explanation: Playing the only token in the bag is impossible because you either have too little power or too little score.\n Example 2:\n Input: tokens = [100,200], power = 150\n Output: 1\n Explanation: Play the 0th token (100) face up, your power becomes 50 and score becomes 1.\n There is no need to play the 1st token since you cannot play it face up to add to your score.\n Example 3:\n Input: tokens = [100,200,300,400], power = 200\n Output: 2\n Explanation: Play the tokens in this order to get a score of 2:\n 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1.\n 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0.\n 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1.\n 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 949, - "title": "Largest Time for Given Digits", - "question": "class Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n \"\"\"\n Given an array arr of 4 digits, find the latest 24-hour time that can be made using each digit exactly once.\n 24-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.\n Return the latest 24-hour time in \"HH:MM\" format. If no valid time can be made, return an empty string.\n Example 1:\n Input: arr = [1,2,3,4]\n Output: \"23:41\"\n Explanation: The valid 24-hour times are \"12:34\", \"12:43\", \"13:24\", \"13:42\", \"14:23\", \"14:32\", \"21:34\", \"21:43\", \"23:14\", and \"23:41\". Of these times, \"23:41\" is the latest.\n Example 2:\n Input: arr = [5,5,5,5]\n Output: \"\"\n Explanation: There are no valid 24-hour times as \"55:55\" is not valid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 950, - "title": "Reveal Cards In Increasing Order", - "question": "class Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n \"\"\"\n 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].\n You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck.\n You will do the following steps repeatedly until all cards are revealed:\n Take the top card of the deck, reveal it, and take it out of the deck.\n If there are still cards in the deck then put the next top card of the deck at the bottom of the deck.\n If there are still unrevealed cards, go back to step 1. Otherwise, stop.\n Return an ordering of the deck that would reveal the cards in increasing order.\n Note that the first entry in the answer is considered to be the top of the deck.\n Example 1:\n Input: deck = [17,13,11,2,3,5,7]\n Output: [2,13,3,11,5,17,7]\n Explanation: \n We get the deck in the order [17,13,11,2,3,5,7] (this order does not matter), and reorder it.\n After reordering, the deck starts as [2,13,3,11,5,17,7], where 2 is the top of the deck.\n We reveal 2, and move 13 to the bottom. The deck is now [3,11,5,17,7,13].\n We reveal 3, and move 11 to the bottom. The deck is now [5,17,7,13,11].\n We reveal 5, and move 17 to the bottom. The deck is now [7,13,11,17].\n We reveal 7, and move 13 to the bottom. The deck is now [11,17,13].\n We reveal 11, and move 17 to the bottom. The deck is now [13,17].\n We reveal 13, and move 17 to the bottom. The deck is now [17].\n We reveal 17.\n Since all the cards revealed are in increasing order, the answer is correct.\n Example 2:\n Input: deck = [1,1000]\n Output: [1,1000]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 951, - "title": "Flip Equivalent Binary Trees", - "question": "class Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n \"\"\"\n For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.\n A 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.\n Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.\n Example 1:\n Input: 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]\n Output: true\n Explanation: We flipped at nodes with values 1, 3, and 5.\n Example 2:\n Input: root1 = [], root2 = []\n Output: true\n Example 3:\n Input: root1 = [], root2 = [1]\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 952, - "title": "Largest Component Size by Common Factor", - "question": "class Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array of unique positive integers nums. Consider the following graph:\n There are nums.length nodes, labeled nums[0] to nums[nums.length - 1],\n There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n Return the size of the largest connected component in the graph.\n Example 1:\n Input: nums = [4,6,15,35]\n Output: 4\n Example 2:\n Input: nums = [20,50,9,63]\n Output: 2\n Example 3:\n Input: nums = [2,3,6,7,4,12,21,39]\n Output: 8\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 953, - "title": "Verifying an Alien Dictionary", - "question": "class Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n \"\"\"\n 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.\n Given 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:\n Input: words = [\"hello\",\"leetcode\"], order = \"hlabcdefgijkmnopqrstuvwxyz\"\n Output: true\n Explanation: As 'h' comes before 'l' in this language, then the sequence is sorted.\n Example 2:\n Input: words = [\"word\",\"world\",\"row\"], order = \"worldabcefghijkmnpqstuvxyz\"\n Output: false\n Explanation: As 'd' comes after 'l' in this language, then words[0] > words[1], hence the sequence is unsorted.\n Example 3:\n Input: words = [\"apple\",\"app\"], order = \"abcdefghijklmnopqrstuvwxyz\"\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 954, - "title": "Array of Doubled Pairs", - "question": "class Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n \"\"\"\n 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:\n Input: arr = [3,1,3,6]\n Output: false\n Example 2:\n Input: arr = [2,1,2,6]\n Output: false\n Example 3:\n Input: arr = [4,-2,2,-4]\n Output: true\n Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 955, - "title": "Delete Columns to Make Sorted II", - "question": "class Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n \"\"\"\n You are given an array of n strings strs, all of the same length.\n We may choose any deletion indices, and we delete all the characters in those indices for each string.\n For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\n Suppose 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:\n Input: strs = [\"ca\",\"bb\",\"ac\"]\n Output: 1\n Explanation: \n After deleting the first column, strs = [\"a\", \"b\", \"c\"].\n Now strs is in lexicographic order (ie. strs[0] <= strs[1] <= strs[2]).\n We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.\n Example 2:\n Input: strs = [\"xc\",\"yb\",\"za\"]\n Output: 0\n Explanation: \n strs is already in lexicographic order, so we do not need to delete anything.\n Note that the rows of strs are not necessarily in lexicographic order:\n i.e., it is NOT necessarily true that (strs[0][0] <= strs[0][1] <= ...)\n Example 3:\n Input: strs = [\"zyx\",\"wvu\",\"tsr\"]\n Output: 3\n Explanation: We have to delete every column.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 956, - "title": "Tallest Billboard", - "question": "class Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n \"\"\"\n You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.\n You are given a collection of rods that can be welded together. For example, if you have rods of lengths 1, 2, and 3, you can weld them together to make a support of length 6.\n Return the largest possible height of your billboard installation. If you cannot support the billboard, return 0.\n Example 1:\n Input: rods = [1,2,3,6]\n Output: 6\n Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.\n Example 2:\n Input: rods = [1,2,3,4,5,6]\n Output: 10\n Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.\n Example 3:\n Input: rods = [1,2]\n Output: 0\n Explanation: The billboard cannot be supported, so we return 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 957, - "title": "Prison Cells After N Days", - "question": "class Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n \"\"\"\n There are 8 prison cells in a row and each cell is either occupied or vacant.\n Each day, whether the cell is occupied or vacant changes according to the following rules:\n If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.\n Otherwise, it becomes vacant.\n Note that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.\n You 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.\n Return the state of the prison after n days (i.e., n such changes described above).\n Example 1:\n Input: cells = [0,1,0,1,1,0,0,1], n = 7\n Output: [0,0,1,1,0,0,0,0]\n Explanation: The following table summarizes the state of the prison on each day:\n Day 0: [0, 1, 0, 1, 1, 0, 0, 1]\n Day 1: [0, 1, 1, 0, 0, 0, 0, 0]\n Day 2: [0, 0, 0, 0, 1, 1, 1, 0]\n Day 3: [0, 1, 1, 0, 0, 1, 0, 0]\n Day 4: [0, 0, 0, 0, 0, 1, 0, 0]\n Day 5: [0, 1, 1, 1, 0, 1, 0, 0]\n Day 6: [0, 0, 1, 0, 1, 1, 0, 0]\n Day 7: [0, 0, 1, 1, 0, 0, 0, 0]\n Example 2:\n Input: cells = [1,0,0,1,0,0,1,0], n = 1000000000\n Output: [0,0,1,1,1,1,1,0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 958, - "title": "Check Completeness of a Binary Tree", - "question": "class Solution:\n def isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n \"\"\"\n Given the root of a binary tree, determine if it is a complete binary tree.\n In 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:\n Input: root = [1,2,3,4,5,6]\n Output: true\n Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.\n Example 2:\n Input: root = [1,2,3,4,5,null,7]\n Output: false\n Explanation: The node with value 7 isn't as far left as possible.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 959, - "title": "Regions Cut By Slashes", - "question": "class Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n \"\"\"\n 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.\n Given the grid grid represented as a string array, return the number of regions.\n Note that backslash characters are escaped, so a '\\' is represented as '\\\\'.\n Example 1:\n Input: grid = [\" /\",\"/ \"]\n Output: 2\n Example 2:\n Input: grid = [\" /\",\" \"]\n Output: 1\n Example 3:\n Input: grid = [\"/\\\\\",\"\\\\/\"]\n Output: 5\n Explanation: Recall that because \\ characters are escaped, \"\\\\/\" refers to \\/, and \"/\\\\\" refers to /\\.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 960, - "title": "Delete Columns to Make Sorted III", - "question": "class Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n \"\"\"\n You are given an array of n strings strs, all of the same length.\n We may choose any deletion indices, and we delete all the characters in those indices for each string.\n For example, if we have strs = [\"abcdef\",\"uvwxyz\"] and deletion indices {0, 2, 3}, then the final array after deletions is [\"bef\", \"vyz\"].\n Suppose we chose a set of deletion indices answer such that after deletions, the final array has every string (row) in lexicographic order. (i.e., (strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1]), and (strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1]), and so on). Return the minimum possible value of answer.length.\n Example 1:\n Input: strs = [\"babca\",\"bbazb\"]\n Output: 3\n Explanation: After deleting columns 0, 1, and 4, the final array is strs = [\"bc\", \"az\"].\n Both these rows are individually in lexicographic order (ie. strs[0][0] <= strs[0][1] and strs[1][0] <= strs[1][1]).\n Note that strs[0] > strs[1] - the array strs is not necessarily in lexicographic order.\n Example 2:\n Input: strs = [\"edcba\"]\n Output: 4\n Explanation: If we delete less than 4 columns, the only row will not be lexicographically sorted.\n Example 3:\n Input: strs = [\"ghi\",\"def\",\"abc\"]\n Output: 0\n Explanation: All rows are already lexicographically sorted.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 961, - "title": "N-Repeated Element in Size 2N Array", - "question": "class Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums with the following properties:\n nums.length == 2 * n.\n nums contains n + 1 unique elements.\n Exactly one element of nums is repeated n times.\n Return the element that is repeated n times.\n Example 1:\n Input: nums = [1,2,3,3]\n Output: 3\n Example 2:\n Input: nums = [2,1,2,5,3,2]\n Output: 2\n Example 3:\n Input: nums = [5,1,5,2,5,3,5,4]\n Output: 5\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 962, - "title": "Maximum Width Ramp", - "question": "class Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Given 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:\n Input: nums = [6,0,8,2,1,5]\n Output: 4\n Explanation: The maximum width ramp is achieved at (i, j) = (1, 5): nums[1] = 0 and nums[5] = 5.\n Example 2:\n Input: nums = [9,8,1,0,1,9,4,0,4,1]\n Output: 7\n Explanation: The maximum width ramp is achieved at (i, j) = (2, 9): nums[2] = 1 and nums[9] = 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 963, - "title": "Minimum Area Rectangle II", - "question": "class Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n \"\"\"\n You are given an array of points in the X-Y plane points where points[i] = [xi, yi].\n Return 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.\n Answers within 10-5 of the actual answer will be accepted.\n Example 1:\n Input: points = [[1,2],[2,1],[1,0],[0,1]]\n Output: 2.00000\n Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.\n Example 2:\n Input: points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\n Output: 1.00000\n Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.\n Example 3:\n Input: points = [[0,3],[1,2],[3,1],[1,3],[2,1]]\n Output: 0\n Explanation: There is no possible rectangle to form from these points.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 964, - "title": "Least Operators to Express Number", - "question": "class Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n \"\"\"\n Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /). For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.\n When writing such an expression, we adhere to the following conventions:\n The division operator (/) returns rational numbers.\n There are no parentheses placed anywhere.\n We use the usual order of operations: multiplication and division happen before addition and subtraction.\n It is not allowed to use the unary negation operator (-). For example, \"x - x\" is a valid expression as it only uses subtraction, but \"-x + x\" is not because it uses negation.\n We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.\n Example 1:\n Input: x = 3, target = 19\n Output: 5\n Explanation: 3 * 3 + 3 * 3 + 3 / 3.\n The expression contains 5 operations.\n Example 2:\n Input: x = 5, target = 501\n Output: 8\n Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.\n The expression contains 8 operations.\n Example 3:\n Input: x = 100, target = 100000000\n Output: 3\n Explanation: 100 * 100 * 100 * 100.\n The expression contains 3 operations.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 965, - "title": "Univalued Binary Tree", - "question": "class Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n \"\"\"\n A binary tree is uni-valued if every node in the tree has the same value.\n Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.\n Example 1:\n Input: root = [1,1,1,1,1,null,1]\n Output: true\n Example 2:\n Input: root = [2,2,2,5,2]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 966, - "title": "Vowel Spellchecker", - "question": "class Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n \"\"\"\n Given a wordlist, we want to implement a spellchecker that converts a query word into a correct word.\n For a given query word, the spell checker handles two categories of spelling mistakes:\n Capitalization: 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.\n Example: wordlist = [\"yellow\"], query = \"YellOw\": correct = \"yellow\"\n Example: wordlist = [\"Yellow\"], query = \"yellow\": correct = \"Yellow\"\n Example: wordlist = [\"yellow\"], query = \"yellow\": correct = \"yellow\"\n Vowel 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.\n Example: wordlist = [\"YellOw\"], query = \"yollow\": correct = \"YellOw\"\n Example: wordlist = [\"YellOw\"], query = \"yeellow\": correct = \"\" (no match)\n Example: wordlist = [\"YellOw\"], query = \"yllw\": correct = \"\" (no match)\n In addition, the spell checker operates under the following precedence rules:\n When the query exactly matches a word in the wordlist (case-sensitive), you should return the same word back.\n When the query matches a word up to capitlization, you should return the first such match in the wordlist.\n When the query matches a word up to vowel errors, you should return the first such match in the wordlist.\n If the query has no matches in the wordlist, you should return the empty string.\n Given some queries, return a list of words answer, where answer[i] is the correct word for query = queries[i].\n Example 1:\n Input: wordlist = [\"KiTe\",\"kite\",\"hare\",\"Hare\"], queries = [\"kite\",\"Kite\",\"KiTe\",\"Hare\",\"HARE\",\"Hear\",\"hear\",\"keti\",\"keet\",\"keto\"]\n Output: [\"kite\",\"KiTe\",\"KiTe\",\"Hare\",\"hare\",\"\",\"\",\"KiTe\",\"\",\"KiTe\"]\n Example 2:\n Input: wordlist = [\"yellow\"], queries = [\"YellOw\"]\n Output: [\"yellow\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 967, - "title": "Numbers With Same Consecutive Differences", - "question": "class Solution:\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n \"\"\"\n 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.\n Note that the integers should not have leading zeros. Integers as 02 and 043 are not allowed.\n Example 1:\n Input: n = 3, k = 7\n Output: [181,292,707,818,929]\n Explanation: Note that 070 is not a valid number, because it has leading zeroes.\n Example 2:\n Input: n = 2, k = 1\n Output: [10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 968, - "title": "Binary Tree Cameras", - "question": "class Solution:\n def minCameraCover(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n Return the minimum number of cameras needed to monitor all nodes of the tree.\n Example 1:\n Input: root = [0,0,null,0,0]\n Output: 1\n Explanation: One camera is enough to monitor all nodes if placed as shown.\n Example 2:\n Input: root = [0,0,null,0,null,0,null,null,0]\n Output: 2\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 969, - "title": "Pancake Sorting", - "question": "class Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n \"\"\"\n Given an array of integers arr, sort the array by performing a series of pancake flips.\n In one pancake flip we do the following steps:\n Choose an integer k where 1 <= k <= arr.length.\n Reverse the sub-array arr[0...k-1] (0-indexed).\n For 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.\n Return 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:\n Input: arr = [3,2,4,1]\n Output: [4,2,4,3]\n Explanation: \n We perform 4 pancake flips, with k values 4, 2, 4, and 3.\n Starting state: arr = [3, 2, 4, 1]\n After 1st flip (k = 4): arr = [1, 4, 2, 3]\n After 2nd flip (k = 2): arr = [4, 1, 2, 3]\n After 3rd flip (k = 4): arr = [3, 2, 1, 4]\n After 4th flip (k = 3): arr = [1, 2, 3, 4], which is sorted.\n Example 2:\n Input: arr = [1,2,3]\n Output: []\n Explanation: The input is already sorted, so there is no need to flip anything.\n Note that other answers, such as [3, 3], would also be accepted.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 970, - "title": "Powerful Integers", - "question": "class Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n \"\"\"\n 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.\n An integer is powerful if it can be represented as xi + yj for some integers i >= 0 and j >= 0.\n You may return the answer in any order. In your answer, each value should occur at most once.\n Example 1:\n Input: x = 2, y = 3, bound = 10\n Output: [2,3,4,5,7,9,10]\n Explanation:\n 2 = 20 + 30\n 3 = 21 + 30\n 4 = 20 + 31\n 5 = 21 + 31\n 7 = 22 + 31\n 9 = 23 + 30\n 10 = 20 + 32\n Example 2:\n Input: x = 3, y = 5, bound = 15\n Output: [2,4,6,8,10,14]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 971, - "title": "Flip Binary Tree To Match Preorder Traversal", - "question": "class Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n \"\"\"\n 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.\n Any 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:\n Flip the smallest number of nodes so that the pre-order traversal of the tree matches voyage.\n Return 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:\n Input: root = [1,2], voyage = [2,1]\n Output: [-1]\n Explanation: It is impossible to flip the nodes such that the pre-order traversal matches voyage.\n Example 2:\n Input: root = [1,2,3], voyage = [1,3,2]\n Output: [1]\n Explanation: Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.\n Example 3:\n Input: root = [1,2,3], voyage = [1,2,3]\n Output: []\n Explanation: The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 972, - "title": "Equal Rational Numbers", - "question": "class Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n \"\"\"\n Given two strings s and t, each of which represents a non-negative rational number, return true if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.\n A 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 \n For example, 12, 0, and 123.\n <.>\n For example, 0.5, 1., 2.12, and 123.0001.\n <.><(><)>\n For example, 0.1(6), 1.(9), 123.00(1212).\n The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:\n 1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66).\n Example 1:\n Input: s = \"0.(52)\", t = \"0.5(25)\"\n Output: true\n Explanation: Because \"0.(52)\" represents 0.52525252..., and \"0.5(25)\" represents 0.52525252525..... , the strings represent the same number.\n Example 2:\n Input: s = \"0.1666(6)\", t = \"0.166(66)\"\n Output: true\n Example 3:\n Input: s = \"0.9(9)\", t = \"1.\"\n Output: true\n Explanation: \"0.9(9)\" represents 0.999999999... repeated forever, which equals 1. [See this link for an explanation.]\n \"1.\" represents the number 1, which is formed correctly: (IntegerPart) = \"1\" and (NonRepeatingPart) = \"\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 509, - "title": "Fibonacci Number", - "question": "class Solution:\n def fib(self, n: int) -> int:\n \"\"\"\n 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,\n F(0) = 0, F(1) = 1\n F(n) = F(n - 1) + F(n - 2), for n > 1.\n Given n, calculate F(n).\n Example 1:\n Input: n = 2\n Output: 1\n Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.\n Example 2:\n Input: n = 3\n Output: 2\n Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.\n Example 3:\n Input: n = 4\n Output: 3\n Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 973, - "title": "K Closest Points to Origin", - "question": "class Solution:\n def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:\n \"\"\"\n 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).\n The distance between two points on the X-Y plane is the Euclidean distance (i.e., \u221a(x1 - x2)2 + (y1 - y2)2).\n You 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:\n Input: points = [[1,3],[-2,2]], k = 1\n Output: [[-2,2]]\n Explanation:\n The distance between (1, 3) and the origin is sqrt(10).\n The distance between (-2, 2) and the origin is sqrt(8).\n Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.\n We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].\n Example 2:\n Input: points = [[3,3],[5,-1],[-2,4]], k = 2\n Output: [[3,3],[-2,4]]\n Explanation: The answer [[-2,4],[3,3]] would also be accepted.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 974, - "title": "Subarray Sums Divisible by K", - "question": "class Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an integer array nums and an integer k, return the number of non-empty subarrays that have a sum divisible by k.\n A subarray is a contiguous part of an array.\n Example 1:\n Input: nums = [4,5,0,-2,-3,1], k = 5\n Output: 7\n Explanation: There are 7 subarrays with a sum divisible by k = 5:\n [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]\n Example 2:\n Input: nums = [5], k = 9\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 975, - "title": "Odd Even Jump", - "question": "class Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n \"\"\"\n You are given an integer array arr. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called odd-numbered jumps, and the (2nd, 4th, 6th, ...) jumps in the series are called even-numbered jumps. Note that the jumps are numbered, not the indices.\n You may jump forward from index i to index j (with i < j) in the following way:\n During odd-numbered jumps (i.e., jumps 1, 3, 5, ...), you jump to the index j such that arr[i] <= arr[j] and arr[j] is the smallest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.\n During even-numbered jumps (i.e., jumps 2, 4, 6, ...), you jump to the index j such that arr[i] >= arr[j] and arr[j] is the largest possible value. If there are multiple such indices j, you can only jump to the smallest such index j.\n It may be the case that for some index i, there are no legal jumps.\n A starting index is good if, starting from that index, you can reach the end of the array (index arr.length - 1) by jumping some number of times (possibly 0 or more than once).\n Return the number of good starting indices.\n Example 1:\n Input: arr = [10,13,12,14,15]\n Output: 2\n Explanation: \n From starting index i = 0, we can make our 1st jump to i = 2 (since arr[2] is the smallest among arr[1], arr[2], arr[3], arr[4] that is greater or equal to arr[0]), then we cannot jump any more.\n From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.\n From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.\n From starting index i = 4, we have reached the end already.\n In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of\n jumps.\n Example 2:\n Input: arr = [2,3,1,1,4]\n Output: 3\n Explanation: \n From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:\n During our 1st jump (odd-numbered), we first jump to i = 1 because arr[1] is the smallest value in [arr[1], arr[2], arr[3], arr[4]] that is greater than or equal to arr[0].\n During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr[2] is the largest value in [arr[2], arr[3], arr[4]] that is less than or equal to arr[1]. arr[3] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3\n During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr[3] is the smallest value in [arr[3], arr[4]] that is greater than or equal to arr[2].\n We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.\n In a similar manner, we can deduce that:\n From starting index i = 1, we jump to i = 4, so we reach the end.\n From starting index i = 2, we jump to i = 3, and then we can't jump anymore.\n From starting index i = 3, we jump to i = 4, so we reach the end.\n From starting index i = 4, we are already at the end.\n In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some\n number of jumps.\n Example 3:\n Input: arr = [5,1,3,4,2]\n Output: 3\n Explanation: We can reach the end from starting indices 1, 2, and 4.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 976, - "title": "Largest Perimeter Triangle", - "question": "class Solution:\n def largestPerimeter(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [2,1,2]\n Output: 5\n Explanation: You can form a triangle with three side lengths: 1, 2, and 2.\n Example 2:\n Input: nums = [1,2,1,10]\n Output: 0\n Explanation: \n You cannot use the side lengths 1, 1, and 2 to form a triangle.\n You cannot use the side lengths 1, 1, and 10 to form a triangle.\n You cannot use the side lengths 1, 2, and 10 to form a triangle.\n As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 977, - "title": "Squares of a Sorted Array", - "question": "class Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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:\n Input: nums = [-4,-1,0,3,10]\n Output: [0,1,9,16,100]\n Explanation: After squaring, the array becomes [16,1,0,9,100].\n After sorting, it becomes [0,1,9,16,100].\n Example 2:\n Input: nums = [-7,-3,2,3,11]\n Output: [4,9,9,49,121]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 978, - "title": "Longest Turbulent Subarray", - "question": "class Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n \"\"\"\n Given an integer array arr, return the length of a maximum size turbulent subarray of arr.\n A subarray is turbulent if the comparison sign flips between each adjacent pair of elements in the subarray.\n More formally, a subarray [arr[i], arr[i + 1], ..., arr[j]] of arr is said to be turbulent if and only if:\n For i <= k < j:\n arr[k] > arr[k + 1] when k is odd, and\n arr[k] < arr[k + 1] when k is even.\n Or, for i <= k < j:\n arr[k] > arr[k + 1] when k is even, and\n arr[k] < arr[k + 1] when k is odd.\n Example 1:\n Input: arr = [9,4,2,10,7,8,8,1,9]\n Output: 5\n Explanation: arr[1] > arr[2] < arr[3] > arr[4] < arr[5]\n Example 2:\n Input: arr = [4,8,12,16]\n Output: 2\n Example 3:\n Input: arr = [100]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 979, - "title": "Distribute Coins in Binary Tree", - "question": "class Solution:\n def distributeCoins(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n In 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.\n Return the minimum number of moves required to make every node have exactly one coin.\n Example 1:\n Input: root = [3,0,0]\n Output: 2\n Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.\n Example 2:\n Input: root = [0,3,0]\n Output: 3\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 980, - "title": "Unique Paths III", - "question": "class Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n integer array grid where grid[i][j] could be:\n 1 representing the starting square. There is exactly one starting square.\n 2 representing the ending square. There is exactly one ending square.\n 0 representing empty squares we can walk over.\n -1 representing obstacles that we cannot walk over.\n Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.\n Example 1:\n Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]\n Output: 2\n Explanation: We have the following two paths: \n 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)\n 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)\n Example 2:\n Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]\n Output: 4\n Explanation: We have the following four paths: \n 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)\n 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)\n 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)\n 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)\n Example 3:\n Input: grid = [[0,1],[2,0]]\n Output: 0\n Explanation: There is no path that walks over every empty square exactly once.\n Note that the starting and ending square can be anywhere in the grid.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 981, - "title": "Time Based Key-Value Store", - "question": "class TimeMap:\n def __init__(self):\n def set(self, key: str, value: str, timestamp: int) -> None:\n def get(self, key: str, timestamp: int) -> str:\n \"\"\"\n Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.\n Implement the TimeMap class:\n TimeMap() Initializes the object of the data structure.\n void set(String key, String value, int timestamp) Stores the key key with the value value at the given time timestamp.\n String get(String key, int timestamp) Returns a value such that set was called previously, with timestamp_prev <= timestamp. If there are multiple such values, it returns the value associated with the largest timestamp_prev. If there are no values, it returns \"\".\n Example 1:\n Input\n [\"TimeMap\", \"set\", \"get\", \"get\", \"set\", \"get\", \"get\"]\n [[], [\"foo\", \"bar\", 1], [\"foo\", 1], [\"foo\", 3], [\"foo\", \"bar2\", 4], [\"foo\", 4], [\"foo\", 5]]\n Output\n [null, null, \"bar\", \"bar\", null, \"bar2\", \"bar2\"]\n Explanation\n TimeMap timeMap = new TimeMap();\n timeMap.set(\"foo\", \"bar\", 1); // store the key \"foo\" and value \"bar\" along with timestamp = 1.\n timeMap.get(\"foo\", 1); // return \"bar\"\n timeMap.get(\"foo\", 3); // return \"bar\", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is \"bar\".\n timeMap.set(\"foo\", \"bar2\", 4); // store the key \"foo\" and value \"bar2\" along with timestamp = 4.\n timeMap.get(\"foo\", 4); // return \"bar2\"\n timeMap.get(\"foo\", 5); // return \"bar2\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 982, - "title": "Triples with Bitwise AND Equal To Zero", - "question": "class Solution:\n def countTriplets(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the number of AND triples.\n An AND triple is a triple of indices (i, j, k) such that:\n 0 <= i < nums.length\n 0 <= j < nums.length\n 0 <= k < nums.length\n nums[i] & nums[j] & nums[k] == 0, where & represents the bitwise-AND operator.\n Example 1:\n Input: nums = [2,1,3]\n Output: 12\n Explanation: We could choose the following i, j, k triples:\n (i=0, j=0, k=1) : 2 & 2 & 1\n (i=0, j=1, k=0) : 2 & 1 & 2\n (i=0, j=1, k=1) : 2 & 1 & 1\n (i=0, j=1, k=2) : 2 & 1 & 3\n (i=0, j=2, k=1) : 2 & 3 & 1\n (i=1, j=0, k=0) : 1 & 2 & 2\n (i=1, j=0, k=1) : 1 & 2 & 1\n (i=1, j=0, k=2) : 1 & 2 & 3\n (i=1, j=1, k=0) : 1 & 1 & 2\n (i=1, j=2, k=0) : 1 & 3 & 2\n (i=2, j=0, k=1) : 3 & 2 & 1\n (i=2, j=1, k=0) : 3 & 1 & 2\n Example 2:\n Input: nums = [0,0,0]\n Output: 27\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 983, - "title": "Minimum Cost For Tickets", - "question": "class Solution:\n def mincostTickets(self, days: List[int], costs: List[int]) -> int:\n \"\"\"\n 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.\n Train tickets are sold in three different ways:\n a 1-day pass is sold for costs[0] dollars,\n a 7-day pass is sold for costs[1] dollars, and\n a 30-day pass is sold for costs[2] dollars.\n The passes allow that many days of consecutive travel.\n For 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.\n Return the minimum number of dollars you need to travel every day in the given list of days.\n Example 1:\n Input: days = [1,4,6,7,8,20], costs = [2,7,15]\n Output: 11\n Explanation: For example, here is one way to buy passes that lets you travel your travel plan:\n On day 1, you bought a 1-day pass for costs[0] = $2, which covered day 1.\n On day 3, you bought a 7-day pass for costs[1] = $7, which covered days 3, 4, ..., 9.\n On day 20, you bought a 1-day pass for costs[0] = $2, which covered day 20.\n In total, you spent $11 and covered all the days of your travel.\n Example 2:\n Input: days = [1,2,3,4,5,6,7,8,9,10,30,31], costs = [2,7,15]\n Output: 17\n Explanation: For example, here is one way to buy passes that lets you travel your travel plan:\n On day 1, you bought a 30-day pass for costs[2] = $15 which covered days 1, 2, ..., 30.\n On day 31, you bought a 1-day pass for costs[0] = $2 which covered day 31.\n In total, you spent $17 and covered all the days of your travel.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 984, - "title": "String Without AAA or BBB", - "question": "class Solution:\n def strWithout3a3b(self, a: int, b: int) -> str:\n \"\"\"\n Given two integers a and b, return any string s such that:\n s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters,\n The substring 'aaa' does not occur in s, and\n The substring 'bbb' does not occur in s.\n Example 1:\n Input: a = 1, b = 2\n Output: \"abb\"\n Explanation: \"abb\", \"bab\" and \"bba\" are all correct answers.\n Example 2:\n Input: a = 4, b = 1\n Output: \"aabaa\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 985, - "title": "Sum of Even Numbers After Queries", - "question": "class Solution:\n def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an integer array nums and an array queries where queries[i] = [vali, indexi].\n For each query i, first, apply nums[indexi] = nums[indexi] + vali, then print the sum of the even values of nums.\n Return an integer array answer where answer[i] is the answer to the ith query.\n Example 1:\n Input: nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]\n Output: [8,6,2,4]\n Explanation: At the beginning, the array is [1,2,3,4].\n After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.\n After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.\n After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.\n After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.\n Example 2:\n Input: nums = [1], queries = [[4,0]]\n Output: [0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 986, - "title": "Interval List Intersections", - "question": "class Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n Return the intersection of these two interval lists.\n A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b.\n The 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:\n Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]]\n Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]\n Example 2:\n Input: firstList = [[1,3],[5,9]], secondList = []\n Output: []\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 987, - "title": "Vertical Order Traversal of a Binary Tree", - "question": "class Solution:\n def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:\n \"\"\"\n Given the root of a binary tree, calculate the vertical order traversal of the binary tree.\n For 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).\n The 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.\n Return the vertical order traversal of the binary tree.\n Example 1:\n Input: root = [3,9,20,null,null,15,7]\n Output: [[9],[3,15],[20],[7]]\n Explanation:\n Column -1: Only node 9 is in this column.\n Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.\n Column 1: Only node 20 is in this column.\n Column 2: Only node 7 is in this column.\n Example 2:\n Input: root = [1,2,3,4,5,6,7]\n Output: [[4],[2],[1,5,6],[3],[7]]\n Explanation:\n Column -2: Only node 4 is in this column.\n Column -1: Only node 2 is in this column.\n Column 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.\n Column 1: Only node 3 is in this column.\n Column 2: Only node 7 is in this column.\n Example 3:\n Input: root = [1,2,3,4,6,5,7]\n Output: [[4],[2],[1,5,6],[3],[7]]\n Explanation:\n This case is the exact same as example 2, but with nodes 5 and 6 swapped.\n Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 988, - "title": "Smallest String Starting From Leaf", - "question": "class Solution:\n def smallestFromLeaf(self, root: Optional[TreeNode]) -> str:\n \"\"\"\n 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'.\n Return the lexicographically smallest string that starts at a leaf of this tree and ends at the root.\n As a reminder, any shorter prefix of a string is lexicographically smaller.\n For example, \"ab\" is lexicographically smaller than \"aba\".\n A leaf of a node is a node that has no children.\n Example 1:\n Input: root = [0,1,2,3,4,3,4]\n Output: \"dba\"\n Example 2:\n Input: root = [25,1,3,1,3,0,2]\n Output: \"adz\"\n Example 3:\n Input: root = [2,2,1,null,1,0,null,0]\n Output: \"abc\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 989, - "title": "Add to Array-Form of Integer", - "question": "class Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n \"\"\"\n The array-form of an integer num is an array representing its digits in left to right order.\n For example, for num = 1321, the array form is [1,3,2,1].\n Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.\n Example 1:\n Input: num = [1,2,0,0], k = 34\n Output: [1,2,3,4]\n Explanation: 1200 + 34 = 1234\n Example 2:\n Input: num = [2,7,4], k = 181\n Output: [4,5,5]\n Explanation: 274 + 181 = 455\n Example 3:\n Input: num = [2,1,5], k = 806\n Output: [1,0,2,1]\n Explanation: 215 + 806 = 1021\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 990, - "title": "Satisfiability of Equality Equations", - "question": "class Solution:\n def equationsPossible(self, equations: List[str]) -> bool:\n \"\"\"\n 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.\n Return 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:\n Input: equations = [\"a==b\",\"b!=a\"]\n Output: false\n Explanation: If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.\n There is no way to assign the variables to satisfy both equations.\n Example 2:\n Input: equations = [\"b==a\",\"a==b\"]\n Output: true\n Explanation: We could assign a = 1 and b = 1 to satisfy both equations.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 991, - "title": "Broken Calculator", - "question": "class Solution:\n def brokenCalc(self, startValue: int, target: int) -> int:\n \"\"\"\n There is a broken calculator that has the integer startValue on its display initially. In one operation, you can:\n multiply the number on display by 2, or\n subtract 1 from the number on display.\n Given two integers startValue and target, return the minimum number of operations needed to display target on the calculator.\n Example 1:\n Input: startValue = 2, target = 3\n Output: 2\n Explanation: Use double operation and then decrement operation {2 -> 4 -> 3}.\n Example 2:\n Input: startValue = 5, target = 8\n Output: 2\n Explanation: Use decrement and then double {5 -> 4 -> 8}.\n Example 3:\n Input: startValue = 3, target = 10\n Output: 3\n Explanation: Use double, decrement and double {3 -> 6 -> 5 -> 10}.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 992, - "title": "Subarrays with K Different Integers", - "question": "class Solution:\n def subarraysWithKDistinct(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an integer array nums and an integer k, return the number of good subarrays of nums.\n A good array is an array where the number of different integers in that array is exactly k.\n For example, [1,2,3,1,2] has 3 different integers: 1, 2, and 3.\n A subarray is a contiguous part of an array.\n Example 1:\n Input: nums = [1,2,1,2,3], k = 2\n Output: 7\n Explanation: Subarrays formed with exactly 2 different integers: [1,2], [2,1], [1,2], [2,3], [1,2,1], [2,1,2], [1,2,1,2]\n Example 2:\n Input: nums = [1,2,1,3,4], k = 3\n Output: 3\n Explanation: Subarrays formed with exactly 3 different integers: [1,2,1,3], [2,1,3], [1,3,4].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 993, - "title": "Cousins in Binary Tree", - "question": "class Solution:\n def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:\n \"\"\"\n 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.\n Two nodes of a binary tree are cousins if they have the same depth with different parents.\n Note 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:\n Input: root = [1,2,3,4], x = 4, y = 3\n Output: false\n Example 2:\n Input: root = [1,2,3,null,4,null,5], x = 5, y = 4\n Output: true\n Example 3:\n Input: root = [1,2,3,null,4], x = 2, y = 3\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 994, - "title": "Rotting Oranges", - "question": "class Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n grid where each cell can have one of three values:\n 0 representing an empty cell,\n 1 representing a fresh orange, or\n 2 representing a rotten orange.\n Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.\n Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.\n Example 1:\n Input: grid = [[2,1,1],[1,1,0],[0,1,1]]\n Output: 4\n Example 2:\n Input: grid = [[2,1,1],[0,1,1],[1,0,1]]\n Output: -1\n Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.\n Example 3:\n Input: grid = [[0,2]]\n Output: 0\n Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 995, - "title": "Minimum Number of K Consecutive Bit Flips", - "question": "class Solution:\n def minKBitFlips(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given a binary array nums and an integer k.\n A 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.\n Return the minimum number of k-bit flips required so that there is no 0 in the array. If it is not possible, return -1.\n A subarray is a contiguous part of an array.\n Example 1:\n Input: nums = [0,1,0], k = 1\n Output: 2\n Explanation: Flip nums[0], then flip nums[2].\n Example 2:\n Input: nums = [1,1,0], k = 2\n Output: -1\n Explanation: No matter how we flip subarrays of size 2, we cannot make the array become [1,1,1].\n Example 3:\n Input: nums = [0,0,0,1,0,1,1,0], k = 3\n Output: 3\n Explanation: \n Flip nums[0],nums[1],nums[2]: nums becomes [1,1,1,1,0,1,1,0]\n Flip nums[4],nums[5],nums[6]: nums becomes [1,1,1,1,1,0,0,0]\n Flip nums[5],nums[6],nums[7]: nums becomes [1,1,1,1,1,1,1,1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 996, - "title": "Number of Squareful Arrays", - "question": "class Solution:\n def numSquarefulPerms(self, nums: List[int]) -> int:\n \"\"\"\n An array is squareful if the sum of every pair of adjacent elements is a perfect square.\n Given an integer array nums, return the number of permutations of nums that are squareful.\n Two permutations perm1 and perm2 are different if there is some index i such that perm1[i] != perm2[i].\n Example 1:\n Input: nums = [1,17,8]\n Output: 2\n Explanation: [1,8,17] and [17,8,1] are the valid permutations.\n Example 2:\n Input: nums = [2,2,2]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 997, - "title": "Find the Town Judge", - "question": "class Solution:\n def findJudge(self, n: int, trust: List[List[int]]) -> int:\n \"\"\"\n 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.\n If the town judge exists, then:\n The town judge trusts nobody.\n Everybody (except for the town judge) trusts the town judge.\n There is exactly one person that satisfies properties 1 and 2.\n You 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.\n Return the label of the town judge if the town judge exists and can be identified, or return -1 otherwise.\n Example 1:\n Input: n = 2, trust = [[1,2]]\n Output: 2\n Example 2:\n Input: n = 3, trust = [[1,3],[2,3]]\n Output: 3\n Example 3:\n Input: n = 3, trust = [[1,3],[2,3],[3,1]]\n Output: -1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 998, - "title": "Maximum Binary Tree II", - "question": "class Solution:\n def insertIntoMaxTree(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:\n \"\"\"\n A maximum tree is a tree where every node has a value greater than any other value in its subtree.\n You are given the root of a maximum binary tree and an integer val.\n Just as in the previous problem, the given tree was constructed from a list a (root = Construct(a)) recursively with the following Construct(a) routine:\n If a is empty, return null.\n Otherwise, let a[i] be the largest element of a. Create a root node with the value a[i].\n The left child of root will be Construct([a[0], a[1], ..., a[i - 1]]).\n The right child of root will be Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]]).\n Return root.\n Note that we were not given a directly, only a root node root = Construct(a).\n Suppose b is a copy of a with the value val appended to it. It is guaranteed that b has unique values.\n Return Construct(b).\n Example 1:\n Input: root = [4,1,3,null,null,2], val = 5\n Output: [5,4,null,1,3,null,null,2]\n Explanation: a = [1,4,2,3], b = [1,4,2,3,5]\n Example 2:\n Input: root = [5,2,4,null,1], val = 3\n Output: [5,2,4,null,1,null,3]\n Explanation: a = [2,1,5,4], b = [2,1,5,4,3]\n Example 3:\n Input: root = [5,2,3,null,1], val = 4\n Output: [5,2,4,null,1,3]\n Explanation: a = [2,1,5,3], b = [2,1,5,3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 999, - "title": "Available Captures for Rook", - "question": "class Solution:\n def numRookCaptures(self, board: List[List[str]]) -> int:\n \"\"\"\n 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 '.'.\n When 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.\n Return the number of available captures for the white rook.\n Example 1:\n Input: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\n Output: 3\n Explanation: In this example, the rook is attacking all the pawns.\n Example 2:\n Input: 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\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\n Output: 0\n Explanation: The bishops are blocking the rook from attacking any of the pawns.\n Example 3:\n Input: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\"p\",\"p\",\".\",\"R\",\".\",\"p\",\"B\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"]]\n Output: 3\n Explanation: The rook is attacking the pawns at positions b5, d6, and f5.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1000, - "title": "Minimum Cost to Merge Stones", - "question": "class Solution:\n def mergeStones(self, stones: List[int], k: int) -> int:\n \"\"\"\n There are n piles of stones arranged in a row. The ith pile has stones[i] stones.\n A move consists of merging exactly k consecutive piles into one pile, and the cost of this move is equal to the total number of stones in these k piles.\n Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return -1.\n Example 1:\n Input: stones = [3,2,4,1], k = 2\n Output: 20\n Explanation: We start with [3, 2, 4, 1].\n We merge [3, 2] for a cost of 5, and we are left with [5, 4, 1].\n We merge [4, 1] for a cost of 5, and we are left with [5, 5].\n We merge [5, 5] for a cost of 10, and we are left with [10].\n The total cost was 20, and this is the minimum possible.\n Example 2:\n Input: stones = [3,2,4,1], k = 3\n Output: -1\n Explanation: After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.\n Example 3:\n Input: stones = [3,5,1,2,6], k = 3\n Output: 25\n Explanation: We start with [3, 5, 1, 2, 6].\n We merge [5, 1, 2] for a cost of 8, and we are left with [3, 8, 6].\n We merge [3, 8, 6] for a cost of 17, and we are left with [17].\n The total cost was 25, and this is the minimum possible.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1001, - "title": "Grid Illumination", - "question": "class Solution:\n def gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]:\n \"\"\"\n There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.\n You 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.\n When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.\n You 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].\n Return 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:\n Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]\n Output: [1,0]\n Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].\n The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.\n The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.\n Example 2:\n Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]\n Output: [1,1]\n Example 3:\n Input: n = 5, lamps = [[0,0],[0,4]], queries = [[0,4],[0,1],[1,4]]\n Output: [1,1,0]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1002, - "title": "Find Common Characters", - "question": "class Solution:\n def commonChars(self, words: List[str]) -> List[str]:\n \"\"\"\n 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:\n Input: words = [\"bella\",\"label\",\"roller\"]\n Output: [\"e\",\"l\",\"l\"]\n Example 2:\n Input: words = [\"cool\",\"lock\",\"cook\"]\n Output: [\"c\",\"o\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1003, - "title": "Check If Word Is Valid After Substitutions", - "question": "class Solution:\n def isValid(self, s: str) -> bool:\n \"\"\"\n Given a string s, determine if it is valid.\n A 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:\n Insert 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.\n Return true if s is a valid string, otherwise, return false.\n Example 1:\n Input: s = \"aabcbc\"\n Output: true\n Explanation:\n \"\" -> \"abc\" -> \"aabcbc\"\n Thus, \"aabcbc\" is valid.\n Example 2:\n Input: s = \"abcabcababcc\"\n Output: true\n Explanation:\n \"\" -> \"abc\" -> \"abcabc\" -> \"abcabcabc\" -> \"abcabcababcc\"\n Thus, \"abcabcababcc\" is valid.\n Example 3:\n Input: s = \"abccba\"\n Output: false\n Explanation: It is impossible to get \"abccba\" using the operation.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1004, - "title": "Max Consecutive Ones III", - "question": "class Solution:\n def longestOnes(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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:\n Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2\n Output: 6\n Explanation: [1,1,1,0,0,1,1,1,1,1,1]\n Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n Example 2:\n Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3\n Output: 10\n Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]\n Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1005, - "title": "Maximize Sum Of Array After K Negations", - "question": "class Solution:\n def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an integer array nums and an integer k, modify the array in the following way:\n choose an index i and replace nums[i] with -nums[i].\n You should apply this process exactly k times. You may choose the same index i multiple times.\n Return the largest possible sum of the array after modifying it in this way.\n Example 1:\n Input: nums = [4,2,3], k = 1\n Output: 5\n Explanation: Choose index 1 and nums becomes [4,-2,3].\n Example 2:\n Input: nums = [3,-1,0,2], k = 3\n Output: 6\n Explanation: Choose indices (1, 2, 2) and nums becomes [3,1,0,2].\n Example 3:\n Input: nums = [2,-3,-1,5,-4], k = 2\n Output: 13\n Explanation: Choose indices (1, 4) and nums becomes [2,3,-1,5,4].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1006, - "title": "Clumsy Factorial", - "question": "class Solution:\n def clumsy(self, n: int) -> int:\n \"\"\"\n The factorial of a positive integer n is the product of all positive integers less than or equal to n.\n For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.\n We 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.\n For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1.\n However, 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.\n Additionally, the division that we use is floor division such that 10 * 9 / 8 = 90 / 8 = 11.\n Given an integer n, return the clumsy factorial of n.\n Example 1:\n Input: n = 4\n Output: 7\n Explanation: 7 = 4 * 3 / 2 + 1\n Example 2:\n Input: n = 10\n Output: 12\n Explanation: 12 = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1007, - "title": "Minimum Domino Rotations For Equal Row", - "question": "class Solution:\n def minDominoRotations(self, tops: List[int], bottoms: List[int]) -> int:\n \"\"\"\n 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.)\n We may rotate the ith domino, so that tops[i] and bottoms[i] swap values.\n Return the minimum number of rotations so that all the values in tops are the same, or all the values in bottoms are the same.\n If it cannot be done, return -1.\n Example 1:\n Input: tops = [2,1,2,4,2,2], bottoms = [5,2,6,2,3,2]\n Output: 2\n Explanation: \n The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.\n If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.\n Example 2:\n Input: tops = [3,5,1,2,3], bottoms = [3,6,3,3,4]\n Output: -1\n Explanation: \n In this case, it is not possible to rotate the dominoes to make one row of values equal.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1008, - "title": "Construct Binary Search Tree from Preorder Traversal", - "question": "class Solution:\n def bstFromPreorder(self, preorder: List[int]) -> Optional[TreeNode]:\n \"\"\"\n 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.\n It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.\n A 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.\n A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.\n Example 1:\n Input: preorder = [8,5,1,7,10,12]\n Output: [8,5,10,1,7,null,12]\n Example 2:\n Input: preorder = [1,3]\n Output: [1,null,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1009, - "title": "Complement of Base 10 Integer", - "question": "class Solution:\n def bitwiseComplement(self, n: int) -> int:\n \"\"\"\n 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.\n For example, The integer 5 is \"101\" in binary and its complement is \"010\" which is the integer 2.\n Given an integer n, return its complement.\n Example 1:\n Input: n = 5\n Output: 2\n Explanation: 5 is \"101\" in binary, with complement \"010\" in binary, which is 2 in base-10.\n Example 2:\n Input: n = 7\n Output: 0\n Explanation: 7 is \"111\" in binary, with complement \"000\" in binary, which is 0 in base-10.\n Example 3:\n Input: n = 10\n Output: 5\n Explanation: 10 is \"1010\" in binary, with complement \"0101\" in binary, which is 5 in base-10.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1010, - "title": "Pairs of Songs With Total Durations Divisible by 60", - "question": "class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n \"\"\"\n You are given a list of songs where the ith song has a duration of time[i] seconds.\n Return 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:\n Input: time = [30,20,150,100,40]\n Output: 3\n Explanation: Three pairs have a total duration divisible by 60:\n (time[0] = 30, time[2] = 150): total duration 180\n (time[1] = 20, time[3] = 100): total duration 120\n (time[1] = 20, time[4] = 40): total duration 60\n Example 2:\n Input: time = [60,60,60]\n Output: 3\n Explanation: All three pairs have a total duration of 120, which is divisible by 60.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1011, - "title": "Capacity To Ship Packages Within D Days", - "question": "class Solution:\n def shipWithinDays(self, weights: List[int], days: int) -> int:\n \"\"\"\n A conveyor belt has packages that must be shipped from one port to another within days days.\n The 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.\n Return 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:\n Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5\n Output: 15\n Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this:\n 1st day: 1, 2, 3, 4, 5\n 2nd day: 6, 7\n 3rd day: 8\n 4th day: 9\n 5th day: 10\n Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed.\n Example 2:\n Input: weights = [3,2,2,4,1,4], days = 3\n Output: 6\n Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this:\n 1st day: 3, 2\n 2nd day: 2, 4\n 3rd day: 1, 4\n Example 3:\n Input: weights = [1,2,3,1,1], days = 4\n Output: 3\n Explanation:\n 1st day: 1\n 2nd day: 2\n 3rd day: 3\n 4th day: 1, 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1012, - "title": "Numbers With Repeated Digits", - "question": "class Solution:\n def numDupDigitsAtMostN(self, n: int) -> int:\n \"\"\"\n 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:\n Input: n = 20\n Output: 1\n Explanation: The only positive number (<= 20) with at least 1 repeated digit is 11.\n Example 2:\n Input: n = 100\n Output: 10\n Explanation: The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100.\n Example 3:\n Input: n = 1000\n Output: 262\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1061, - "title": "Lexicographically Smallest Equivalent String", - "question": "class Solution:\n def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:\n \"\"\"\n You are given two strings of the same length s1 and s2 and a string baseStr.\n We say s1[i] and s2[i] are equivalent characters.\n For example, if s1 = \"abc\" and s2 = \"cde\", then we have 'a' == 'c', 'b' == 'd', and 'c' == 'e'.\n Equivalent characters follow the usual rules of any equivalence relation:\n Reflexivity: 'a' == 'a'.\n Symmetry: 'a' == 'b' implies 'b' == 'a'.\n Transitivity: 'a' == 'b' and 'b' == 'c' implies 'a' == 'c'.\n For example, given the equivalency information from s1 = \"abc\" and s2 = \"cde\", \"acd\" and \"aab\" are equivalent strings of baseStr = \"eed\", and \"aab\" is the lexicographically smallest equivalent string of baseStr.\n Return the lexicographically smallest equivalent string of baseStr by using the equivalency information from s1 and s2.\n Example 1:\n Input: s1 = \"parker\", s2 = \"morris\", baseStr = \"parser\"\n Output: \"makkek\"\n Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [m,p], [a,o], [k,r,s], [e,i].\n The characters in each group are equivalent and sorted in lexicographical order.\n So the answer is \"makkek\".\n Example 2:\n Input: s1 = \"hello\", s2 = \"world\", baseStr = \"hold\"\n Output: \"hdld\"\n Explanation: Based on the equivalency information in s1 and s2, we can group their characters as [h,w], [d,e,o], [l,r].\n So only the second letter 'o' in baseStr is changed to 'd', the answer is \"hdld\".\n Example 3:\n Input: s1 = \"leetcode\", s2 = \"programs\", baseStr = \"sourcecode\"\n Output: \"aauaaaaada\"\n Explanation: We group the equivalent characters in s1 and s2 as [a,o,e,r,s,c], [l,p], [g,t] and [d,m], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is \"aauaaaaada\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1013, - "title": "Partition Array Into Three Parts With Equal Sum", - "question": "class Solution:\n def canThreePartsEqualSum(self, arr: List[int]) -> bool:\n \"\"\"\n Given an array of integers arr, return true if we can partition the array into three non-empty parts with equal sums.\n Formally, 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:\n Input: arr = [0,2,1,-6,6,-7,9,1,2,0,1]\n Output: true\n Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1\n Example 2:\n Input: arr = [0,2,1,-6,6,7,9,-1,2,0,1]\n Output: false\n Example 3:\n Input: arr = [3,3,6,5,-2,2,5,1,-9,4]\n Output: true\n Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1014, - "title": "Best Sightseeing Pair", - "question": "class Solution:\n def maxScoreSightseeingPair(self, values: List[int]) -> int:\n \"\"\"\n 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.\n The 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.\n Return the maximum score of a pair of sightseeing spots.\n Example 1:\n Input: values = [8,1,5,2,6]\n Output: 11\n Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11\n Example 2:\n Input: values = [1,2]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1015, - "title": "Smallest Integer Divisible by K", - "question": "class Solution:\n def smallestRepunitDivByK(self, k: int) -> int:\n \"\"\"\n 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.\n Return the length of n. If there is no such n, return -1.\n Note: n may not fit in a 64-bit signed integer.\n Example 1:\n Input: k = 1\n Output: 1\n Explanation: The smallest answer is n = 1, which has length 1.\n Example 2:\n Input: k = 2\n Output: -1\n Explanation: There is no such positive integer n divisible by 2.\n Example 3:\n Input: k = 3\n Output: 3\n Explanation: The smallest answer is n = 111, which has length 3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1016, - "title": "Binary String With Substrings Representing 1 To N", - "question": "class Solution:\n def queryString(self, s: str, n: int) -> bool:\n \"\"\"\n 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.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: s = \"0110\", n = 3\n Output: true\n Example 2:\n Input: s = \"0110\", n = 4\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1017, - "title": "Convert to Base -2", - "question": "class Solution:\n def baseNeg2(self, n: int) -> str:\n \"\"\"\n Given an integer n, return a binary string representing its representation in base -2.\n Note that the returned string should not have leading zeros unless the string is \"0\".\n Example 1:\n Input: n = 2\n Output: \"110\"\n Explantion: (-2)2 + (-2)1 = 2\n Example 2:\n Input: n = 3\n Output: \"111\"\n Explantion: (-2)2 + (-2)1 + (-2)0 = 3\n Example 3:\n Input: n = 4\n Output: \"100\"\n Explantion: (-2)2 = 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1018, - "title": "Binary Prefix Divisible By 5", - "question": "class Solution:\n def prefixesDivBy5(self, nums: List[int]) -> List[bool]:\n \"\"\"\n You are given a binary array nums (0-indexed).\n We define xi as the number whose binary representation is the subarray nums[0..i] (from most-significant-bit to least-significant-bit).\n For example, if nums = [1,0,1], then x0 = 1, x1 = 2, and x2 = 5.\n Return an array of booleans answer where answer[i] is true if xi is divisible by 5.\n Example 1:\n Input: nums = [0,1,1]\n Output: [true,false,false]\n Explanation: The input numbers in binary are 0, 01, 011; which are 0, 1, and 3 in base-10.\n Only the first number is divisible by 5, so answer[0] is true.\n Example 2:\n Input: nums = [1,1,1]\n Output: [false,false,false]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1019, - "title": "Next Greater Node In Linked List", - "question": "class Solution:\n def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:\n \"\"\"\n You are given the head of a linked list with n nodes.\n For 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.\n Return 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:\n Input: head = [2,1,5]\n Output: [5,5,0]\n Example 2:\n Input: head = [2,7,4,3,5]\n Output: [7,0,5,5,0]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1020, - "title": "Number of Enclaves", - "question": "class Solution:\n def numEnclaves(self, grid: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.\n A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.\n Return the number of land cells in grid for which we cannot walk off the boundary of the grid in any number of moves.\n Example 1:\n Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]\n Output: 3\n Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.\n Example 2:\n Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]\n Output: 0\n Explanation: All 1s are either on the boundary or can reach the boundary.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1021, - "title": "Remove Outermost Parentheses", - "question": "class Solution:\n def removeOuterParentheses(self, s: str) -> str:\n \"\"\"\n A valid parentheses string is either empty \"\", \"(\" + A + \")\", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.\n For example, \"\", \"()\", \"(())()\", and \"(()(()))\" are all valid parentheses strings.\n A 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.\n Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.\n Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.\n Example 1:\n Input: s = \"(()())(())\"\n Output: \"()()()\"\n Explanation: \n The input string is \"(()())(())\", with primitive decomposition \"(()())\" + \"(())\".\n After removing outer parentheses of each part, this is \"()()\" + \"()\" = \"()()()\".\n Example 2:\n Input: s = \"(()())(())(()(()))\"\n Output: \"()()()()(())\"\n Explanation: \n The input string is \"(()())(())(()(()))\", with primitive decomposition \"(()())\" + \"(())\" + \"(()(()))\".\n After removing outer parentheses of each part, this is \"()()\" + \"()\" + \"()(())\" = \"()()()()(())\".\n Example 3:\n Input: s = \"()()\"\n Output: \"\"\n Explanation: \n The input string is \"()()\", with primitive decomposition \"()\" + \"()\".\n After removing outer parentheses of each part, this is \"\" + \"\" = \"\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1022, - "title": "Sum of Root To Leaf Binary Numbers", - "question": "class Solution:\n def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.\n For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return the sum of these numbers.\n The test cases are generated so that the answer fits in a 32-bits integer.\n Example 1:\n Input: root = [1,0,1,0,1,0,1]\n Output: 22\n Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22\n Example 2:\n Input: root = [0]\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1023, - "title": "Camelcase Matching", - "question": "class Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n \"\"\"\n 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.\n A 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:\n Input: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FB\"\n Output: [true,false,true,true,false]\n Explanation: \"FooBar\" can be generated like this \"F\" + \"oo\" + \"B\" + \"ar\".\n \"FootBall\" can be generated like this \"F\" + \"oot\" + \"B\" + \"all\".\n \"FrameBuffer\" can be generated like this \"F\" + \"rame\" + \"B\" + \"uffer\".\n Example 2:\n Input: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBa\"\n Output: [true,false,true,false,false]\n Explanation: \"FooBar\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\".\n \"FootBall\" can be generated like this \"Fo\" + \"ot\" + \"Ba\" + \"ll\".\n Example 3:\n Input: queries = [\"FooBar\",\"FooBarTest\",\"FootBall\",\"FrameBuffer\",\"ForceFeedBack\"], pattern = \"FoBaT\"\n Output: [false,true,false,false,false]\n Explanation: \"FooBarTest\" can be generated like this \"Fo\" + \"o\" + \"Ba\" + \"r\" + \"T\" + \"est\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1024, - "title": "Video Stitching", - "question": "class Solution:\n def videoStitching(self, clips: List[List[int]], time: int) -> int:\n \"\"\"\n 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.\n Each 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.\n We can cut these clips into segments freely.\n For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].\n Return 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:\n Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10\n Output: 3\n Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.\n Then, we can reconstruct the sporting event as follows:\n We cut [1,9] into segments [1,2] + [2,8] + [8,9].\n Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].\n Example 2:\n Input: clips = [[0,1],[1,2]], time = 5\n Output: -1\n Explanation: We cannot cover [0,5] with only [0,1] and [1,2].\n Example 3:\n Input: 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\n Output: 3\n Explanation: We can take clips [0,4], [4,7], and [6,9].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1025, - "title": "Divisor Game", - "question": "class Solution:\n def divisorGame(self, n: int) -> bool:\n \"\"\"\n Alice and Bob take turns playing a game, with Alice starting first.\n Initially, there is a number n on the chalkboard. On each player's turn, that player makes a move consisting of:\n Choosing any x with 0 < x < n and n % x == 0.\n Replacing the number n on the chalkboard with n - x.\n Also, if a player cannot make a move, they lose the game.\n Return true if and only if Alice wins the game, assuming both players play optimally.\n Example 1:\n Input: n = 2\n Output: true\n Explanation: Alice chooses 1, and Bob has no more moves.\n Example 2:\n Input: n = 3\n Output: false\n Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1027, - "title": "Longest Arithmetic Subsequence", - "question": "class Solution:\n def longestArithSeqLength(self, nums: List[int]) -> int:\n \"\"\"\n Given an array nums of integers, return the length of the longest arithmetic subsequence in nums.\n Note that:\n A 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 A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value (for 0 <= i < seq.length - 1).\n Example 1:\n Input: nums = [3,6,9,12]\n Output: 4\n Explanation: The whole array is an arithmetic sequence with steps of length = 3.\n Example 2:\n Input: nums = [9,4,7,2,10]\n Output: 3\n Explanation: The longest arithmetic subsequence is [4,7,10].\n Example 3:\n Input: nums = [20,1,15,3,10,5,8]\n Output: 4\n Explanation: The longest arithmetic subsequence is [20,15,10,5].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1026, - "title": "Maximum Difference Between Node and Ancestor", - "question": "class Solution:\n def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n A 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:\n Input: root = [8,3,10,1,6,null,14,null,null,4,7,13]\n Output: 7\n Explanation: 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\n Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.\n Example 2:\n Input: root = [1,null,2,null,0,3]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1028, - "title": "Recover a Tree From Preorder Traversal", - "question": "class Solution:\n def recoverFromPreorder(self, traversal: str) -> Optional[TreeNode]:\n \"\"\"\n We run a preorder depth-first search (DFS) on the root of a binary tree.\n At 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.\n If a node has only one child, that child is guaranteed to be the left child.\n Given the output traversal of this traversal, recover the tree and return its root.\n Example 1:\n Input: traversal = \"1-2--3--4-5--6--7\"\n Output: [1,2,5,3,4,6,7]\n Example 2:\n Input: traversal = \"1-2--3---4-5--6---7\"\n Output: [1,2,5,3,null,6,null,4,null,7]\n Example 3:\n Input: traversal = \"1-401--349---90--88\"\n Output: [1,401,null,349,88,90]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1030, - "title": "Matrix Cells in Distance Order", - "question": "class Solution:\n def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:\n \"\"\"\n 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).\n Return 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.\n The distance between two cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.\n Example 1:\n Input: rows = 1, cols = 2, rCenter = 0, cCenter = 0\n Output: [[0,0],[0,1]]\n Explanation: The distances from (0, 0) to other cells are: [0,1]\n Example 2:\n Input: rows = 2, cols = 2, rCenter = 0, cCenter = 1\n Output: [[0,1],[0,0],[1,1],[1,0]]\n Explanation: The distances from (0, 1) to other cells are: [0,1,1,2]\n The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct.\n Example 3:\n Input: rows = 2, cols = 3, rCenter = 1, cCenter = 2\n Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]]\n Explanation: The distances from (1, 2) to other cells are: [0,1,1,2,2,3]\n There 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1029, - "title": "Two City Scheduling", - "question": "class Solution:\n def twoCitySchedCost(self, costs: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.\n Example 1:\n Input: costs = [[10,20],[30,200],[400,50],[30,20]]\n Output: 110\n Explanation: \n The first person goes to city A for a cost of 10.\n The second person goes to city A for a cost of 30.\n The third person goes to city B for a cost of 50.\n The fourth person goes to city B for a cost of 20.\n The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.\n Example 2:\n Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]\n Output: 1859\n Example 3:\n Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]\n Output: 3086\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1031, - "title": "Maximum Sum of Two Non-Overlapping Subarrays", - "question": "class Solution:\n def maxSumTwoNoOverlap(self, nums: List[int], firstLen: int, secondLen: int) -> int:\n \"\"\"\n 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.\n The array with length firstLen could occur before or after the array with length secondLen, but they have to be non-overlapping.\n A subarray is a contiguous part of an array.\n Example 1:\n Input: nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2\n Output: 20\n Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.\n Example 2:\n Input: nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2\n Output: 29\n Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.\n Example 3:\n Input: nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3\n Output: 31\n Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [0,3,8] with length 3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1032, - "title": "Stream of Characters", - "question": "class StreamChecker:\n def __init__(self, words: List[str]):\n def query(self, letter: str) -> bool:\n \"\"\"\n Design an algorithm that accepts a stream of characters and checks if a suffix of these characters is a string of a given array of strings words.\n For example, if words = [\"abc\", \"xyz\"] and the stream added the four characters (one by one) 'a', 'x', 'y', and 'z', your algorithm should detect that the suffix \"xyz\" of the characters \"axyz\" matches \"xyz\" from words.\n Implement the StreamChecker class:\n StreamChecker(String[] words) Initializes the object with the strings array words.\n boolean query(char letter) Accepts a new character from the stream and returns true if any non-empty suffix from the stream forms a word that is in words.\n Example 1:\n Input\n [\"StreamChecker\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\", \"query\"]\n [[[\"cd\", \"f\", \"kl\"]], [\"a\"], [\"b\"], [\"c\"], [\"d\"], [\"e\"], [\"f\"], [\"g\"], [\"h\"], [\"i\"], [\"j\"], [\"k\"], [\"l\"]]\n Output\n [null, false, false, false, true, false, true, false, false, false, false, false, true]\n Explanation\n StreamChecker streamChecker = new StreamChecker([\"cd\", \"f\", \"kl\"]);\n streamChecker.query(\"a\"); // return False\n streamChecker.query(\"b\"); // return False\n streamChecker.query(\"c\"); // return False\n streamChecker.query(\"d\"); // return True, because 'cd' is in the wordlist\n streamChecker.query(\"e\"); // return False\n streamChecker.query(\"f\"); // return True, because 'f' is in the wordlist\n streamChecker.query(\"g\"); // return False\n streamChecker.query(\"h\"); // return False\n streamChecker.query(\"i\"); // return False\n streamChecker.query(\"j\"); // return False\n streamChecker.query(\"k\"); // return False\n streamChecker.query(\"l\"); // return True, because 'kl' is in the wordlist\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1033, - "title": "Moving Stones Until Consecutive", - "question": "class Solution:\n def numMovesStones(self, a: int, b: int, c: int) -> List[int]:\n \"\"\"\n 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.\n In 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.\n The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\n Return an integer array answer of length 2 where:\n answer[0] is the minimum number of moves you can play, and\n answer[1] is the maximum number of moves you can play.\n Example 1:\n Input: a = 1, b = 2, c = 5\n Output: [1,2]\n Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.\n Example 2:\n Input: a = 4, b = 3, c = 2\n Output: [0,0]\n Explanation: We cannot make any moves.\n Example 3:\n Input: a = 3, b = 5, c = 1\n Output: [1,2]\n Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1034, - "title": "Coloring A Border", - "question": "class Solution:\n def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:\n \"\"\"\n 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.\n Two squares belong to the same connected component if they have the same color and are next to each other in any of the 4 directions.\n The border of a connected component is all the squares in the connected component that are either 4-directionally adjacent to a square not in the component, or on the boundary of the grid (the first or last row or column).\n You should color the border of the connected component that contains the square grid[row][col] with color.\n Return the final grid.\n Example 1:\n Input: grid = [[1,1],[1,2]], row = 0, col = 0, color = 3\n Output: [[3,3],[3,2]]\n Example 2:\n Input: grid = [[1,2,2],[2,3,2]], row = 0, col = 1, color = 3\n Output: [[1,3,3],[2,3,3]]\n Example 3:\n Input: grid = [[1,1,1],[1,1,1],[1,1,1]], row = 1, col = 1, color = 2\n Output: [[2,2,2],[2,1,2],[2,2,2]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1035, - "title": "Uncrossed Lines", - "question": "class Solution:\n def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n 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.\n We may draw connecting lines: a straight line connecting two numbers nums1[i] and nums2[j] such that:\n nums1[i] == nums2[j], and\n the line we draw does not intersect any other connecting (non-horizontal) line.\n Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line).\n Return the maximum number of connecting lines we can draw in this way.\n Example 1:\n Input: nums1 = [1,4,2], nums2 = [1,2,4]\n Output: 2\n Explanation: We can draw 2 uncrossed lines as in the diagram.\n We cannot draw 3 uncrossed lines, because the line from nums1[1] = 4 to nums2[2] = 4 will intersect the line from nums1[2]=2 to nums2[1]=2.\n Example 2:\n Input: nums1 = [2,5,1,2,5], nums2 = [10,5,2,1,5,2]\n Output: 3\n Example 3:\n Input: nums1 = [1,3,7,1,7,5], nums2 = [1,9,2,5,1]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1036, - "title": "Escape a Large Maze", - "question": "class Solution:\n def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:\n \"\"\"\n There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are (x, y).\n We start at the source = [sx, sy] square and want to reach the target = [tx, ty] square. There is also an array of blocked squares, where each blocked[i] = [xi, yi] represents a blocked square with coordinates (xi, yi).\n Each move, we can walk one square north, east, south, or west if the square is not in the array of blocked squares. We are also not allowed to walk outside of the grid.\n Return true if and only if it is possible to reach the target square from the source square through a sequence of valid moves.\n Example 1:\n Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]\n Output: false\n Explanation: The target square is inaccessible starting from the source square because we cannot move.\n We cannot move north or east because those squares are blocked.\n We cannot move south or west because we cannot go outside of the grid.\n Example 2:\n Input: blocked = [], source = [0,0], target = [999999,999999]\n Output: true\n Explanation: Because there are no blocked cells, it is possible to reach the target square.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1039, - "title": "Minimum Score Triangulation of Polygon", - "question": "class Solution:\n def minScoreTriangulation(self, values: List[int]) -> int:\n \"\"\"\n 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).\n You 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.\n Return the smallest possible total score that you can achieve with some triangulation of the polygon.\n Example 1:\n Input: values = [1,2,3]\n Output: 6\n Explanation: The polygon is already triangulated, and the score of the only triangle is 6.\n Example 2:\n Input: values = [3,7,4,5]\n Output: 144\n Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144.\n The minimum score is 144.\n Example 3:\n Input: values = [1,3,1,4,1,5]\n Output: 13\n Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1160, - "title": "Find Words That Can Be Formed by Characters", - "question": "class Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n \"\"\"\n You are given an array of strings words and a string chars.\n A string is good if it can be formed by characters from chars (each character can only be used once).\n Return the sum of lengths of all good strings in words.\n Example 1:\n Input: words = [\"cat\",\"bt\",\"hat\",\"tree\"], chars = \"atach\"\n Output: 6\n Explanation: The strings that can be formed are \"cat\" and \"hat\" so the answer is 3 + 3 = 6.\n Example 2:\n Input: words = [\"hello\",\"world\",\"leetcode\"], chars = \"welldonehoneyr\"\n Output: 10\n Explanation: The strings that can be formed are \"hello\" and \"world\" so the answer is 5 + 5 = 10.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1040, - "title": "Moving Stones Until Consecutive II", - "question": "class Solution:\n def numMovesStonesII(self, stones: List[int]) -> List[int]:\n \"\"\"\n There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones.\n Call 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.\n In 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.\n The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions).\n Return an integer array answer of length 2 where:\n answer[0] is the minimum number of moves you can play, and\n answer[1] is the maximum number of moves you can play.\n Example 1:\n Input: stones = [7,4,9]\n Output: [1,2]\n Explanation: We can move 4 -> 8 for one move to finish the game.\n Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.\n Example 2:\n Input: stones = [6,5,4,3,10]\n Output: [2,3]\n Explanation: We can move 3 -> 8 then 10 -> 7 to finish the game.\n Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.\n Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1038, - "title": "Binary Search Tree to Greater Sum Tree", - "question": "class Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 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.\n As a reminder, a binary search tree is a tree that satisfies these constraints:\n The left subtree of a node contains only nodes with keys less than the node's key.\n The right subtree of a node contains only nodes with keys greater than the node's key.\n Both the left and right subtrees must also be binary search trees.\n Example 1:\n Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]\n Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]\n Example 2:\n Input: root = [0,null,1]\n Output: [1,null,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1037, - "title": "Valid Boomerang", - "question": "class Solution:\n def isBoomerang(self, points: List[List[int]]) -> bool:\n \"\"\"\n 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.\n A boomerang is a set of three points that are all distinct and not in a straight line.\n Example 1:\n Input: points = [[1,1],[2,3],[3,2]]\n Output: true\n Example 2:\n Input: points = [[1,1],[2,2],[3,3]]\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1161, - "title": "Maximum Level Sum of a Binary Tree", - "question": "class Solution:\n def maxLevelSum(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on.\n Return the smallest level x such that the sum of all the values of nodes at level x is maximal.\n Example 1:\n Input: root = [1,7,0,7,-8,null,null]\n Output: 2\n Explanation: \n Level 1 sum = 1.\n Level 2 sum = 7 + 0 = 7.\n Level 3 sum = 7 + -8 = -1.\n So we return the level with the maximum sum which is level 2.\n Example 2:\n Input: root = [989,null,10250,98693,-89388,null,null,null,-32127]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1162, - "title": "As Far from Land as Possible", - "question": "class Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n The 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:\n Input: grid = [[1,0,1],[0,0,0],[1,0,1]]\n Output: 2\n Explanation: The cell (1, 1) is as far as possible from all the land with distance 2.\n Example 2:\n Input: grid = [[1,0,0],[0,0,0],[0,0,0]]\n Output: 4\n Explanation: The cell (2, 2) is as far as possible from all the land with distance 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1041, - "title": "Robot Bounded In Circle", - "question": "class Solution:\n def isRobotBounded(self, instructions: str) -> bool:\n \"\"\"\n On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:\n The north direction is the positive direction of the y-axis.\n The south direction is the negative direction of the y-axis.\n The east direction is the positive direction of the x-axis.\n The west direction is the negative direction of the x-axis.\n The 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).\n The robot performs the instructions given in order, and repeats them forever.\n Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.\n Example 1:\n Input: instructions = \"GGLLGG\"\n Output: true\n Explanation: 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.\n Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0).\n Based on that, we return true.\n Example 2:\n Input: instructions = \"GG\"\n Output: false\n Explanation: 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 Repeating the instructions, keeps advancing in the north direction and does not go into cycles.\n Based on that, we return false.\n Example 3:\n Input: instructions = \"GL\"\n Output: true\n Explanation: 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.\n Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0).\n Based on that, we return true.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1042, - "title": "Flower Planting With No Adjacent", - "question": "class Solution:\n def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n All gardens have at most 3 paths coming into or leaving it.\n Your 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.\n Return 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:\n Input: n = 3, paths = [[1,2],[2,3],[3,1]]\n Output: [1,2,3]\n Explanation:\n Gardens 1 and 2 have different types.\n Gardens 2 and 3 have different types.\n Gardens 3 and 1 have different types.\n Hence, [1,2,3] is a valid answer. Other valid answers include [1,2,4], [1,4,2], and [3,2,1].\n Example 2:\n Input: n = 4, paths = [[1,2],[3,4]]\n Output: [1,2,1,2]\n Example 3:\n Input: n = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]\n Output: [1,2,3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1043, - "title": "Partition Array for Maximum Sum", - "question": "class Solution:\n def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:\n \"\"\"\n 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.\n Return 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:\n Input: arr = [1,15,7,9,2,5,10], k = 3\n Output: 84\n Explanation: arr becomes [15,15,15,9,10,10,10]\n Example 2:\n Input: arr = [1,4,1,5,7,3,6,1,9,9,3], k = 4\n Output: 83\n Example 3:\n Input: arr = [1], k = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1044, - "title": "Longest Duplicate Substring", - "question": "class Solution:\n def longestDupSubstring(self, s: str) -> str:\n \"\"\"\n Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.\n Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is \"\".\n Example 1:\n Input: s = \"banana\"\n Output: \"ana\"\n Example 2:\n Input: s = \"abcd\"\n Output: \"\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1046, - "title": "Last Stone Weight", - "question": "class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n \"\"\"\n You are given an array of integers stones where stones[i] is the weight of the ith stone.\n We 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:\n If x == y, both stones are destroyed, and\n If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.\n At the end of the game, there is at most one stone left.\n Return the weight of the last remaining stone. If there are no stones left, return 0.\n Example 1:\n Input: stones = [2,7,4,1,8,1]\n Output: 1\n Explanation: \n We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,\n we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,\n we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,\n we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.\n Example 2:\n Input: stones = [1]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1047, - "title": "Remove All Adjacent Duplicates In String", - "question": "class Solution:\n def removeDuplicates(self, s: str) -> str:\n \"\"\"\n 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.\n We repeatedly make duplicate removals on s until we no longer can.\n Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.\n Example 1:\n Input: s = \"abbaca\"\n Output: \"ca\"\n Explanation: \n For example, in \"abbaca\" we could remove \"bb\" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is \"aaca\", of which only \"aa\" is possible, so the final string is \"ca\".\n Example 2:\n Input: s = \"azxxzy\"\n Output: \"ay\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1048, - "title": "Longest String Chain", - "question": "class Solution:\n def longestStrChain(self, words: List[str]) -> int:\n \"\"\"\n You are given an array of words where each word consists of lowercase English letters.\n wordA 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.\n For example, \"abc\" is a predecessor of \"abac\", while \"cba\" is not a predecessor of \"bcad\".\n A 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.\n Return the length of the longest possible word chain with words chosen from the given list of words.\n Example 1:\n Input: words = [\"a\",\"b\",\"ba\",\"bca\",\"bda\",\"bdca\"]\n Output: 4\n Explanation: One of the longest word chains is [\"a\",\"ba\",\"bda\",\"bdca\"].\n Example 2:\n Input: words = [\"xbc\",\"pcxbcf\",\"xb\",\"cxbc\",\"pcxbc\"]\n Output: 5\n Explanation: All the words can be put in a word chain [\"xb\", \"xbc\", \"cxbc\", \"pcxbc\", \"pcxbcf\"].\n Example 3:\n Input: words = [\"abcd\",\"dbqca\"]\n Output: 1\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1049, - "title": "Last Stone Weight II", - "question": "class Solution:\n def lastStoneWeightII(self, stones: List[int]) -> int:\n \"\"\"\n You are given an array of integers stones where stones[i] is the weight of the ith stone.\n We 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:\n If x == y, both stones are destroyed, and\n If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.\n At the end of the game, there is at most one stone left.\n Return the smallest possible weight of the left stone. If there are no stones left, return 0.\n Example 1:\n Input: stones = [2,7,4,1,8,1]\n Output: 1\n Explanation:\n We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,\n we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,\n we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,\n we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.\n Example 2:\n Input: stones = [31,26,33,21,40]\n Output: 5\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1163, - "title": "Last Substring in Lexicographical Order", - "question": "class Solution:\n def lastSubstring(self, s: str) -> str:\n \"\"\"\n Given a string s, return the last substring of s in lexicographical order.\n Example 1:\n Input: s = \"abab\"\n Output: \"bab\"\n Explanation: The substrings are [\"a\", \"ab\", \"aba\", \"abab\", \"b\", \"ba\", \"bab\"]. The lexicographically maximum substring is \"bab\".\n Example 2:\n Input: s = \"leetcode\"\n Output: \"tcode\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1051, - "title": "Height Checker", - "question": "class Solution:\n def heightChecker(self, heights: List[int]) -> int:\n \"\"\"\n 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.\n You 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).\n Return the number of indices where heights[i] != expected[i].\n Example 1:\n Input: heights = [1,1,4,2,1,3]\n Output: 3\n Explanation: \n heights: [1,1,4,2,1,3]\n expected: [1,1,1,2,3,4]\n Indices 2, 4, and 5 do not match.\n Example 2:\n Input: heights = [5,1,2,3,4]\n Output: 5\n Explanation:\n heights: [5,1,2,3,4]\n expected: [1,2,3,4,5]\n All indices do not match.\n Example 3:\n Input: heights = [1,2,3,4,5]\n Output: 0\n Explanation:\n heights: [1,2,3,4,5]\n expected: [1,2,3,4,5]\n All indices match.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1052, - "title": "Grumpy Bookstore Owner", - "question": "class Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:\n \"\"\"\n 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.\n On 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.\n When the bookstore owner is grumpy, the customers of that minute are not satisfied, otherwise, they are satisfied.\n The bookstore owner knows a secret technique to keep themselves not grumpy for minutes consecutive minutes, but can only use it once.\n Return the maximum number of customers that can be satisfied throughout the day.\n Example 1:\n Input: customers = [1,0,1,2,1,1,7,5], grumpy = [0,1,0,1,0,1,0,1], minutes = 3\n Output: 16\n Explanation: The bookstore owner keeps themselves not grumpy for the last 3 minutes. \n The maximum number of customers that can be satisfied = 1 + 1 + 1 + 1 + 7 + 5 = 16.\n Example 2:\n Input: customers = [1], grumpy = [0], minutes = 1\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1053, - "title": "Previous Permutation With One Swap", - "question": "class Solution:\n def prevPermOpt1(self, arr: List[int]) -> List[int]:\n \"\"\"\n Given an array of positive integers arr (not necessarily distinct), return the lexicographically largest permutation that is smaller than arr, that can be made with exactly one swap. If it cannot be done, then return the same array.\n Note that a swap exchanges the positions of two numbers arr[i] and arr[j]\n Example 1:\n Input: arr = [3,2,1]\n Output: [3,1,2]\n Explanation: Swapping 2 and 1.\n Example 2:\n Input: arr = [1,1,5]\n Output: [1,1,5]\n Explanation: This is already the smallest permutation.\n Example 3:\n Input: arr = [1,9,4,6,7]\n Output: [1,7,4,6,9]\n Explanation: Swapping 9 and 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1054, - "title": "Distant Barcodes", - "question": "class Solution:\n def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:\n \"\"\"\n In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].\n Rearrange 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:\n Input: barcodes = [1,1,1,2,2,2]\n Output: [2,1,2,1,2,1]\n Example 2:\n Input: barcodes = [1,1,1,1,2,2,3,3]\n Output: [1,3,1,3,1,2,1,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1074, - "title": "Number of Submatrices That Sum to Target", - "question": "class Solution:\n def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:\n \"\"\"\n Given a matrix and a target, return the number of non-empty submatrices that sum to target.\n A submatrix x1, y1, x2, y2 is the set of all cells matrix[x][y] with x1 <= x <= x2 and y1 <= y <= y2.\n Two submatrices (x1, y1, x2, y2) and (x1', y1', x2', y2') are different if they have some coordinate that is different: for example, if x1 != x1'.\n Example 1:\n Input: matrix = [[0,1,0],[1,1,1],[0,1,0]], target = 0\n Output: 4\n Explanation: The four 1x1 submatrices that only contain 0.\n Example 2:\n Input: matrix = [[1,-1],[-1,1]], target = 0\n Output: 5\n Explanation: The two 1x2 submatrices, plus the two 2x1 submatrices, plus the 2x2 submatrix.\n Example 3:\n Input: matrix = [[904]], target = 0\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1071, - "title": "Greatest Common Divisor of Strings", - "question": "class Solution:\n def gcdOfStrings(self, str1: str, str2: str) -> str:\n \"\"\"\n For two strings s and t, we say \"t divides s\" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times).\n Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.\n Example 1:\n Input: str1 = \"ABCABC\", str2 = \"ABC\"\n Output: \"ABC\"\n Example 2:\n Input: str1 = \"ABABAB\", str2 = \"ABAB\"\n Output: \"AB\"\n Example 3:\n Input: str1 = \"LEET\", str2 = \"CODE\"\n Output: \"\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1072, - "title": "Flip Columns For Maximum Number of Equal Rows", - "question": "class Solution:\n def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n binary matrix matrix.\n You 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).\n Return the maximum number of rows that have all values equal after some number of flips.\n Example 1:\n Input: matrix = [[0,1],[1,1]]\n Output: 1\n Explanation: After flipping no values, 1 row has all values equal.\n Example 2:\n Input: matrix = [[0,1],[1,0]]\n Output: 2\n Explanation: After flipping values in the first column, both rows have equal values.\n Example 3:\n Input: matrix = [[0,0,0],[0,0,1],[1,1,0]]\n Output: 2\n Explanation: After flipping values in the first two columns, the last two rows have equal values.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1073, - "title": "Adding Two Negabinary Numbers", - "question": "class Solution:\n def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:\n \"\"\"\n Given two numbers arr1 and arr2 in base -2, return the result of adding them together.\n Each 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.\n Return 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:\n Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1]\n Output: [1,0,0,0,0]\n Explanation: arr1 represents 11, arr2 represents 5, the output represents 16.\n Example 2:\n Input: arr1 = [0], arr2 = [0]\n Output: [0]\n Example 3:\n Input: arr1 = [0], arr2 = [1]\n Output: [1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1078, - "title": "Occurrences After Bigram", - "question": "class Solution:\n def findOcurrences(self, text: str, first: str, second: str) -> List[str]:\n \"\"\"\n 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.\n Return an array of all the words third for each occurrence of \"first second third\".\n Example 1:\n Input: text = \"alice is a good girl she is a good student\", first = \"a\", second = \"good\"\n Output: [\"girl\",\"student\"]\n Example 2:\n Input: text = \"we will we will rock you\", first = \"we\", second = \"will\"\n Output: [\"we\",\"rock\"]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1080, - "title": "Insufficient Nodes in Root to Leaf Paths", - "question": "class Solution:\n def sufficientSubset(self, root: Optional[TreeNode], limit: int) -> Optional[TreeNode]:\n \"\"\"\n 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.\n A node is insufficient if every root to leaf path intersecting this node has a sum strictly less than limit.\n A leaf is a node with no children.\n Example 1:\n Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1\n Output: [1,2,3,4,null,null,7,8,9,null,14]\n Example 2:\n Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22\n Output: [5,4,8,11,null,17,4,7,null,null,null,5]\n Example 3:\n Input: root = [1,2,-3,-5,null,4,null], limit = -1\n Output: [1,null,-3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1081, - "title": "Smallest Subsequence of Distinct Characters", - "question": "class Solution:\n def smallestSubsequence(self, s: str) -> str:\n \"\"\"\n Given a string s, return the lexicographically smallest subsequence of s that contains all the distinct characters of s exactly once.\n Example 1:\n Input: s = \"bcabc\"\n Output: \"abc\"\n Example 2:\n Input: s = \"cbacdcbc\"\n Output: \"acdb\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1079, - "title": "Letter Tile Possibilities", - "question": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n \"\"\"\n You have n tiles, where each tile has one letter tiles[i] printed on it.\n Return the number of possible non-empty sequences of letters you can make using the letters printed on those tiles.\n Example 1:\n Input: tiles = \"AAB\"\n Output: 8\n Explanation: The possible sequences are \"A\", \"B\", \"AA\", \"AB\", \"BA\", \"AAB\", \"ABA\", \"BAA\".\n Example 2:\n Input: tiles = \"AAABBC\"\n Output: 188\n Example 3:\n Input: tiles = \"V\"\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1089, - "title": "Duplicate Zeros", - "question": "class Solution:\n def duplicateZeros(self, arr: List[int]) -> None:\n \"\"\"\n Do not return anything, modify arr in-place instead.\n Given a fixed-length integer array arr, duplicate each occurrence of zero, shifting the remaining elements to the right.\n Note that elements beyond the length of the original array are not written. Do the above modifications to the input array in place and do not return anything.\n Example 1:\n Input: arr = [1,0,2,3,0,4,5,0]\n Output: [1,0,0,2,3,0,0,4]\n Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]\n Example 2:\n Input: arr = [1,2,3]\n Output: [1,2,3]\n Explanation: After calling your function, the input array is modified to: [1,2,3]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1090, - "title": "Largest Values From Labels", - "question": "class Solution:\n def largestValsFromLabels(self, values: List[int], labels: List[int], numWanted: int, useLimit: int) -> int:\n \"\"\"\n 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.\n Choose a subset s of the n elements such that:\n The size of the subset s is less than or equal to numWanted.\n There are at most useLimit items with the same label in s.\n The score of a subset is the sum of the values in the subset.\n Return the maximum score of a subset s.\n Example 1:\n Input: values = [5,4,3,2,1], labels = [1,1,2,2,3], numWanted = 3, useLimit = 1\n Output: 9\n Explanation: The subset chosen is the first, third, and fifth items.\n Example 2:\n Input: values = [5,4,3,2,1], labels = [1,3,3,3,2], numWanted = 3, useLimit = 2\n Output: 12\n Explanation: The subset chosen is the first, second, and third items.\n Example 3:\n Input: values = [9,8,8,7,6], labels = [0,0,0,1,1], numWanted = 3, useLimit = 1\n Output: 16\n Explanation: The subset chosen is the first and fourth items.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1092, - "title": "Shortest Common Supersequence ", - "question": "class Solution:\n def shortestCommonSupersequence(self, str1: str, str2: str) -> str:\n \"\"\"\n 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.\n A 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:\n Input: str1 = \"abac\", str2 = \"cab\"\n Output: \"cabac\"\n Explanation: \n str1 = \"abac\" is a subsequence of \"cabac\" because we can delete the first \"c\".\n str2 = \"cab\" is a subsequence of \"cabac\" because we can delete the last \"ac\".\n The answer provided is the shortest such string that satisfies these properties.\n Example 2:\n Input: str1 = \"aaaaaaaa\", str2 = \"aaaaaaaa\"\n Output: \"aaaaaaaa\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1091, - "title": "Shortest Path in Binary Matrix", - "question": "class Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n A 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:\n All the visited cells of the path are 0.\n All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).\n The length of a clear path is the number of visited cells of this path.\n Example 1:\n Input: grid = [[0,1],[1,0]]\n Output: 2\n Example 2:\n Input: grid = [[0,0,0],[1,1,0],[1,1,0]]\n Output: 4\n Example 3:\n Input: grid = [[1,0,0],[1,1,0],[1,1,0]]\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1093, - "title": "Statistics from a Large Sample", - "question": "class Solution:\n def sampleStats(self, count: List[int]) -> List[float]:\n \"\"\"\n 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.\n Calculate the following statistics:\n minimum: The minimum element in the sample.\n maximum: The maximum element in the sample.\n mean: The average of the sample, calculated as the total sum of all elements divided by the total number of elements.\n median:\n If the sample has an odd number of elements, then the median is the middle element once the sample is sorted.\n If the sample has an even number of elements, then the median is the average of the two middle elements once the sample is sorted.\n mode: The number that appears the most in the sample. It is guaranteed to be unique.\n Return 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:\n Input: 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]\n Output: [1.00000,3.00000,2.37500,2.50000,3.00000]\n Explanation: The sample represented by count is [1,2,2,2,3,3,3,3].\n The minimum and maximum are 1 and 3 respectively.\n The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375.\n Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5.\n The mode is 3 as it appears the most in the sample.\n Example 2:\n Input: 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]\n Output: [1.00000,4.00000,2.18182,2.00000,1.00000]\n Explanation: The sample represented by count is [1,1,1,1,2,2,2,3,3,4,4].\n The minimum and maximum are 1 and 4 respectively.\n The 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).\n Since the size of the sample is odd, the median is the middle element 2.\n The mode is 1 as it appears the most in the sample.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1094, - "title": "Car Pooling", - "question": "class Solution:\n def carPooling(self, trips: List[List[int]], capacity: int) -> bool:\n \"\"\"\n There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).\n You 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.\n Return true if it is possible to pick up and drop off all passengers for all the given trips, or false otherwise.\n Example 1:\n Input: trips = [[2,1,5],[3,3,7]], capacity = 4\n Output: false\n Example 2:\n Input: trips = [[2,1,5],[3,3,7]], capacity = 5\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1095, - "title": "Find in Mountain Array", - "question": " \"\"\"\n (This problem is an interactive problem.)\n You may recall that an array arr is a mountain array if and only if:\n arr.length >= 3\n There exists some i with 0 < i < arr.length - 1 such that:\n arr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.\n You cannot access the mountain array directly. You may only access the array using a MountainArray interface:\n MountainArray.get(k) returns the element of the array at index k (0-indexed).\n MountainArray.length() returns the length of the array.\n Submissions 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:\n Input: array = [1,2,3,4,5,3,1], target = 3\n Output: 2\n Explanation: 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.\n Example 2:\n Input: array = [0,1,2,4,2,1], target = 3\n Output: -1\n Explanation: 3 does not exist in the array, so we return -1.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1117, - "title": "Building H2O", - "question": "class H2O:\n def __init__(self):\n pass\n def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:\n releaseHydrogen()\n def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None:\n releaseOxygen()\n \"\"\"\n There are two kinds of threads: oxygen and hydrogen. Your goal is to group these threads to form water molecules.\n There is a barrier where each thread has to wait until a complete molecule can be formed. Hydrogen and oxygen threads will be given releaseHydrogen and releaseOxygen methods respectively, which will allow them to pass the barrier. These threads should pass the barrier in groups of three, and they must immediately bond with each other to form a water molecule. You must guarantee that all the threads from one molecule bond before any other threads from the next molecule do.\n In other words:\n If an oxygen thread arrives at the barrier when no hydrogen threads are present, it must wait for two hydrogen threads.\n If a hydrogen thread arrives at the barrier when no other threads are present, it must wait for an oxygen thread and another hydrogen thread.\n We do not have to worry about matching the threads up explicitly; the threads do not necessarily know which other threads they are paired up with. The key is that threads pass the barriers in complete sets; thus, if we examine the sequence of threads that bind and divide them into groups of three, each group should contain one oxygen and two hydrogen threads.\n Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.\n Example 1:\n Input: water = \"HOH\"\n Output: \"HHO\"\n Explanation: \"HOH\" and \"OHH\" are also valid answers.\n Example 2:\n Input: water = \"OOHHHH\"\n Output: \"HHOHHO\"\n Explanation: \"HOHHHO\", \"OHHHHO\", \"HHOHOH\", \"HOHHOH\", \"OHHHOH\", \"HHOOHH\", \"HOHOHH\" and \"OHHOHH\" are also valid answers.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1115, - "title": "Print FooBar Alternately", - "question": "class FooBar:\n def __init__(self, n):\n self.n = n\n def foo(self, printFoo: 'Callable[[], None]') -> None:\n for i in range(self.n):\n printFoo()\n def bar(self, printBar: 'Callable[[], None]') -> None:\n for i in range(self.n):\n printBar()\n \"\"\"\n Suppose you are given the following code:\n class FooBar {\n public void foo() {\n for (int i = 0; i < n; i++) {\n print(\"foo\");\n }\n }\n public void bar() {\n for (int i = 0; i < n; i++) {\n print(\"bar\");\n }\n }\n }\n The same instance of FooBar will be passed to two different threads:\n thread A will call foo(), while\n thread B will call bar().\n Modify the given program to output \"foobar\" n times.\n Example 1:\n Input: n = 1\n Output: \"foobar\"\n Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().\n \"foobar\" is being output 1 time.\n Example 2:\n Input: n = 2\n Output: \"foobarfoobar\"\n Explanation: \"foobar\" is being output 2 times.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1096, - "title": "Brace Expansion II", - "question": "class Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n \"\"\"\n Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.\n The grammar can best be understood through simple examples:\n Single letters represent a singleton set containing that word.\n R(\"a\") = {\"a\"}\n R(\"w\") = {\"w\"}\n When we take a comma-delimited list of two or more expressions, we take the union of possibilities.\n R(\"{a,b,c}\") = {\"a\",\"b\",\"c\"}\n R(\"{{a,b},{b,c}}\") = {\"a\",\"b\",\"c\"} (notice the final set only contains each word at most once)\n When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.\n R(\"{a,b}{c,d}\") = {\"ac\",\"ad\",\"bc\",\"bd\"}\n R(\"a{b,c}{d,e}f{g,h}\") = {\"abdfg\", \"abdfh\", \"abefg\", \"abefh\", \"acdfg\", \"acdfh\", \"acefg\", \"acefh\"}\n Formally, the three rules for our grammar:\n For every lowercase letter x, we have R(x) = {x}.\n For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) \u222a R(e2) \u222a ...\n For 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.\n Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.\n Example 1:\n Input: expression = \"{a,b}{c,{d,e}}\"\n Output: [\"ac\",\"ad\",\"ae\",\"bc\",\"bd\",\"be\"]\n Example 2:\n Input: expression = \"{{a,z},a{b,c},{ab,z}}\"\n Output: [\"a\",\"ab\",\"ac\",\"z\"]\n Explanation: Each distinct word is written only once in the final answer.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1104, - "title": "Path In Zigzag Labelled Binary Tree", - "question": "class Solution:\n def pathInZigZagTree(self, label: int) -> List[int]:\n \"\"\"\n In an infinite binary tree where every node has two children, the nodes are labelled in row order.\n In 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.\n Given 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:\n Input: label = 14\n Output: [1,3,4,14]\n Example 2:\n Input: label = 26\n Output: [1,2,6,10,26]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1103, - "title": "Distribute Candies to People", - "question": "class Solution:\n def distributeCandies(self, candies: int, num_people: int) -> List[int]:\n \"\"\"\n We distribute some number of candies, to a row of n = num_people people in the following way:\n We 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.\n Then, 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.\n This 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).\n Return an array (of length num_people and sum candies) that represents the final distribution of candies.\n Example 1:\n Input: candies = 7, num_people = 4\n Output: [1,2,3,1]\n Explanation:\n On the first turn, ans[0] += 1, and the array is [1,0,0,0].\n On the second turn, ans[1] += 2, and the array is [1,2,0,0].\n On the third turn, ans[2] += 3, and the array is [1,2,3,0].\n On the fourth turn, ans[3] += 1 (because there is only one candy left), and the final array is [1,2,3,1].\n Example 2:\n Input: candies = 10, num_people = 3\n Output: [5,2,3]\n Explanation: \n On the first turn, ans[0] += 1, and the array is [1,0,0].\n On the second turn, ans[1] += 2, and the array is [1,2,0].\n On the third turn, ans[2] += 3, and the array is [1,2,3].\n On the fourth turn, ans[0] += 4, and the final array is [5,2,3].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1105, - "title": "Filling Bookcase Shelves", - "question": "class Solution:\n def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:\n \"\"\"\n 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.\n We want to place these books in order onto bookcase shelves that have a total width shelfWidth.\n We 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.\n Note 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.\n For 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.\n Return the minimum possible height that the total bookshelf can be after placing shelves in this manner.\n Example 1:\n Input: books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelfWidth = 4\n Output: 6\n Explanation:\n The sum of the heights of the 3 shelves is 1 + 3 + 2 = 6.\n Notice that book number 2 does not have to be on the first shelf.\n Example 2:\n Input: books = [[1,3],[2,4],[3,2]], shelfWidth = 6\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1106, - "title": "Parsing A Boolean Expression", - "question": "class Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n \"\"\"\n 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.\n Given a string expression that represents a boolean expression, return the evaluation of that expression.\n It is guaranteed that the given expression is valid and follows the given rules.\n Example 1:\n Input: expression = \"&(|(f))\"\n Output: false\n Explanation: \n First, evaluate |(f) --> f. The expression is now \"&(f)\".\n Then, evaluate &(f) --> f. The expression is now \"f\".\n Finally, return false.\n Example 2:\n Input: expression = \"|(f,f,f,t)\"\n Output: true\n Explanation: The evaluation of (false OR false OR false OR true) is true.\n Example 3:\n Input: expression = \"!(&(f,t))\"\n Output: true\n Explanation: \n First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now \"!(f)\".\n Then, evaluate !(f) --> NOT false --> true. We return true.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1114, - "title": "Print in Order", - "question": "class Foo:\n def __init__(self):\n pass\n def first(self, printFirst: 'Callable[[], None]') -> None:\n printFirst()\n def second(self, printSecond: 'Callable[[], None]') -> None:\n printSecond()\n def third(self, printThird: 'Callable[[], None]') -> None:\n printThird()\n \"\"\"\n Suppose we have a class:\n public class Foo {\n public void first() { print(\"first\"); }\n public void second() { print(\"second\"); }\n public void third() { print(\"third\"); }\n }\n The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().\n Note:\n We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seem to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.\n Example 1:\n Input: nums = [1,2,3]\n Output: \"firstsecondthird\"\n Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). \"firstsecondthird\" is the correct output.\n Example 2:\n Input: nums = [1,3,2]\n Output: \"firstsecondthird\"\n Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). \"firstsecondthird\" is the correct output.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1108, - "title": "Defanging an IP Address", - "question": "class Solution:\n def defangIPaddr(self, address: str) -> str:\n \"\"\"\n Given a valid (IPv4) IP address, return a defanged version of that IP address.\r\n A defanged IP address replaces every period \".\" with \"[.]\".\r\n Example 1:\r\n Input: address = \"1.1.1.1\"\r\n Output: \"1[.]1[.]1[.]1\"\r\n Example 2:\r\n Input: address = \"255.100.50.0\"\r\n Output: \"255[.]100[.]50[.]0\"\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1109, - "title": "Corporate Flight Bookings", - "question": "class Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n \"\"\"\n There are n flights that are labeled from 1 to n.\n You 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.\n Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.\n Example 1:\n Input: bookings = [[1,2,10],[2,3,20],[2,5,25]], n = 5\n Output: [10,55,45,25,25]\n Explanation:\n Flight labels: 1 2 3 4 5\n Booking 1 reserved: 10 10\n Booking 2 reserved: 20 20\n Booking 3 reserved: 25 25 25 25\n Total seats: 10 55 45 25 25\n Hence, answer = [10,55,45,25,25]\n Example 2:\n Input: bookings = [[1,2,10],[2,2,15]], n = 2\n Output: [10,25]\n Explanation:\n Flight labels: 1 2\n Booking 1 reserved: 10 10\n Booking 2 reserved: 15\n Total seats: 10 25\n Hence, answer = [10,25]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1110, - "title": "Delete Nodes And Return Forest", - "question": "class Solution:\n def delNodes(self, root: Optional[TreeNode], to_delete: List[int]) -> List[TreeNode]:\n \"\"\"\n Given the root of a binary tree, each node in the tree has a distinct value.\n After deleting all nodes with a value in to_delete, we are left with a forest (a disjoint union of trees).\n Return the roots of the trees in the remaining forest. You may return the result in any order.\n Example 1:\n Input: root = [1,2,3,4,5,6,7], to_delete = [3,5]\n Output: [[1,2,null,4],[6],[7]]\n Example 2:\n Input: root = [1,2,4,null,3], to_delete = [3]\n Output: [[1,2,4]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1111, - "title": "Maximum Nesting Depth of Two Valid Parentheses Strings", - "question": "class Solution:\n def maxDepthAfterSplit(self, seq: str) -> List[int]:\n \"\"\"\n A string is a valid parentheses string (denoted VPS) if and only if it consists of \"(\" and \")\" characters only, and:\r\n It is the empty string, or\r\n It can be written as AB (A concatenated with B), where A and B are VPS's, or\r\n It can be written as (A), where A is a VPS.\r\n We can similarly define the nesting depth depth(S) of any VPS S as follows:\r\n depth(\"\") = 0\r\n depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's\r\n depth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\r\n For example, \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\r\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).\r\n Now choose any such A and B such that max(depth(A), depth(B)) is the minimum possible value.\r\n Return 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.\r\n Example 1:\n Input: seq = \"(()())\"\n Output: [0,1,1,1,1,0]\n Example 2:\n Input: seq = \"()(())()\"\n Output: [0,0,0,1,1,0,1,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1619, - "title": "Mean of Array After Removing Some Elements", - "question": "class Solution:\n def trimMean(self, arr: List[int]) -> float:\n \"\"\"\n Given an integer array arr, return the mean of the remaining integers after removing the smallest 5% and the largest 5% of the elements.\n Answers within 10-5 of the actual answer will be considered accepted.\n Example 1:\n Input: arr = [1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3]\n Output: 2.00000\n Explanation: After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.\n Example 2:\n Input: arr = [6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0]\n Output: 4.00000\n Example 3:\n Input: 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]\n Output: 4.77778\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1286, - "title": "Iterator for Combination", - "question": "class CombinationIterator:\n def __init__(self, characters: str, combinationLength: int):\n def next(self) -> str:\n def hasNext(self) -> bool:\n \"\"\"\n Design the CombinationIterator class:\n CombinationIterator(string characters, int combinationLength) Initializes the object with a string characters of sorted distinct lowercase English letters and a number combinationLength as arguments.\n next() Returns the next combination of length combinationLength in lexicographical order.\n hasNext() Returns true if and only if there exists a next combination.\n Example 1:\n Input\n [\"CombinationIterator\", \"next\", \"hasNext\", \"next\", \"hasNext\", \"next\", \"hasNext\"]\n [[\"abc\", 2], [], [], [], [], [], []]\n Output\n [null, \"ab\", true, \"ac\", true, \"bc\", false]\n Explanation\n CombinationIterator itr = new CombinationIterator(\"abc\", 2);\n itr.next(); // return \"ab\"\n itr.hasNext(); // return True\n itr.next(); // return \"ac\"\n itr.hasNext(); // return True\n itr.next(); // return \"bc\"\n itr.hasNext(); // return False\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1291, - "title": "Sequential Digits", - "question": "class Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n \"\"\"\n An integer has sequential digits if and only if each digit in the number is one more than the previous digit.\n Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.\n Example 1:\n Input: low = 100, high = 300\n Output: [123,234]\n Example 2:\n Input: low = 1000, high = 13000\n Output: [1234,2345,3456,4567,5678,6789,12345]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1116, - "title": "Print Zero Even Odd", - "question": "class ZeroEvenOdd:\n def __init__(self, n):\n self.n = n\n def zero(self, printNumber: 'Callable[[int], None]') -> None:\n def even(self, printNumber: 'Callable[[int], None]') -> None:\n def odd(self, printNumber: 'Callable[[int], None]') -> None:\n \"\"\"\n You have a function printNumber that can be called with an integer parameter and prints it to the console.\n For example, calling printNumber(7) prints 7 to the console.\n You are given an instance of the class ZeroEvenOdd that has three functions: zero, even, and odd. The same instance of ZeroEvenOdd will be passed to three different threads:\n Thread A: calls zero() that should only output 0's.\n Thread B: calls even() that should only output even numbers.\n Thread C: calls odd() that should only output odd numbers.\n Modify the given class to output the series \"010203040506...\" where the length of the series must be 2n.\n Implement the ZeroEvenOdd class:\n ZeroEvenOdd(int n) Initializes the object with the number n that represents the numbers that should be printed.\n void zero(printNumber) Calls printNumber to output one zero.\n void even(printNumber) Calls printNumber to output one even number.\n void odd(printNumber) Calls printNumber to output one odd number.\n Example 1:\n Input: n = 2\n Output: \"0102\"\n Explanation: There are three threads being fired asynchronously.\n One of them calls zero(), the other calls even(), and the last one calls odd().\n \"0102\" is the correct output.\n Example 2:\n Input: n = 5\n Output: \"0102030405\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1122, - "title": "Relative Sort Array", - "question": "class Solution:\n def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:\n \"\"\"\n Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1.\n Sort 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:\n Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]\n Output: [2,2,2,1,4,3,3,9,6,7,19]\n Example 2:\n Input: arr1 = [28,6,22,8,44,17], arr2 = [22,28,8,6]\n Output: [22,28,8,6,17,44]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1123, - "title": "Lowest Common Ancestor of Deepest Leaves", - "question": "class Solution:\n def lcaDeepestLeaves(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n \"\"\"\n Given the root of a binary tree, return the lowest common ancestor of its deepest leaves.\n Recall that:\n The node of a binary tree is a leaf if and only if it has no children\n The 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.\n The 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:\n Input: root = [3,5,1,6,2,0,8,null,null,7,4]\n Output: [2,7,4]\n Explanation: We return the node with value 2, colored in yellow in the diagram.\n The nodes coloured in blue are the deepest leaf-nodes of the tree.\n Note that nodes 6, 0, and 8 are also leaf nodes, but the depth of them is 2, but the depth of nodes 7 and 4 is 3.\n Example 2:\n Input: root = [1]\n Output: [1]\n Explanation: The root is the deepest node in the tree, and it's the lca of itself.\n Example 3:\n Input: root = [0,1,3,null,2]\n Output: [2]\n Explanation: The deepest leaf node in the tree is 2, the lca of one node is itself.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1124, - "title": "Longest Well-Performing Interval", - "question": "class Solution:\n def longestWPI(self, hours: List[int]) -> int:\n \"\"\"\n We are given hours, a list of the number of hours worked per day for a given employee.\n A day is considered to be a tiring day if and only if the number of hours worked is (strictly) greater than 8.\n A 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.\n Return the length of the longest well-performing interval.\n Example 1:\n Input: hours = [9,9,6,0,6,6,9]\n Output: 3\n Explanation: The longest well-performing interval is [9,9,6].\n Example 2:\n Input: hours = [6,6,6]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1125, - "title": "Smallest Sufficient Team", - "question": "class Solution:\n def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:\n \"\"\"\n In a project, you have a list of required skills req_skills, and a list of people. The ith person people[i] contains a list of skills that the person has.\n Consider a sufficient team: a set of people such that for every required skill in req_skills, there is at least one person in the team who has that skill. We can represent these teams by the index of each person.\n For example, team = [0, 1, 3] represents the people with skills people[0], people[1], and people[3].\n Return any sufficient team of the smallest possible size, represented by the index of each person. You may return the answer in any order.\n It is guaranteed an answer exists.\n Example 1:\n Input: req_skills = [\"java\",\"nodejs\",\"reactjs\"], people = [[\"java\"],[\"nodejs\"],[\"nodejs\",\"reactjs\"]]\n Output: [0,2]\n Example 2:\n Input: req_skills = [\"algorithms\",\"math\",\"java\",\"reactjs\",\"csharp\",\"aws\"], people = [[\"algorithms\",\"math\",\"java\"],[\"algorithms\",\"math\",\"reactjs\"],[\"java\",\"csharp\",\"aws\"],[\"reactjs\",\"csharp\"],[\"csharp\",\"math\"],[\"aws\",\"java\"]]\n Output: [1,2]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1287, - "title": "Element Appearing More Than 25% In Sorted Array", - "question": "class Solution:\n def findSpecialInteger(self, arr: List[int]) -> int:\n \"\"\"\n 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:\n Input: arr = [1,2,2,6,6,6,6,7,10]\n Output: 6\n Example 2:\n Input: arr = [1,1]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1288, - "title": "Remove Covered Intervals", - "question": "class Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n \"\"\"\n 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.\n The interval [a, b) is covered by the interval [c, d) if and only if c <= a and b <= d.\n Return the number of remaining intervals.\n Example 1:\n Input: intervals = [[1,4],[3,6],[2,8]]\n Output: 2\n Explanation: Interval [3,6] is covered by [2,8], therefore it is removed.\n Example 2:\n Input: intervals = [[1,4],[2,3]]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1627, - "title": "Graph Connectivity With Threshold", - "question": "class Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n \"\"\"\n We have n cities labeled from 1 to n. Two different cities with labels x and y are directly connected by a bidirectional road if and only if x and y share a common divisor strictly greater than some threshold. More formally, cities with labels x and y have a road between them if there exists an integer z such that all of the following are true:\n x % z == 0,\n y % z == 0, and\n z > threshold.\n Given the two integers, n and threshold, and an array of queries, you must determine for each queries[i] = [ai, bi] if cities ai and bi are connected directly or indirectly. (i.e. there is some path between them).\n Return an array answer, where answer.length == queries.length and answer[i] is true if for the ith query, there is a path between ai and bi, or answer[i] is false if there is no path.\n Example 1:\n Input: n = 6, threshold = 2, queries = [[1,4],[2,5],[3,6]]\n Output: [false,false,true]\n Explanation: The divisors for each number:\n 1: 1\n 2: 1, 2\n 3: 1, 3\n 4: 1, 2, 4\n 5: 1, 5\n 6: 1, 2, 3, 6\n Using the underlined divisors above the threshold, only cities 3 and 6 share a common divisor, so they are the\n only ones directly connected. The result of each query:\n [1,4] 1 is not connected to 4\n [2,5] 2 is not connected to 5\n [3,6] 3 is connected to 6 through path 3--6\n Example 2:\n Input: n = 6, threshold = 0, queries = [[4,5],[3,4],[3,2],[2,6],[1,3]]\n Output: [true,true,true,true,true]\n Explanation: The divisors for each number are the same as the previous example. However, since the threshold is 0,\n all divisors can be used. Since all numbers share 1 as a divisor, all cities are connected.\n Example 3:\n Input: n = 5, threshold = 1, queries = [[4,5],[4,5],[3,2],[2,3],[3,4]]\n Output: [false,false,false,false,false]\n Explanation: Only cities 2 and 4 share a common divisor 2 which is strictly greater than the threshold 1, so they are the only ones directly connected.\n Please notice that there can be multiple queries for the same pair of nodes [x, y], and that the query [x, y] is equivalent to the query [y, x].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1289, - "title": "Minimum Falling Path Sum II", - "question": "class Solution:\n def minFallingPathSum(self, grid: List[List[int]]) -> int:\n \"\"\"\n Given an n x n integer matrix grid, return the minimum sum of a falling path with non-zero shifts.\n A falling path with non-zero shifts is a choice of exactly one element from each row of grid such that no two elements chosen in adjacent rows are in the same column.\n Example 1:\n Input: arr = [[1,2,3],[4,5,6],[7,8,9]]\n Output: 13\n Explanation: \n The possible falling paths are:\n [1,5,9], [1,5,7], [1,6,7], [1,6,8],\n [2,4,8], [2,4,9], [2,6,7], [2,6,8],\n [3,4,8], [3,4,9], [3,5,7], [3,5,9]\n The falling path with the smallest sum is [1,5,7], so the answer is 13.\n Example 2:\n Input: grid = [[7]]\n Output: 7\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1128, - "title": "Number of Equivalent Domino Pairs", - "question": "class Solution:\n def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].\n Example 1:\n Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]\n Output: 1\n Example 2:\n Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]\n Output: 3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1130, - "title": "Minimum Cost Tree From Leaf Values", - "question": "class Solution:\n def mctFromLeafValues(self, arr: List[int]) -> int:\n \"\"\"\n Given an array arr of positive integers, consider all binary trees such that:\n Each node has either 0 or 2 children;\n The values of arr correspond to the values of each leaf in an in-order traversal of the tree.\n The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.\n Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.\n A node is a leaf if and only if it has zero children.\n Example 1:\n Input: arr = [6,2,4]\n Output: 32\n Explanation: There are two possible trees shown.\n The first has a non-leaf node sum 36, and the second has non-leaf node sum 32.\n Example 2:\n Input: arr = [4,11]\n Output: 44\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1129, - "title": "Shortest Path with Alternating Colors", - "question": "class Solution:\n def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an integer n, the number of nodes in a directed graph where the nodes are labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.\n You are given two arrays redEdges and blueEdges where:\n redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai to node bi in the graph, and\n blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj to node vj in the graph.\n Return an array answer of length n, where each answer[x] is the length of the shortest path from node 0 to node x such that the edge colors alternate along the path, or -1 if such a path does not exist.\n Example 1:\n Input: n = 3, redEdges = [[0,1],[1,2]], blueEdges = []\n Output: [0,1,-1]\n Example 2:\n Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]\n Output: [0,1,-1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1131, - "title": "Maximum of Absolute Value Expression", - "question": "class Solution:\n def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:\n \"\"\"\n Given two arrays of integers with equal lengths, return the maximum value of:\r\n |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|\r\n where the maximum is taken over all 0 <= i, j < arr1.length.\r\n Example 1:\n Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6]\n Output: 13\n Example 2:\n Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]\n Output: 20\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1299, - "title": "Replace Elements with Greatest Element on Right Side", - "question": "class Solution:\n def replaceElements(self, arr: List[int]) -> List[int]:\n \"\"\"\n 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.\n After doing so, return the array.\n Example 1:\n Input: arr = [17,18,5,4,6,1]\n Output: [18,6,6,6,1,-1]\n Explanation: \n - index 0 --> the greatest element to the right of index 0 is index 1 (18).\n - index 1 --> the greatest element to the right of index 1 is index 4 (6).\n - index 2 --> the greatest element to the right of index 2 is index 4 (6).\n - index 3 --> the greatest element to the right of index 3 is index 4 (6).\n - index 4 --> the greatest element to the right of index 4 is index 5 (1).\n - index 5 --> there are no elements to the right of index 5, so we put -1.\n Example 2:\n Input: arr = [400]\n Output: [-1]\n Explanation: There are no elements to the right of index 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1300, - "title": "Sum of Mutated Array Closest to Target", - "question": "class Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n \"\"\"\n 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.\n In case of a tie, return the minimum such integer.\n Notice that the answer is not neccesarilly a number from arr.\n Example 1:\n Input: arr = [4,9,3], target = 10\n Output: 3\n Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.\n Example 2:\n Input: arr = [2,3,5], target = 10\n Output: 5\n Example 3:\n Input: arr = [60864,25176,27249,21296,20204], target = 56803\n Output: 11361\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1301, - "title": "Number of Paths with Max Score", - "question": "class Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n \"\"\"\n 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'.\r\n You need to reach the top left square marked with the character 'E'. The rest of the squares are labeled either with a numeric character 1, 2, ..., 9 or with an obstacle 'X'. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.\r\n Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo 10^9 + 7.\r\n In case there is no path, return [0, 0].\r\n Example 1:\r\n Input: board = [\"E23\",\"2X2\",\"12S\"]\r\n Output: [7,1]\r\n Example 2:\r\n Input: board = [\"E12\",\"1X1\",\"21S\"]\r\n Output: [4,2]\r\n Example 3:\r\n Input: board = [\"E11\",\"XXX\",\"11S\"]\r\n Output: [0,0]\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1137, - "title": "N-th Tribonacci Number", - "question": "class Solution:\n def tribonacci(self, n: int) -> int:\n \"\"\"\n The Tribonacci sequence Tn is defined as follows: \r\n T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.\r\n Given n, return the value of Tn.\r\n Example 1:\r\n Input: n = 4\r\n Output: 4\r\n Explanation:\r\n T_3 = 0 + 1 + 1 = 2\r\n T_4 = 1 + 1 + 2 = 4\r\n Example 2:\r\n Input: n = 25\r\n Output: 1389537\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1138, - "title": "Alphabet Board Path", - "question": "class Solution:\n def alphabetBoardPath(self, target: str) -> str:\n \"\"\"\n On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].\r\n Here, board = [\"abcde\", \"fghij\", \"klmno\", \"pqrst\", \"uvwxy\", \"z\"], as shown in the diagram below.\r\n We may make the following moves:\r\n 'U' moves our position up one row, if the position exists on the board;\r\n 'D' moves our position down one row, if the position exists on the board;\r\n 'L' moves our position left one column, if the position exists on the board;\r\n 'R' moves our position right one column, if the position exists on the board;\r\n '!' adds the character board[r][c] at our current position (r, c) to the answer.\r\n (Here, the only positions that exist on the board are positions with letters on them.)\r\n Return 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.\r\n Example 1:\r\n Input: target = \"leet\"\r\n Output: \"DDR!UURRR!!DDD!\"\r\n Example 2:\r\n Input: target = \"code\"\r\n Output: \"RR!DDRR!UUL!R!\"\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1139, - "title": "Largest 1-Bordered Square", - "question": "class Solution:\n def largest1BorderedSquare(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\r\n Example 1:\r\n Input: grid = [[1,1,1],[1,0,1],[1,1,1]]\r\n Output: 9\r\n Example 2:\r\n Input: grid = [[1,1,0,0]]\r\n Output: 1\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1140, - "title": "Stone Game II", - "question": "class Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n \"\"\"\n 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. \n Alice and Bob take turns, with Alice starting first. Initially, M = 1.\n On 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).\n The game continues until all the stones have been taken.\n Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.\n Example 1:\n Input: piles = [2,7,9,4,4]\n Output: 10\n Explanation: 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. \n Example 2:\n Input: piles = [1,2,3,4,5,100]\n Output: 104\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1313, - "title": "Decompress Run-Length Encoded List", - "question": "class Solution:\n def decompressRLElist(self, nums: List[int]) -> List[int]:\n \"\"\"\n We are given a list nums of integers representing a list compressed with run-length encoding.\n Consider 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.\n Return the decompressed list.\n Example 1:\n Input: nums = [1,2,3,4]\n Output: [2,4,4,4]\n Explanation: The first pair [1,2] means we have freq = 1 and val = 2 so we generate the array [2].\n The second pair [3,4] means we have freq = 3 and val = 4 so we generate [4,4,4].\n At the end the concatenation [2] + [4,4,4] is [2,4,4,4].\n Example 2:\n Input: nums = [1,1,2,3]\n Output: [1,3,3]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1314, - "title": "Matrix Block Sum", - "question": "class Solution:\n def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:\n \"\"\"\n 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:\n i - k <= r <= i + k,\n j - k <= c <= j + k, and\n (r, c) is a valid position in the matrix.\n Example 1:\n Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 1\n Output: [[12,21,16],[27,45,33],[24,39,28]]\n Example 2:\n Input: mat = [[1,2,3],[4,5,6],[7,8,9]], k = 2\n Output: [[45,45,45],[45,45,45],[45,45,45]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1315, - "title": "Sum of Nodes with Even-Valued Grandparent", - "question": "class Solution:\n def sumEvenGrandparent(self, root: TreeNode) -> int:\n \"\"\"\n 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.\n A grandparent of a node is the parent of its parent if it exists.\n Example 1:\n Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\n Output: 18\n Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.\n Example 2:\n Input: root = [1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1316, - "title": "Distinct Echo Substrings", - "question": "class Solution:\n def distinctEchoSubstrings(self, text: str) -> int:\n \"\"\"\n 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:\n Input: text = \"abcabcabc\"\n Output: 3\n Explanation: The 3 substrings are \"abcabc\", \"bcabca\" and \"cabcab\".\n Example 2:\n Input: text = \"leetcodeleetcode\"\n Output: 2\n Explanation: The 2 substrings are \"ee\" and \"leetcodeleetcode\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1144, - "title": "Decrease Elements To Make Array Zigzag", - "question": "class Solution:\n def movesToMakeZigzag(self, nums: List[int]) -> int:\n \"\"\"\n Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.\n An array A is a zigzag array if either:\n Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...\n OR, every odd-indexed element is greater than adjacent elements, ie. A[0] < A[1] > A[2] < A[3] > A[4] < ...\n Return the minimum number of moves to transform the given array nums into a zigzag array.\n Example 1:\n Input: nums = [1,2,3]\n Output: 2\n Explanation: We can decrease 2 to 0 or 3 to 1.\n Example 2:\n Input: nums = [9,6,1,6,2]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1145, - "title": "Binary Tree Coloring Game", - "question": "class Solution:\n def btreeGameWinningMove(self, root: Optional[TreeNode], n: int, x: int) -> bool:\n \"\"\"\n 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.\n Initially, 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.\n Then, 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.)\n If (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.\n You 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:\n Input: root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3\n Output: true\n Explanation: The second player can choose the node with value 2.\n Example 2:\n Input: root = [1,2,3], n = 3, x = 1\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1146, - "title": "Snapshot Array", - "question": "class SnapshotArray:\n def __init__(self, length: int):\n def set(self, index: int, val: int) -> None:\n def snap(self) -> int:\n def get(self, index: int, snap_id: int) -> int:\n \"\"\"\n Implement a SnapshotArray that supports the following interface:\n SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.\n void set(index, val) sets the element at the given index to be equal to val.\n int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.\n int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id\n Example 1:\n Input: [\"SnapshotArray\",\"set\",\"snap\",\"set\",\"get\"]\n [[3],[0,5],[],[0,6],[0,0]]\n Output: [null,null,0,null,5]\n Explanation: \n SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3\n snapshotArr.set(0,5); // Set array[0] = 5\n snapshotArr.snap(); // Take a snapshot, return snap_id = 0\n snapshotArr.set(0,6);\n snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1143, - "title": "Longest Common Subsequence", - "question": "class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n \"\"\"\n Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.\n A 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 For example, \"ace\" is a subsequence of \"abcde\".\n A common subsequence of two strings is a subsequence that is common to both strings.\n Example 1:\n Input: text1 = \"abcde\", text2 = \"ace\" \n Output: 3 \n Explanation: The longest common subsequence is \"ace\" and its length is 3.\n Example 2:\n Input: text1 = \"abc\", text2 = \"abc\"\n Output: 3\n Explanation: The longest common subsequence is \"abc\" and its length is 3.\n Example 3:\n Input: text1 = \"abc\", text2 = \"def\"\n Output: 0\n Explanation: There is no such common subsequence, so the result is 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1147, - "title": "Longest Chunked Palindrome Decomposition", - "question": "class Solution:\n def longestDecomposition(self, text: str) -> int:\n \"\"\"\n You are given a string text. You should split it to k substrings (subtext1, subtext2, ..., subtextk) such that:\n subtexti is a non-empty string.\n The concatenation of all the substrings is equal to text (i.e., subtext1 + subtext2 + ... + subtextk == text).\n subtexti == subtextk - i + 1 for all valid values of i (i.e., 1 <= i <= k).\n Return the largest possible value of k.\n Example 1:\n Input: text = \"ghiabcdefhelloadamhelloabcdefghi\"\n Output: 7\n Explanation: We can split the string on \"(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)\".\n Example 2:\n Input: text = \"merchant\"\n Output: 1\n Explanation: We can split the string on \"(merchant)\".\n Example 3:\n Input: text = \"antaprezatepzapreanta\"\n Output: 11\n Explanation: We can split the string on \"(a)(nt)(a)(pre)(za)(tep)(za)(pre)(a)(nt)(a)\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1328, - "title": "Break a Palindrome", - "question": "class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n \"\"\"\n 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.\n Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.\n A 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:\n Input: palindrome = \"abccba\"\n Output: \"aaccba\"\n Explanation: There are many ways to make \"abccba\" not a palindrome, such as \"zbccba\", \"aaccba\", and \"abacba\".\n Of all the ways, \"aaccba\" is the lexicographically smallest.\n Example 2:\n Input: palindrome = \"a\"\n Output: \"\"\n Explanation: There is no way to replace a single character to make \"a\" not a palindrome, so return an empty string.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1329, - "title": "Sort the Matrix Diagonally", - "question": "class Solution:\n def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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].\n Given an m x n matrix mat of integers, sort each matrix diagonal in ascending order and return the resulting matrix.\n Example 1:\n Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]\n Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]\n Example 2:\n Input: 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]]\n Output: [[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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1302, - "title": "Deepest Leaves Sum", - "question": "class Solution:\n def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given the root of a binary tree, return the sum of values of its deepest leaves.\n Example 1:\n Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]\n Output: 15\n Example 2:\n Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]\n Output: 19\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1330, - "title": "Reverse Subarray To Maximize Array Value", - "question": "class Solution:\n def maxValueAfterReverse(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums. The value of this array is defined as the sum of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1.\n You are allowed to select any subarray of the given array and reverse it. You can perform this operation only once.\n Find maximum possible value of the final array.\n Example 1:\n Input: nums = [2,3,1,5,4]\n Output: 10\n Explanation: By reversing the subarray [3,1,5] the array becomes [2,5,1,3,4] whose value is 10.\n Example 2:\n Input: nums = [2,4,9,24,2,1,10]\n Output: 68\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1331, - "title": "Rank Transform of an Array", - "question": "class Solution:\n def arrayRankTransform(self, arr: List[int]) -> List[int]:\n \"\"\"\n Given an array of integers arr, replace each element with its rank.\n The rank represents how large the element is. The rank has the following rules:\n Rank is an integer starting from 1.\n The larger the element, the larger the rank. If two elements are equal, their rank must be the same.\n Rank should be as small as possible.\n Example 1:\n Input: arr = [40,10,20,30]\n Output: [4,1,2,3]\n Explanation: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.\n Example 2:\n Input: arr = [100,100,100]\n Output: [1,1,1]\n Explanation: Same elements share the same rank.\n Example 3:\n Input: arr = [37,12,28,9,100,56,80,5,12]\n Output: [5,3,4,2,8,6,7,1,3]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1632, - "title": "Rank Transform of a Matrix", - "question": "class Solution:\n def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].\n The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:\n The rank is an integer starting from 1.\n If two elements p and q are in the same row or column, then:\n If p < q then rank(p) < rank(q)\n If p == q then rank(p) == rank(q)\n If p > q then rank(p) > rank(q)\n The rank should be as small as possible.\n The test cases are generated so that answer is unique under the given rules.\n Example 1:\n Input: matrix = [[1,2],[3,4]]\n Output: [[1,2],[2,3]]\n Explanation:\n The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.\n The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.\n The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.\n The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.\n Example 2:\n Input: matrix = [[7,7],[7,7]]\n Output: [[1,1],[1,1]]\n Example 3:\n Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]\n Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1154, - "title": "Day of the Year", - "question": "class Solution:\n def dayOfYear(self, date: str) -> int:\n \"\"\"\n Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.\n Example 1:\n Input: date = \"2019-01-09\"\n Output: 9\n Explanation: Given date is the 9th day of the year in 2019.\n Example 2:\n Input: date = \"2019-02-10\"\n Output: 41\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1156, - "title": "Swap For Longest Repeated Character Substring", - "question": "class Solution:\n def maxRepOpt1(self, text: str) -> int:\n \"\"\"\n You are given a string text. You can swap two of the characters in the text.\n Return the length of the longest substring with repeated characters.\n Example 1:\n Input: text = \"ababa\"\n Output: 3\n Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated character substring is \"aaa\" with length 3.\n Example 2:\n Input: text = \"aaabaaa\"\n Output: 6\n Explanation: Swap 'b' with the last 'a' (or the first 'a'), and we get longest repeated character substring \"aaaaaa\" with length 6.\n Example 3:\n Input: text = \"aaaaa\"\n Output: 5\n Explanation: No need to swap, longest repeated character substring is \"aaaaa\" with length is 5.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1157, - "title": "Online Majority Element In Subarray", - "question": "class MajorityChecker:\n def __init__(self, arr: List[int]):\n def query(self, left: int, right: int, threshold: int) -> int:\n \"\"\"\n Design a data structure that efficiently finds the majority element of a given subarray.\n The majority element of a subarray is an element that occurs threshold times or more in the subarray.\n Implementing the MajorityChecker class:\n MajorityChecker(int[] arr) Initializes the instance of the class with the given array arr.\n int query(int left, int right, int threshold) returns the element in the subarray arr[left...right] that occurs at least threshold times, or -1 if no such element exists.\n Example 1:\n Input\n [\"MajorityChecker\", \"query\", \"query\", \"query\"]\n [[[1, 1, 2, 2, 1, 1]], [0, 5, 4], [0, 3, 3], [2, 3, 2]]\n Output\n [null, 1, -1, 2]\n Explanation\n MajorityChecker majorityChecker = new MajorityChecker([1, 1, 2, 2, 1, 1]);\n majorityChecker.query(0, 5, 4); // return 1\n majorityChecker.query(0, 3, 3); // return -1\n majorityChecker.query(2, 3, 2); // return 2\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1155, - "title": "Number of Dice Rolls With Target Sum", - "question": "class Solution:\n def numRollsToTarget(self, n: int, k: int, target: int) -> int:\n \"\"\"\n You have n dice, and each die has k faces numbered from 1 to k.\n Given 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:\n Input: n = 1, k = 6, target = 3\n Output: 1\n Explanation: You throw one die with 6 faces.\n There is only one way to get a sum of 3.\n Example 2:\n Input: n = 2, k = 6, target = 7\n Output: 6\n Explanation: You throw two dice, each with 6 faces.\n There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.\n Example 3:\n Input: n = 30, k = 30, target = 500\n Output: 222616187\n Explanation: The answer must be returned modulo 109 + 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1935, - "title": "Maximum Number of Words You Can Type", - "question": "class Solution:\n def canBeTypedWords(self, text: str, brokenLetters: str) -> int:\n \"\"\"\n There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.\n Given 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:\n Input: text = \"hello world\", brokenLetters = \"ad\"\n Output: 1\n Explanation: We cannot type \"world\" because the 'd' key is broken.\n Example 2:\n Input: text = \"leet code\", brokenLetters = \"lt\"\n Output: 1\n Explanation: We cannot type \"leet\" because the 'l' and 't' keys are broken.\n Example 3:\n Input: text = \"leet code\", brokenLetters = \"e\"\n Output: 0\n Explanation: We cannot type either word because the 'e' key is broken.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1171, - "title": "Remove Zero Sum Consecutive Nodes from Linked List", - "question": "class Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n Given the head of a linked list, we repeatedly delete consecutive sequences of nodes that sum to 0 until there are no such sequences.\r\n After doing so, return the head of the final linked list. You may return any such answer.\r\n (Note that in the examples below, all sequences are serializations of ListNode objects.)\n Example 1:\n Input: head = [1,2,-3,3,1]\n Output: [3,1]\n Note: The answer [1,2,1] would also be accepted.\n Example 2:\n Input: head = [1,2,3,-3,4]\n Output: [1,2,4]\n Example 3:\n Input: head = [1,2,3,-3,-2]\n Output: [1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1172, - "title": "Dinner Plate Stacks", - "question": "class DinnerPlates:\n def __init__(self, capacity: int):\n def push(self, val: int) -> None:\n def pop(self) -> int:\n def popAtStack(self, index: int) -> int:\n \"\"\"\n You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum capacity.\n Implement the DinnerPlates class:\n DinnerPlates(int capacity) Initializes the object with the maximum capacity of the stacks capacity.\n void push(int val) Pushes the given integer val into the leftmost stack with a size less than capacity.\n int pop() Returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns -1 if all the stacks are empty.\n int popAtStack(int index) Returns the value at the top of the stack with the given index index and removes it from that stack or returns -1 if the stack with that given index is empty.\n Example 1:\n Input\n [\"DinnerPlates\", \"push\", \"push\", \"push\", \"push\", \"push\", \"popAtStack\", \"push\", \"push\", \"popAtStack\", \"popAtStack\", \"pop\", \"pop\", \"pop\", \"pop\", \"pop\"]\n [[2], [1], [2], [3], [4], [5], [0], [20], [21], [0], [2], [], [], [], [], []]\n Output\n [null, null, null, null, null, null, 2, null, null, 20, 21, 5, 4, 3, 1, -1]\n Explanation: \n DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2\n D.push(1);\n D.push(2);\n D.push(3);\n D.push(4);\n D.push(5); // The stacks are now: 2 4\n 1 3 5\n \ufe48 \ufe48 \ufe48\n D.popAtStack(0); // Returns 2. The stacks are now: 4\n 1 3 5\n \ufe48 \ufe48 \ufe48\n D.push(20); // The stacks are now: 20 4\n 1 3 5\n \ufe48 \ufe48 \ufe48\n D.push(21); // The stacks are now: 20 4 21\n 1 3 5\n \ufe48 \ufe48 \ufe48\n D.popAtStack(0); // Returns 20. The stacks are now: 4 21\n 1 3 5\n \ufe48 \ufe48 \ufe48\n D.popAtStack(2); // Returns 21. The stacks are now: 4\n 1 3 5\n \ufe48 \ufe48 \ufe48 \n D.pop() // Returns 5. The stacks are now: 4\n 1 3 \n \ufe48 \ufe48 \n D.pop() // Returns 4. The stacks are now: 1 3 \n \ufe48 \ufe48 \n D.pop() // Returns 3. The stacks are now: 1 \n \ufe48 \n D.pop() // Returns 1. There are no stacks.\n D.pop() // Returns -1. There are still no stacks.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1169, - "title": "Invalid Transactions", - "question": "class Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n \"\"\"\n A transaction is possibly invalid if:\n the amount exceeds $1000, or;\n if it occurs within (and including) 60 minutes of another transaction with the same name in a different city.\n You 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.\n Return a list of transactions that are possibly invalid. You may return the answer in any order.\n Example 1:\n Input: transactions = [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\n Output: [\"alice,20,800,mtv\",\"alice,50,100,beijing\"]\n Explanation: The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.\n Example 2:\n Input: transactions = [\"alice,20,800,mtv\",\"alice,50,1200,mtv\"]\n Output: [\"alice,50,1200,mtv\"]\n Example 3:\n Input: transactions = [\"alice,20,800,mtv\",\"bob,50,1200,mtv\"]\n Output: [\"bob,50,1200,mtv\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1170, - "title": "Compare Strings by Frequency of the Smallest Character", - "question": "class Solution:\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n \"\"\"\n 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.\n You 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.\n Return an integer array answer, where each answer[i] is the answer to the ith query.\n Example 1:\n Input: queries = [\"cbd\"], words = [\"zaaaz\"]\n Output: [1]\n Explanation: On the first query we have f(\"cbd\") = 1, f(\"zaaaz\") = 3 so f(\"cbd\") < f(\"zaaaz\").\n Example 2:\n Input: queries = [\"bbb\",\"cc\"], words = [\"a\",\"aa\",\"aaa\",\"aaaa\"]\n Output: [1,2]\n Explanation: On the first query only f(\"bbb\") < f(\"aaaa\"). On the second query both f(\"aaa\") and f(\"aaaa\") are both > f(\"cc\").\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1360, - "title": "Number of Days Between Two Dates", - "question": "class Solution:\n def daysBetweenDates(self, date1: str, date2: str) -> int:\n \"\"\"\n Write a program to count the number of days between two dates.\n The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.\n Example 1:\n Input: date1 = \"2019-06-29\", date2 = \"2019-06-30\"\n Output: 1\n Example 2:\n Input: date1 = \"2020-01-15\", date2 = \"2019-12-31\"\n Output: 15\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1361, - "title": "Validate Binary Tree Nodes", - "question": "class Solution:\n def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:\n \"\"\"\n 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.\n If node i has no left child then leftChild[i] will equal -1, similarly for the right child.\n Note that the nodes have no values and that we only use the node numbers in this problem.\n Example 1:\n Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,-1,-1,-1]\n Output: true\n Example 2:\n Input: n = 4, leftChild = [1,-1,3,-1], rightChild = [2,3,-1,-1]\n Output: false\n Example 3:\n Input: n = 2, leftChild = [1,0], rightChild = [-1,-1]\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1362, - "title": "Closest Divisors", - "question": "class Solution:\n def closestDivisors(self, num: int) -> List[int]:\n \"\"\"\n Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.\n Return the two integers in any order.\n Example 1:\n Input: num = 8\n Output: [3,3]\n Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.\n Example 2:\n Input: num = 123\n Output: [5,25]\n Example 3:\n Input: num = 999\n Output: [40,25]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1363, - "title": "Largest Multiple of Three", - "question": "class Solution:\n def largestMultipleOfThree(self, digits: List[int]) -> str:\n \"\"\"\n 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.\n Since 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:\n Input: digits = [8,1,9]\n Output: \"981\"\n Example 2:\n Input: digits = [8,6,7,1,0]\n Output: \"8760\"\n Example 3:\n Input: digits = [1]\n Output: \"\"\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1175, - "title": "Prime Arrangements", - "question": "class Solution:\n def numPrimeArrangements(self, n: int) -> int:\n \"\"\"\n 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.)\n Since the answer may be large, return the answer modulo 10^9 + 7.\n Example 1:\n Input: n = 5\n Output: 12\n Explanation: For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.\n Example 2:\n Input: n = 100\n Output: 682289015\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1177, - "title": "Can Make Palindrome from Substring", - "question": "class Solution:\n def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:\n \"\"\"\n 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.\n If 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.\n Return a boolean array answer where answer[i] is the result of the ith query queries[i].\n Note 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 :\n Input: s = \"abcda\", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]\n Output: [true,false,false,true,true]\n Explanation:\n queries[0]: substring = \"d\", is palidrome.\n queries[1]: substring = \"bc\", is not palidrome.\n queries[2]: substring = \"abcd\", is not palidrome after replacing only 1 character.\n queries[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\".\n queries[4]: substring = \"abcda\", could be changed to \"abcba\" which is palidrome.\n Example 2:\n Input: s = \"lyb\", queries = [[0,1,0],[2,2,1]]\n Output: [false,true]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1178, - "title": "Number of Valid Words for Each Puzzle", - "question": "class Solution:\n def findNumOfValidWords(self, words: List[str], puzzles: List[str]) -> List[int]:\n \"\"\"\n With respect to a given puzzle string, a word is valid if both the following conditions are satisfied:\n word contains the first letter of puzzle.\n For each letter in word, that letter is in puzzle.\n For example, if the puzzle is \"abcdefg\", then valid words are \"faced\", \"cabbage\", and \"baggage\", while\n invalid words are \"beefed\" (does not include 'a') and \"based\" (includes 's' which is not in the puzzle).\n Return 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:\n Input: words = [\"aaaa\",\"asas\",\"able\",\"ability\",\"actt\",\"actor\",\"access\"], puzzles = [\"aboveyz\",\"abrodyz\",\"abslute\",\"absoryz\",\"actresz\",\"gaswxyz\"]\n Output: [1,1,3,2,4,0]\n Explanation: \n 1 valid word for \"aboveyz\" : \"aaaa\" \n 1 valid word for \"abrodyz\" : \"aaaa\"\n 3 valid words for \"abslute\" : \"aaaa\", \"asas\", \"able\"\n 2 valid words for \"absoryz\" : \"aaaa\", \"asas\"\n 4 valid words for \"actresz\" : \"aaaa\", \"asas\", \"actt\", \"access\"\n There are no valid words for \"gaswxyz\" cause none of the words in the list contains letter 'g'.\n Example 2:\n Input: words = [\"apple\",\"pleas\",\"please\"], puzzles = [\"aelwxyz\",\"aelpxyz\",\"aelpsxy\",\"saelpxy\",\"xaelpsy\"]\n Output: [0,1,3,2,0]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1507, - "title": "Reformat Date", - "question": "class Solution:\n def reformatDate(self, date: str) -> str:\n \"\"\"\n Given a date string in the form Day Month Year, where:\n Day is in the set {\"1st\", \"2nd\", \"3rd\", \"4th\", ..., \"30th\", \"31st\"}.\n Month is in the set {\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"}.\n Year is in the range [1900, 2100].\n Convert the date string to the format YYYY-MM-DD, where:\n YYYY denotes the 4 digit year.\n MM denotes the 2 digit month.\n DD denotes the 2 digit day.\n Example 1:\n Input: date = \"20th Oct 2052\"\n Output: \"2052-10-20\"\n Example 2:\n Input: date = \"6th Jun 1933\"\n Output: \"1933-06-06\"\n Example 3:\n Input: date = \"26th May 1960\"\n Output: \"1960-05-26\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1390, - "title": "Four Divisors", - "question": "class Solution:\n def sumFourDivisors(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [21,4,7]\n Output: 32\n Explanation: \n 21 has 4 divisors: 1, 3, 7, 21\n 4 has 3 divisors: 1, 2, 4\n 7 has 2 divisors: 1, 7\n The answer is the sum of divisors of 21 only.\n Example 2:\n Input: nums = [21,21]\n Output: 64\n Example 3:\n Input: nums = [1,2,3,4,5]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1382, - "title": "Balance a Binary Search Tree", - "question": "class Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 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.\n A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1.\n Example 1:\n Input: root = [1,null,2,null,3,null,4,null,null]\n Output: [2,1,3,null,null,null,4]\n Explanation: This is not the only correct answer, [3,1,4,null,2] is also correct.\n Example 2:\n Input: root = [2,1,3]\n Output: [2,1,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1425, - "title": "Constrained Subsequence Sum", - "question": "class Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of that array such that for every two consecutive integers in the subsequence, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied.\n A subsequence of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.\n Example 1:\n Input: nums = [10,2,-10,5,20], k = 2\n Output: 37\n Explanation: The subsequence is [10, 2, 5, 20].\n Example 2:\n Input: nums = [-1,-2,-3], k = 1\n Output: -1\n Explanation: The subsequence must be non-empty, so we choose the largest number.\n Example 3:\n Input: nums = [10,-2,-10,-5,20], k = 2\n Output: 23\n Explanation: The subsequence is [10, -2, -5, 20].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1184, - "title": "Distance Between Bus Stops", - "question": "class Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n \"\"\"\n 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.\r\n The bus goes along both directions i.e. clockwise and counterclockwise.\r\n Return the shortest distance between the given start and destination stops.\r\n Example 1:\r\n Input: distance = [1,2,3,4], start = 0, destination = 1\r\n Output: 1\r\n Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.\r\n Example 2:\r\n Input: distance = [1,2,3,4], start = 0, destination = 2\r\n Output: 3\r\n Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.\r\n Example 3:\r\n Input: distance = [1,2,3,4], start = 0, destination = 3\r\n Output: 4\r\n Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1186, - "title": "Maximum Subarray Sum with One Deletion", - "question": "class Solution:\n def maximumSum(self, arr: List[int]) -> int:\n \"\"\"\n 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.\n Note that the subarray needs to be non-empty after deleting one element.\n Example 1:\n Input: arr = [1,-2,0,3]\n Output: 4\n Explanation: Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.\n Example 2:\n Input: arr = [1,-2,-2,3]\n Output: 3\n Explanation: We just choose [3] and it's the maximum sum.\n Example 3:\n Input: arr = [-1,-1,-1,-1]\n Output: -1\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1185, - "title": "Day of the Week", - "question": "class Solution:\n def dayOfTheWeek(self, day: int, month: int, year: int) -> str:\n \"\"\"\n Given a date, return the corresponding day of the week for that date.\n The input is given as three integers representing the day, month and year respectively.\n Return the answer as one of the following values {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"}.\n Example 1:\n Input: day = 31, month = 8, year = 2019\n Output: \"Saturday\"\n Example 2:\n Input: day = 18, month = 7, year = 1999\n Output: \"Sunday\"\n Example 3:\n Input: day = 15, month = 8, year = 1993\n Output: \"Sunday\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1187, - "title": "Make Array Strictly Increasing", - "question": "class Solution:\n def makeArrayIncreasing(self, arr1: List[int], arr2: List[int]) -> int:\n \"\"\"\n Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing.\r\n In one operation, you can choose two indices 0 <= i < arr1.length and 0 <= j < arr2.length and do the assignment arr1[i] = arr2[j].\r\n If there is no way to make arr1 strictly increasing, return -1.\r\n Example 1:\r\n Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]\r\n Output: 1\r\n Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7].\r\n Example 2:\r\n Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1]\r\n Output: 2\r\n Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7].\r\n Example 3:\r\n Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]\r\n Output: -1\r\n Explanation: You can't make arr1 strictly increasing.\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1550, - "title": "Three Consecutive Odds", - "question": "class Solution:\n def threeConsecutiveOdds(self, arr: List[int]) -> bool:\n \"\"\"\n Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.\n Example 1:\n Input: arr = [2,6,4,1]\n Output: false\n Explanation: There are no three consecutive odds.\n Example 2:\n Input: arr = [1,2,34,3,4,5,7,23,12]\n Output: true\n Explanation: [5,7,23] are three consecutive odds.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2080, - "title": "Range Frequency Queries", - "question": "class RangeFreqQuery:\n def __init__(self, arr: List[int]):\n def query(self, left: int, right: int, value: int) -> int:\n \"\"\"\n Design a data structure to find the frequency of a given value in a given subarray.\n The frequency of a value in a subarray is the number of occurrences of that value in the subarray.\n Implement the RangeFreqQuery class:\n RangeFreqQuery(int[] arr) Constructs an instance of the class with the given 0-indexed integer array arr.\n int query(int left, int right, int value) Returns the frequency of value in the subarray arr[left...right].\n A 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:\n Input\n [\"RangeFreqQuery\", \"query\", \"query\"]\n [[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]\n Output\n [null, 1, 2]\n Explanation\n RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]);\n rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4]\n rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1954, - "title": "Minimum Garden Perimeter to Collect Enough Apples", - "question": "class Solution:\n def minimumPerimeter(self, neededApples: int) -> int:\n \"\"\"\n In a garden represented as an infinite 2D grid, there is an apple tree planted at every integer coordinate. The apple tree planted at an integer coordinate (i, j) has |i| + |j| apples growing on it.\n You will buy an axis-aligned square plot of land that is centered at (0, 0).\n Given an integer neededApples, return the minimum perimeter of a plot such that at least neededApples apples are inside or on the perimeter of that plot.\n The value of |x| is defined as:\n x if x >= 0\n -x if x < 0\n Example 1:\n Input: neededApples = 1\n Output: 8\n Explanation: A square plot of side length 1 does not contain any apples.\n However, a square plot of side length 2 has 12 apples inside (as depicted in the image above).\n The perimeter is 2 * 4 = 8.\n Example 2:\n Input: neededApples = 13\n Output: 16\n Example 3:\n Input: neededApples = 1000000000\n Output: 5040\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1483, - "title": "Kth Ancestor of a Tree Node", - "question": "class TreeAncestor:\n def __init__(self, n: int, parent: List[int]):\n def getKthAncestor(self, node: int, k: int) -> int:\n \"\"\"\n You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of ith node. The root of the tree is node 0. Find the kth ancestor of a given node.\n The kth ancestor of a tree node is the kth node in the path from that node to the root node.\n Implement the TreeAncestor class:\n TreeAncestor(int n, int[] parent) Initializes the object with the number of nodes in the tree and the parent array.\n int getKthAncestor(int node, int k) return the kth ancestor of the given node node. If there is no such ancestor, return -1.\n Example 1:\n Input\n [\"TreeAncestor\", \"getKthAncestor\", \"getKthAncestor\", \"getKthAncestor\"]\n [[7, [-1, 0, 0, 1, 1, 2, 2]], [3, 1], [5, 2], [6, 3]]\n Output\n [null, 1, 0, -1]\n Explanation\n TreeAncestor treeAncestor = new TreeAncestor(7, [-1, 0, 0, 1, 1, 2, 2]);\n treeAncestor.getKthAncestor(3, 1); // returns 1 which is the parent of 3\n treeAncestor.getKthAncestor(5, 2); // returns 0 which is the grandparent of 5\n treeAncestor.getKthAncestor(6, 3); // returns -1 because there is no such ancestor\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1189, - "title": "Maximum Number of Balloons", - "question": "class Solution:\n def maxNumberOfBalloons(self, text: str) -> int:\n \"\"\"\n Given a string text, you want to use the characters of text to form as many instances of the word \"balloon\" as possible.\n You can use each character in text at most once. Return the maximum number of instances that can be formed.\n Example 1:\n Input: text = \"nlaebolko\"\n Output: 1\n Example 2:\n Input: text = \"loonbalxballpoon\"\n Output: 2\n Example 3:\n Input: text = \"leetcode\"\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1190, - "title": "Reverse Substrings Between Each Pair of Parentheses", - "question": "class Solution:\n def reverseParentheses(self, s: str) -> str:\n \"\"\"\n You are given a string s that consists of lower case English letters and brackets.\n Reverse the strings in each pair of matching parentheses, starting from the innermost one.\n Your result should not contain any brackets.\n Example 1:\n Input: s = \"(abcd)\"\n Output: \"dcba\"\n Example 2:\n Input: s = \"(u(love)i)\"\n Output: \"iloveu\"\n Explanation: The substring \"love\" is reversed first, then the whole string is reversed.\n Example 3:\n Input: s = \"(ed(et(oc))el)\"\n Output: \"leetcode\"\n Explanation: First, we reverse the substring \"oc\", then \"etco\", and finally, the whole string.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1191, - "title": "K-Concatenation Maximum Sum", - "question": "class Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n \"\"\"\n Given an integer array arr and an integer k, modify the array by repeating it k times.\n For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].\n Return 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.\n As the answer can be very large, return the answer modulo 109 + 7.\n Example 1:\n Input: arr = [1,2], k = 3\n Output: 9\n Example 2:\n Input: arr = [1,-2,1], k = 5\n Output: 2\n Example 3:\n Input: arr = [-1,-2], k = 7\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1192, - "title": "Critical Connections in a Network", - "question": "class Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n A critical connection is a connection that, if removed, will make some servers unable to reach some other server.\n Return all critical connections in the network in any order.\n Example 1:\n Input: n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]\n Output: [[1,3]]\n Explanation: [[3,1]] is also accepted.\n Example 2:\n Input: n = 2, connections = [[0,1]]\n Output: [[0,1]]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1957, - "title": "Delete Characters to Make Fancy String", - "question": "class Solution:\n def makeFancyString(self, s: str) -> str:\n \"\"\"\n A fancy string is a string where no three consecutive characters are equal.\n Given a string s, delete the minimum possible number of characters from s to make it fancy.\n Return the final string after the deletion. It can be shown that the answer will always be unique.\n Example 1:\n Input: s = \"leeetcode\"\n Output: \"leetcode\"\n Explanation:\n Remove an 'e' from the first group of 'e's to create \"leetcode\".\n No three consecutive characters are equal, so return \"leetcode\".\n Example 2:\n Input: s = \"aaabaaaa\"\n Output: \"aabaa\"\n Explanation:\n Remove an 'a' from the first group of 'a's to create \"aabaaaa\".\n Remove two 'a's from the second group of 'a's to create \"aabaa\".\n No three consecutive characters are equal, so return \"aabaa\".\n Example 3:\n Input: s = \"aab\"\n Output: \"aab\"\n Explanation: No three consecutive characters are equal, so return \"aab\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2139, - "title": "Minimum Moves to Reach Target Score", - "question": "class Solution:\n def minMoves(self, target: int, maxDoubles: int) -> int:\n \"\"\"\n You are playing a game with integers. You start with the integer 1 and you want to reach the integer target.\n In one move, you can either:\n Increment the current integer by one (i.e., x = x + 1).\n Double the current integer (i.e., x = 2 * x).\n You can use the increment operation any number of times, however, you can only use the double operation at most maxDoubles times.\n Given the two integers target and maxDoubles, return the minimum number of moves needed to reach target starting with 1.\n Example 1:\n Input: target = 5, maxDoubles = 0\n Output: 4\n Explanation: Keep incrementing by 1 until you reach target.\n Example 2:\n Input: target = 19, maxDoubles = 2\n Output: 7\n Explanation: Initially, x = 1\n Increment 3 times so x = 4\n Double once so x = 8\n Increment once so x = 9\n Double again so x = 18\n Increment once so x = 19\n Example 3:\n Input: target = 10, maxDoubles = 4\n Output: 4\n Explanation: Initially, x = 1\n Increment once so x = 2\n Double once so x = 4\n Increment once so x = 5\n Double again so x = 10\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1405, - "title": "Longest Happy String", - "question": "class Solution:\n def longestDiverseString(self, a: int, b: int, c: int) -> str:\n \"\"\"\n A string s is called happy if it satisfies the following conditions:\n s only contains the letters 'a', 'b', and 'c'.\n s does not contain any of \"aaa\", \"bbb\", or \"ccc\" as a substring.\n s contains at most a occurrences of the letter 'a'.\n s contains at most b occurrences of the letter 'b'.\n s contains at most c occurrences of the letter 'c'.\n Given 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 \"\".\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: a = 1, b = 1, c = 7\n Output: \"ccaccbcc\"\n Explanation: \"ccbccacc\" would also be a correct answer.\n Example 2:\n Input: a = 7, b = 1, c = 0\n Output: \"aabaa\"\n Explanation: It is the only correct answer in this case.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1944, - "title": "Number of Visible People in a Queue", - "question": "class Solution:\n def canSeePersonsCount(self, heights: List[int]) -> List[int]:\n \"\"\"\n 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.\n A 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]).\n Return 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:\n Input: heights = [10,6,8,5,11,9]\n Output: [3,1,2,1,1,0]\n Explanation:\n Person 0 can see person 1, 2, and 4.\n Person 1 can see person 2.\n Person 2 can see person 3 and 4.\n Person 3 can see person 4.\n Person 4 can see person 5.\n Person 5 can see no one since nobody is to the right of them.\n Example 2:\n Input: heights = [5,1,2,3,10]\n Output: [4,1,1,1,0]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1200, - "title": "Minimum Absolute Difference", - "question": "class Solution:\n def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:\n \"\"\"\n Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.\n Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows\n a, b are from arr\n a < b\n b - a equals to the minimum absolute difference of any two elements in arr\n Example 1:\n Input: arr = [4,2,1,3]\n Output: [[1,2],[2,3],[3,4]]\n Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.\n Example 2:\n Input: arr = [1,3,6,10,15]\n Output: [[1,3]]\n Example 3:\n Input: arr = [3,8,-10,23,19,-4,-14,27]\n Output: [[-14,-10],[19,23],[23,27]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1201, - "title": "Ugly Number III", - "question": "class Solution:\n def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:\n \"\"\"\n An ugly number is a positive integer that is divisible by a, b, or c.\n Given four integers n, a, b, and c, return the nth ugly number.\n Example 1:\n Input: n = 3, a = 2, b = 3, c = 5\n Output: 4\n Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3rd is 4.\n Example 2:\n Input: n = 4, a = 2, b = 3, c = 4\n Output: 6\n Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4th is 6.\n Example 3:\n Input: n = 5, a = 2, b = 11, c = 13\n Output: 10\n Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5th is 10.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1202, - "title": "Smallest String With Swaps", - "question": "class Solution:\n def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:\n \"\"\"\n 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.\n You can swap the characters at any pair of indices in the given pairs any number of times.\n Return the lexicographically smallest string that s can be changed to after using the swaps.\n Example 1:\n Input: s = \"dcab\", pairs = [[0,3],[1,2]]\n Output: \"bacd\"\n Explaination: \n Swap s[0] and s[3], s = \"bcad\"\n Swap s[1] and s[2], s = \"bacd\"\n Example 2:\n Input: s = \"dcab\", pairs = [[0,3],[1,2],[0,2]]\n Output: \"abcd\"\n Explaination: \n Swap s[0] and s[3], s = \"bcad\"\n Swap s[0] and s[2], s = \"acbd\"\n Swap s[1] and s[2], s = \"abcd\"\n Example 3:\n Input: s = \"cba\", pairs = [[0,1],[1,2]]\n Output: \"abc\"\n Explaination: \n Swap s[0] and s[1], s = \"bca\"\n Swap s[1] and s[2], s = \"bac\"\n Swap s[0] and s[1], s = \"abc\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1203, - "title": "Sort Items by Groups Respecting Dependencies", - "question": "class Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n \"\"\"\n There are n items each belonging to zero or one of m groups where group[i] is the group that the i-th item belongs to and it's equal to -1 if the i-th item belongs to no group. The items and the groups are zero indexed. A group can have no item belonging to it.\n Return a sorted list of the items such that:\n The items that belong to the same group are next to each other in the sorted list.\n There are some relations between these items where beforeItems[i] is a list containing all the items that should come before the i-th item in the sorted array (to the left of the i-th item).\n Return any solution if there is more than one solution and return an empty list if there is no solution.\n Example 1:\n Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]]\n Output: [6,3,4,1,5,2,0,7]\n Example 2:\n Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3],[],[4],[]]\n Output: []\n Explanation: This is the same as example 1 except that 4 needs to be before 6 in the sorted list.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2079, - "title": "Watering Plants", - "question": "class Solution:\n def wateringPlants(self, plants: List[int], capacity: int) -> int:\n \"\"\"\n 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.\n Each plant needs a specific amount of water. You will water the plants in the following way:\n Water the plants in order from left to right.\n After 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.\n You cannot refill the watering can early.\n You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis.\n Given 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:\n Input: plants = [2,2,3,3], capacity = 5\n Output: 14\n Explanation: 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.\n Steps needed = 1 + 1 + 2 + 3 + 3 + 4 = 14.\n Example 2:\n Input: plants = [1,1,1,4,2,3], capacity = 4\n Output: 30\n Explanation: 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).\n Steps needed = 3 + 3 + 4 + 4 + 5 + 5 + 6 = 30.\n Example 3:\n Input: plants = [7,7,7,7,7,7,7], capacity = 8\n Output: 49\n Explanation: You have to refill before watering each plant.\n Steps needed = 1 + 1 + 2 + 2 + 3 + 3 + 4 + 4 + 5 + 5 + 6 + 6 + 7 = 49.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1895, - "title": "Largest Magic Square", - "question": "class Solution:\n def largestMagicSquare(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Given 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:\n Input: grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]\n Output: 3\n Explanation: The largest magic square has a size of 3.\n Every row sum, column sum, and diagonal sum of this magic square is equal to 12.\n - Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12\n - Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12\n - Diagonal sums: 5+4+3 = 6+4+2 = 12\n Example 2:\n Input: grid = [[5,1,3,1],[9,3,3,1],[1,3,3,8]]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2201, - "title": "Count Artifacts That Can Be Extracted", - "question": "class Solution:\n def digArtifacts(self, n: int, artifacts: List[List[int]], dig: List[List[int]]) -> int:\n \"\"\"\n 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.\n You 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.\n Given 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.\n The test cases are generated such that:\n No two artifacts overlap.\n Each artifact only covers at most 4 cells.\n The entries of dig are unique.\n Example 1:\n Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1]]\n Output: 1\n Explanation: \n The different colors represent different artifacts. Excavated cells are labeled with a 'D' in the grid.\n There is 1 artifact that can be extracted, namely the red artifact.\n The blue artifact has one part in cell (1,1) which remains uncovered, so we cannot extract it.\n Thus, we return 1.\n Example 2:\n Input: n = 2, artifacts = [[0,0,0,0],[0,1,1,1]], dig = [[0,0],[0,1],[1,1]]\n Output: 2\n Explanation: Both the red and blue artifacts have all parts uncovered (labeled with a 'D') and can be extracted, so we return 2. \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1916, - "title": "Count Ways to Build Rooms in an Ant Colony", - "question": "class Solution:\r\n def waysToBuildRooms(self, prevRoom: List[int]) -> int:\n \"\"\"\n 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.\r\n You 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.\r\n Return the number of different orders you can build all the rooms in. Since the answer may be large, return it modulo 109 + 7.\r\n Example 1:\r\n Input: prevRoom = [-1,0,1]\r\n Output: 1\r\n Explanation: There is only one way to build the additional rooms: 0 \u2192 1 \u2192 2\r\n Example 2:\r\n Input: prevRoom = [-1,0,0,1,2]\r\n Output: 6\r\n Explanation:\r\n The 6 ways are:\r\n 0 \u2192 1 \u2192 3 \u2192 2 \u2192 4\r\n 0 \u2192 2 \u2192 4 \u2192 1 \u2192 3\r\n 0 \u2192 1 \u2192 2 \u2192 3 \u2192 4\r\n 0 \u2192 1 \u2192 2 \u2192 4 \u2192 3\r\n 0 \u2192 2 \u2192 1 \u2192 3 \u2192 4\r\n 0 \u2192 2 \u2192 1 \u2192 4 \u2192 3\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1195, - "title": "Fizz Buzz Multithreaded", - "question": "class FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n def fizz(self, printFizz: 'Callable[[], None]') -> None:\n def buzz(self, printBuzz: 'Callable[[], None]') -> None:\n def fizzbuzz(self, printFizzBuzz: 'Callable[[], None]') -> None:\n def number(self, printNumber: 'Callable[[int], None]') -> None:\n \"\"\"\n You have the four functions:\n printFizz that prints the word \"fizz\" to the console,\n printBuzz that prints the word \"buzz\" to the console,\n printFizzBuzz that prints the word \"fizzbuzz\" to the console, and\n printNumber that prints a given integer to the console.\n You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads:\n Thread A: calls fizz() that should output the word \"fizz\".\n Thread B: calls buzz() that should output the word \"buzz\".\n Thread C: calls fizzbuzz() that should output the word \"fizzbuzz\".\n Thread D: calls number() that should only output the integers.\n Modify the given class to output the series [1, 2, \"fizz\", 4, \"buzz\", ...] where the ith token (1-indexed) of the series is:\n \"fizzbuzz\" if i is divisible by 3 and 5,\n \"fizz\" if i is divisible by 3 and not 5,\n \"buzz\" if i is divisible by 5 and not 3, or\n i if i is not divisible by 3 or 5.\n Implement the FizzBuzz class:\n FizzBuzz(int n) Initializes the object with the number n that represents the length of the sequence that should be printed.\n void fizz(printFizz) Calls printFizz to output \"fizz\".\n void buzz(printBuzz) Calls printBuzz to output \"buzz\".\n void fizzbuzz(printFizzBuzz) Calls printFizzBuzz to output \"fizzbuzz\".\n void number(printNumber) Calls printnumber to output the numbers.\n Example 1:\n Input: n = 15\n Output: [1,2,\"fizz\",4,\"buzz\",\"fizz\",7,8,\"fizz\",\"buzz\",11,\"fizz\",13,14,\"fizzbuzz\"]\n Example 2:\n Input: n = 5\n Output: [1,2,\"fizz\",4,\"buzz\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1207, - "title": "Unique Number of Occurrences", - "question": "class Solution:\n def uniqueOccurrences(self, arr: List[int]) -> bool:\n \"\"\"\n 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:\n Input: arr = [1,2,2,1,1,3]\n Output: true\n Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.\n Example 2:\n Input: arr = [1,2]\n Output: false\n Example 3:\n Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1209, - "title": "Remove All Adjacent Duplicates in String II", - "question": "class Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n \"\"\"\n 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.\n We repeatedly make k duplicate removals on s until we no longer can.\n Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.\n Example 1:\n Input: s = \"abcd\", k = 2\n Output: \"abcd\"\n Explanation: There's nothing to delete.\n Example 2:\n Input: s = \"deeedbbcccbdaa\", k = 3\n Output: \"aa\"\n Explanation: \n First delete \"eee\" and \"ccc\", get \"ddbbbdaa\"\n Then delete \"bbb\", get \"dddaa\"\n Finally delete \"ddd\", get \"aa\"\n Example 3:\n Input: s = \"pbbcggttciiippooaais\", k = 2\n Output: \"ps\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1208, - "title": "Get Equal Substrings Within Budget", - "question": "class Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n \"\"\"\n You are given two strings s and t of the same length and an integer maxCost.\n You 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).\n Return 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:\n Input: s = \"abcd\", t = \"bcdf\", maxCost = 3\n Output: 3\n Explanation: \"abc\" of s can change to \"bcd\".\n That costs 3, so the maximum length is 3.\n Example 2:\n Input: s = \"abcd\", t = \"cdef\", maxCost = 3\n Output: 1\n Explanation: Each character in s costs 2 to change to character in t, so the maximum length is 1.\n Example 3:\n Input: s = \"abcd\", t = \"acde\", maxCost = 0\n Output: 1\n Explanation: You cannot make any change, so the maximum length is 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1210, - "title": "Minimum Moves to Reach Target with Rotations", - "question": "class Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n \"\"\"\n In an n*n grid, there is a snake that spans 2 cells and starts moving from the top left corner at (0, 0) and (0, 1). The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at (n-1, n-2) and (n-1, n-1).\n In one move the snake can:\n Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.\n Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from (r, c) and (r, c+1) to (r, c) and (r+1, c).\n Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from (r, c) and (r+1, c) to (r, c) and (r, c+1).\n Return the minimum number of moves to reach the target.\n If there is no way to reach the target, return -1.\n Example 1:\n Input: grid = [[0,0,0,0,0,1],\n [1,1,0,0,1,0],\n [0,0,0,0,1,1],\n [0,0,1,0,1,0],\n [0,1,1,0,0,0],\n [0,1,1,0,0,0]]\n Output: 11\n Explanation:\n One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].\n Example 2:\n Input: grid = [[0,0,1,1,1,1],\n [0,0,0,0,1,1],\n [1,1,0,0,0,1],\n [1,1,1,0,0,1],\n [1,1,1,0,0,1],\n [1,1,1,0,0,0]]\n Output: 9\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1706, - "title": "Where Will the Ball Fall", - "question": "class Solution:\n def findBall(self, grid: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n Each 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.\n A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as 1.\n A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as -1.\n We 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.\n Return 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:\n Input: 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]]\n Output: [1,-1,-1,-1,-1]\n Explanation: This example is shown in the photo.\n Ball b0 is dropped at column 0 and falls out of the box at column 1.\n Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.\n Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.\n Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.\n Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.\n Example 2:\n Input: grid = [[-1]]\n Output: [-1]\n Explanation: The ball gets stuck against the left wall.\n Example 3:\n Input: 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]]\n Output: [0,1,2,3,4,-1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1514, - "title": "Path with Maximum Probability", - "question": "class Solution:\n def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:\n \"\"\"\n 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].\n Given 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.\n If 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:\n Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2\n Output: 0.25000\n Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.\n Example 2:\n Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2\n Output: 0.30000\n Example 3:\n Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2\n Output: 0.00000\n Explanation: There is no path between 0 and 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1862, - "title": "Sum of Floored Pairs", - "question": "class Solution:\n def sumOfFlooredPairs(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n The floor() function returns the integer part of the division.\n Example 1:\n Input: nums = [2,5,9]\n Output: 10\n Explanation:\n floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0\n floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1\n floor(5 / 2) = 2\n floor(9 / 2) = 4\n floor(9 / 5) = 1\n We calculate the floor of the division for every pair of indices in the array then sum them up.\n Example 2:\n Input: nums = [7,7,7,7,7,7,7]\n Output: 49\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1217, - "title": "Minimum Cost to Move Chips to The Same Position", - "question": "class Solution:\n def minCostToMoveChips(self, position: List[int]) -> int:\n \"\"\"\n We have n chips, where the position of the ith chip is position[i].\n We 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:\n position[i] + 2 or position[i] - 2 with cost = 0.\n position[i] + 1 or position[i] - 1 with cost = 1.\n Return the minimum cost needed to move all the chips to the same position.\n Example 1:\n Input: position = [1,2,3]\n Output: 1\n Explanation: First step: Move the chip at position 3 to position 1 with cost = 0.\n Second step: Move the chip at position 2 to position 1 with cost = 1.\n Total cost is 1.\n Example 2:\n Input: position = [2,2,2,3,3]\n Output: 2\n Explanation: We can move the two chips at position 3 to position 2. Each move has cost = 1. The total cost = 2.\n Example 3:\n Input: position = [1,1000000000]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1218, - "title": "Longest Arithmetic Subsequence of Given Difference", - "question": "class Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n \"\"\"\n 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.\n A 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:\n Input: arr = [1,2,3,4], difference = 1\n Output: 4\n Explanation: The longest arithmetic subsequence is [1,2,3,4].\n Example 2:\n Input: arr = [1,3,5,7], difference = 1\n Output: 1\n Explanation: The longest arithmetic subsequence is any single element.\n Example 3:\n Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2\n Output: 4\n Explanation: The longest arithmetic subsequence is [7,5,3,1].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1219, - "title": "Path with Maximum Gold", - "question": "class Solution:\n def getMaximumGold(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the maximum amount of gold you can collect under the conditions:\n Every time you are located in a cell you will collect all the gold in that cell.\n From your position, you can walk one step to the left, right, up, or down.\n You can't visit the same cell more than once.\n Never visit a cell with 0 gold.\n You can start and stop collecting gold from any position in the grid that has some gold.\n Example 1:\n Input: grid = [[0,6,0],[5,8,7],[0,9,0]]\n Output: 24\n Explanation:\n [[0,6,0],\n [5,8,7],\n [0,9,0]]\n Path to get the maximum gold, 9 -> 8 -> 7.\n Example 2:\n Input: grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]\n Output: 28\n Explanation:\n [[1,0,7],\n [2,0,6],\n [3,4,5],\n [0,3,0],\n [9,0,20]]\n Path to get the maximum gold, 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1220, - "title": "Count Vowels Permutation", - "question": "class Solution:\n def countVowelPermutation(self, n: int) -> int:\n \"\"\"\n Given an integer n, your task is to count how many strings of length n can be formed under the following rules:\n Each character is a lower case vowel ('a', 'e', 'i', 'o', 'u')\n Each vowel 'a' may only be followed by an 'e'.\n Each vowel 'e' may only be followed by an 'a' or an 'i'.\n Each vowel 'i' may not be followed by another 'i'.\n Each vowel 'o' may only be followed by an 'i' or a 'u'.\n Each vowel 'u' may only be followed by an 'a'.\n Since the answer may be too large, return it modulo 10^9 + 7.\n Example 1:\n Input: n = 1\n Output: 5\n Explanation: All possible strings are: \"a\", \"e\", \"i\" , \"o\" and \"u\".\n Example 2:\n Input: n = 2\n Output: 10\n Explanation: All possible strings are: \"ae\", \"ea\", \"ei\", \"ia\", \"ie\", \"io\", \"iu\", \"oi\", \"ou\" and \"ua\".\n Example 3: \n Input: n = 5\n Output: 68\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2191, - "title": "Sort the Jumbled Numbers", - "question": "class Solution:\n def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n The 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.\n You are also given another integer array nums. Return the array nums sorted in non-decreasing order based on the mapped values of its elements.\n Notes:\n Elements with the same mapped values should appear in the same relative order as in the input.\n The elements of nums should only be sorted based on their mapped values and not be replaced by them.\n Example 1:\n Input: mapping = [8,9,4,0,2,1,3,5,7,6], nums = [991,338,38]\n Output: [338,38,991]\n Explanation: \n Map the number 991 as follows:\n 1. mapping[9] = 6, so all occurrences of the digit 9 will become 6.\n 2. mapping[1] = 9, so all occurrences of the digit 1 will become 9.\n Therefore, the mapped value of 991 is 669.\n 338 maps to 007, or 7 after removing the leading zeros.\n 38 maps to 07, which is also 7 after removing leading zeros.\n Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.\n Thus, the sorted array is [338,38,991].\n Example 2:\n Input: mapping = [0,1,2,3,4,5,6,7,8,9], nums = [789,456,123]\n Output: [123,456,789]\n Explanation: 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is [123,456,789].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2310, - "title": "Sum of Numbers With Units Digit K", - "question": "class Solution:\n def minimumNumbers(self, num: int, k: int) -> int:\n \"\"\"\n Given two integers num and k, consider a set of positive integers with the following properties:\n The units digit of each integer is k.\n The sum of the integers is num.\n Return the minimum possible size of such a set, or -1 if no such set exists.\n Note:\n The set can contain multiple instances of the same integer, and the sum of an empty set is considered 0.\n The units digit of a number is the rightmost digit of the number.\n Example 1:\n Input: num = 58, k = 9\n Output: 2\n Explanation:\n One valid set is [9,49], as the sum is 58 and each integer has a units digit of 9.\n Another valid set is [19,39].\n It can be shown that 2 is the minimum possible size of a valid set.\n Example 2:\n Input: num = 37, k = 2\n Output: -1\n Explanation: It is not possible to obtain a sum of 37 using only integers that have a units digit of 2.\n Example 3:\n Input: num = 0, k = 7\n Output: 0\n Explanation: The sum of an empty set is considered 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2226, - "title": "Maximum Candies Allocated to K Children", - "question": "class Solution:\n def maximumCandies(self, candies: List[int], k: int) -> int:\n \"\"\"\n 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.\n You 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.\n Return the maximum number of candies each child can get.\n Example 1:\n Input: candies = [5,8,6], k = 3\n Output: 5\n Explanation: 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.\n Example 2:\n Input: candies = [2,5], k = 11\n Output: 0\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1960, - "title": "Maximum Product of the Length of Two Palindromic Substrings", - "question": "class Solution:\n def maxProduct(self, s: str) -> int:\n \"\"\"\n 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.\n More 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.\n Return the maximum possible product of the lengths of the two non-intersecting palindromic substrings.\n A 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:\n Input: s = \"ababbb\"\n Output: 9\n Explanation: Substrings \"aba\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.\n Example 2:\n Input: s = \"zaaaxbbby\"\n Output: 9\n Explanation: Substrings \"aaa\" and \"bbb\" are palindromes with odd length. product = 3 * 3 = 9.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1206, - "title": "Design Skiplist", - "question": "class Skiplist:\n def __init__(self):\n def search(self, target: int) -> bool:\n def add(self, num: int) -> None:\n def erase(self, num: int) -> bool:\n \"\"\"\n Design a Skiplist without using any built-in libraries.\n A skiplist is a data structure that takes O(log(n)) time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists.\n For example, we have a Skiplist containing [30,40,50,60,70,90] and we want to add 80 and 45 into it. The Skiplist works this way:\n Artyom Kalinin [CC BY-SA 3.0], via Wikimedia Commons\n You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than O(n). It can be proven that the average time complexity for each operation is O(log(n)) and space complexity is O(n).\n See more about Skiplist: https://en.wikipedia.org/wiki/Skip_list\n Implement the Skiplist class:\n Skiplist() Initializes the object of the skiplist.\n bool search(int target) Returns true if the integer target exists in the Skiplist or false otherwise.\n void add(int num) Inserts the value num into the SkipList.\n bool erase(int num) Removes the value num from the Skiplist and returns true. If num does not exist in the Skiplist, do nothing and return false. If there exist multiple num values, removing any one of them is fine.\n Note that duplicates may exist in the Skiplist, your code needs to handle this situation.\n Example 1:\n Input\n [\"Skiplist\", \"add\", \"add\", \"add\", \"search\", \"add\", \"search\", \"erase\", \"erase\", \"search\"]\n [[], [1], [2], [3], [0], [4], [1], [0], [1], [1]]\n Output\n [null, null, null, null, false, null, true, false, true, false]\n Explanation\n Skiplist skiplist = new Skiplist();\n skiplist.add(1);\n skiplist.add(2);\n skiplist.add(3);\n skiplist.search(0); // return False\n skiplist.add(4);\n skiplist.search(1); // return True\n skiplist.erase(0); // return False, 0 is not in skiplist.\n skiplist.erase(1); // return True\n skiplist.search(1); // return False, 1 has already been erased.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1226, - "title": "The Dining Philosophers", - "question": "class DiningPhilosophers:\n def wantsToEat(self,\n philosopher: int,\n pickLeftFork: 'Callable[[], None]',\n pickRightFork: 'Callable[[], None]',\n eat: 'Callable[[], None]',\n putLeftFork: 'Callable[[], None]',\n putRightFork: 'Callable[[], None]') -> None:\n \"\"\"\n Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.\n Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can take the fork on their right or the one on their left as they become available, but cannot start eating before getting both forks.\n Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.\n Design a discipline of behaviour (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.\n The problem statement and the image above are taken from wikipedia.org\n The philosophers' ids are numbered from 0 to 4 in a clockwise order. Implement the function void wantsToEat(philosopher, pickLeftFork, pickRightFork, eat, putLeftFork, putRightFork) where:\n philosopher is the id of the philosopher who wants to eat.\n pickLeftFork and pickRightFork are functions you can call to pick the corresponding forks of that philosopher.\n eat is a function you can call to let the philosopher eat once he has picked both forks.\n putLeftFork and putRightFork are functions you can call to put down the corresponding forks of that philosopher.\n The philosophers are assumed to be thinking as long as they are not asking to eat (the function is not being called with their number).\n Five threads, each representing a philosopher, will simultaneously use one object of your class to simulate the process. The function may be called for the same philosopher more than once, even before the last call ends.\n Example 1:\n Input: n = 1\n Output: [[4,2,1],[4,1,1],[0,1,1],[2,2,1],[2,1,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[0,2,1],[4,2,2],[3,2,1],[3,1,1],[0,0,3],[0,1,2],[0,2,2],[1,2,1],[1,1,1],[3,0,3],[3,1,2],[3,2,2],[1,0,3],[1,1,2],[1,2,2]]\n Explanation:\n n is the number of times each philosopher will call the function.\n The output array describes the calls you made to the functions controlling the forks and the eat function, its format is:\n output[i] = [a, b, c] (three integers)\n - a is the id of a philosopher.\n - b specifies the fork: {1 : left, 2 : right}.\n - c specifies the operation: {1 : pick, 2 : put, 3 : eat}.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1221, - "title": "Split a String in Balanced Strings", - "question": "class Solution:\n def balancedStringSplit(self, s: str) -> int:\n \"\"\"\n Balanced strings are those that have an equal quantity of 'L' and 'R' characters.\n Given a balanced string s, split it into some number of substrings such that:\n Each substring is balanced.\n Return the maximum number of balanced strings you can obtain.\n Example 1:\n Input: s = \"RLRRLLRLRL\"\n Output: 4\n Explanation: s can be split into \"RL\", \"RRLL\", \"RL\", \"RL\", each substring contains same number of 'L' and 'R'.\n Example 2:\n Input: s = \"RLRRRLLRLL\"\n Output: 2\n Explanation: s can be split into \"RL\", \"RRRLLRLL\", each substring contains same number of 'L' and 'R'.\n Note that s cannot be split into \"RL\", \"RR\", \"RL\", \"LR\", \"LL\", because the 2nd and 5th substrings are not balanced.\n Example 3:\n Input: s = \"LLLLRRRR\"\n Output: 1\n Explanation: s can be split into \"LLLLRRRR\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1222, - "title": "Queens That Can Attack the King", - "question": "class Solution:\n def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:\n \"\"\"\n On a 0-indexed 8 x 8 chessboard, there can be multiple black queens ad one white king.\n You 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.\n Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.\n Example 1:\n Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]\n Output: [[0,1],[1,0],[3,3]]\n Explanation: 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 Example 2:\n Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]\n Output: [[2,2],[3,4],[4,4]]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1223, - "title": "Dice Roll Simulation", - "question": "class Solution:\n def dieSimulator(self, n: int, rollMax: List[int]) -> int:\n \"\"\"\n A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times.\n Given an array of integers rollMax and an integer n, return the number of distinct sequences that can be obtained with exact n rolls. Since the answer may be too large, return it modulo 109 + 7.\n Two sequences are considered different if at least one element differs from each other.\n Example 1:\n Input: n = 2, rollMax = [1,1,2,2,2,3]\n Output: 34\n Explanation: There will be 2 rolls of die, if there are no constraints on the die, there are 6 * 6 = 36 possible combinations. In this case, looking at rollMax array, the numbers 1 and 2 appear at most once consecutively, therefore sequences (1,1) and (2,2) cannot occur, so the final answer is 36-2 = 34.\n Example 2:\n Input: n = 2, rollMax = [1,1,1,1,1,1]\n Output: 30\n Example 3:\n Input: n = 3, rollMax = [1,1,1,2,2,3]\n Output: 181\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1224, - "title": "Maximum Equal Frequency", - "question": "class Solution:\n def maxEqualFreq(self, nums: List[int]) -> int:\n \"\"\"\n Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.\n If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).\n Example 1:\n Input: nums = [2,2,1,1,5,3,3,5]\n Output: 7\n Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4] = 5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.\n Example 2:\n Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]\n Output: 13\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2202, - "title": "Maximize the Topmost Element After K Moves", - "question": "class Solution:\n def maximumTop(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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.\n In one move, you can perform either of the following:\n If the pile is not empty, remove the topmost element of the pile.\n If there are one or more removed elements, add any one of them back onto the pile. This element becomes the new topmost element.\n You are also given an integer k, which denotes the total number of moves to be made.\n Return 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:\n Input: nums = [5,2,2,4,0,6], k = 4\n Output: 5\n Explanation:\n One 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].\n Note 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.\n Example 2:\n Input: nums = [2], k = 1\n Output: -1\n Explanation: \n In the first move, our only option is to pop the topmost element of the pile.\n Since it is not possible to obtain a non-empty pile after one move, we return -1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2321, - "title": "Maximum Score Of Spliced Array", - "question": "class Solution:\n def maximumsSplicedArray(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n You are given two 0-indexed integer arrays nums1 and nums2, both of length n.\n You 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].\n For 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].\n You may choose to apply the mentioned operation once or not do anything.\n The 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.\n Return the maximum possible score.\n A 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:\n Input: nums1 = [60,60,60], nums2 = [10,90,10]\n Output: 210\n Explanation: Choosing left = 1 and right = 1, we have nums1 = [60,90,60] and nums2 = [10,60,10].\n The score is max(sum(nums1), sum(nums2)) = max(210, 80) = 210.\n Example 2:\n Input: nums1 = [20,40,20,70,30], nums2 = [50,20,50,40,20]\n Output: 220\n Explanation: Choosing left = 3, right = 4, we have nums1 = [20,40,20,40,20] and nums2 = [50,20,50,70,30].\n The score is max(sum(nums1), sum(nums2)) = max(140, 220) = 220.\n Example 3:\n Input: nums1 = [7,11,13], nums2 = [1,1,1]\n Output: 31\n Explanation: We choose not to swap any subarray.\n The score is max(sum(nums1), sum(nums2)) = max(31, 3) = 31.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1232, - "title": "Check If It Is a Straight Line", - "question": "class Solution:\r\n def checkStraightLine(self, coordinates: List[List[int]]) -> bool:\n \"\"\"\n 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.\r\n Example 1:\r\n Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]\r\n Output: true\r\n Example 2:\r\n Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]\r\n Output: false\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1233, - "title": "Remove Sub-Folders from the Filesystem", - "question": "class Solution:\n def removeSubfolders(self, folder: List[str]) -> List[str]:\n \"\"\"\n 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.\n If a folder[i] is located within another folder[j], it is called a sub-folder of it.\n The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.\n For example, \"/leetcode\" and \"/leetcode/problems\" are valid paths while an empty string and \"/\" are not.\n Example 1:\n Input: folder = [\"/a\",\"/a/b\",\"/c/d\",\"/c/d/e\",\"/c/f\"]\n Output: [\"/a\",\"/c/d\",\"/c/f\"]\n Explanation: Folders \"/a/b\" is a subfolder of \"/a\" and \"/c/d/e\" is inside of folder \"/c/d\" in our filesystem.\n Example 2:\n Input: folder = [\"/a\",\"/a/b/c\",\"/a/b/d\"]\n Output: [\"/a\"]\n Explanation: Folders \"/a/b/c\" and \"/a/b/d\" will be removed because they are subfolders of \"/a\".\n Example 3:\n Input: folder = [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\n Output: [\"/a/b/c\",\"/a/b/ca\",\"/a/b/d\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1234, - "title": "Replace the Substring for Balanced String", - "question": "class Solution:\n def balancedString(self, s: str) -> int:\n \"\"\"\n You are given a string s of length n containing only four kinds of characters: 'Q', 'W', 'E', and 'R'.\n A string is said to be balanced if each of its characters appears n / 4 times where n is the length of the string.\n Return 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:\n Input: s = \"QWER\"\n Output: 0\n Explanation: s is already balanced.\n Example 2:\n Input: s = \"QQWE\"\n Output: 1\n Explanation: We need to replace a 'Q' to 'R', so that \"RQWE\" (or \"QRWE\") is balanced.\n Example 3:\n Input: s = \"QQQW\"\n Output: 2\n Explanation: We can replace the first \"QQ\" to \"ER\". \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1235, - "title": "Maximum Profit in Job Scheduling", - "question": "class Solution:\n def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:\n \"\"\"\n We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].\n You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.\n If 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:\n Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]\n Output: 120\n Explanation: The subset chosen is the first and fourth job. \n Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.\n Example 2:\n Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]\n Output: 150\n Explanation: The subset chosen is the first, fourth and fifth job. \n Profit obtained 150 = 20 + 70 + 60.\n Example 3:\n Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]\n Output: 6\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2273, - "title": "Find Resultant Array After Removing Anagrams", - "question": "class Solution:\n def removeAnagrams(self, words: List[str]) -> List[str]:\n \"\"\"\n You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.\n In 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.\n Return 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.\n An 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:\n Input: words = [\"abba\",\"baba\",\"bbaa\",\"cd\",\"cd\"]\n Output: [\"abba\",\"cd\"]\n Explanation:\n One 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\"].\n We can no longer perform any operations, so [\"abba\",\"cd\"] is the final answer.\n Example 2:\n Input: words = [\"a\",\"b\",\"c\",\"d\",\"e\"]\n Output: [\"a\",\"b\",\"c\",\"d\",\"e\"]\n Explanation:\n No two adjacent strings in words are anagrams of each other, so no operations are performed.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2225, - "title": "Find Players With Zero or One Losses", - "question": "class Solution:\n def findWinners(self, matches: List[List[int]]) -> List[List[int]]:\n \"\"\"\n You are given an integer array matches where matches[i] = [winneri, loseri] indicates that the player winneri defeated player loseri in a match.\n Return a list answer of size 2 where:\n answer[0] is a list of all players that have not lost any matches.\n answer[1] is a list of all players that have lost exactly one match.\n The values in the two lists should be returned in increasing order.\n Note:\n You should only consider the players that have played at least one match.\n The testcases will be generated such that no two matches will have the same outcome.\n Example 1:\n Input: matches = [[1,3],[2,3],[3,6],[5,6],[5,7],[4,5],[4,8],[4,9],[10,4],[10,9]]\n Output: [[1,2,10],[4,5,7,8]]\n Explanation:\n Players 1, 2, and 10 have not lost any matches.\n Players 4, 5, 7, and 8 each have lost one match.\n Players 3, 6, and 9 each have lost two matches.\n Thus, answer[0] = [1,2,10] and answer[1] = [4,5,7,8].\n Example 2:\n Input: matches = [[2,3],[1,3],[5,4],[6,4]]\n Output: [[1,2,5,6],[]]\n Explanation:\n Players 1, 2, 5, and 6 have not lost any matches.\n Players 3 and 4 each have lost two matches.\n Thus, answer[0] = [1,2,5,6] and answer[1] = [].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2216, - "title": "Minimum Deletions to Make Array Beautiful", - "question": "class Solution:\n def minDeletion(self, nums: List[int]) -> int:\n \"\"\"\n You are given a 0-indexed integer array nums. The array nums is beautiful if:\n nums.length is even.\n nums[i] != nums[i + 1] for all i % 2 == 0.\n Note that an empty array is considered beautiful.\n You 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.\n Return the minimum number of elements to delete from nums to make it beautiful.\n Example 1:\n Input: nums = [1,1,2,3,5]\n Output: 1\n Explanation: 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.\n Example 2:\n Input: nums = [1,1,2,2,3,3]\n Output: 2\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2193, - "title": "Minimum Number of Moves to Make Palindrome", - "question": "class Solution:\n def minMovesToMakePalindrome(self, s: str) -> int:\n \"\"\"\n You are given a string s consisting only of lowercase English letters.\n In one move, you can select any two adjacent characters of s and swap them.\n Return the minimum number of moves needed to make s a palindrome.\n Note that the input will be generated such that s can always be converted to a palindrome.\n Example 1:\n Input: s = \"aabb\"\n Output: 2\n Explanation:\n We 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\".\n Thus, the minimum number of moves needed to make s a palindrome is 2.\n Example 2:\n Input: s = \"letelt\"\n Output: 2\n Explanation:\n One of the palindromes we can obtain from s in 2 moves is \"lettel\".\n One of the ways we can obtain it is \"letelt\" -> \"letetl\" -> \"lettel\".\n Other palindromes such as \"tleelt\" can also be obtained in 2 moves.\n It can be shown that it is not possible to obtain a palindrome in less than 2 moves.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1237, - "title": "Find Positive Integer Solution for a Given Equation", - "question": "\n \"\"\"\n This is the custom function interface.\n You should not implement it, or speculate about its implementation\n class CustomFunction:\n def f(self, x, y):\n 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.\n While the exact formula is hidden, the function is monotonically increasing, i.e.:\n f(x, y) < f(x + 1, y)\n f(x, y) < f(x, y + 1)\n The function interface is defined like this:\n interface CustomFunction {\n public:\n // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.\n int f(int x, int y);\n };\n We will judge your solution as follows:\n The 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.\n The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.\n The judge will call your findSolution and compare your results with the answer key.\n If your results match the answer key, your solution will be Accepted.\n Example 1:\n Input: function_id = 1, z = 5\n Output: [[1,4],[2,3],[3,2],[4,1]]\n Explanation: The hidden formula for function_id = 1 is f(x, y) = x + y.\n The following positive integer values of x and y make f(x, y) equal to 5:\n x=1, y=4 -> f(1, 4) = 1 + 4 = 5.\n x=2, y=3 -> f(2, 3) = 2 + 3 = 5.\n x=3, y=2 -> f(3, 2) = 3 + 2 = 5.\n x=4, y=1 -> f(4, 1) = 4 + 1 = 5.\n Example 2:\n Input: function_id = 2, z = 5\n Output: [[1,5],[5,1]]\n Explanation: The hidden formula for function_id = 2 is f(x, y) = x * y.\n The following positive integer values of x and y make f(x, y) equal to 5:\n x=1, y=5 -> f(1, 5) = 1 * 5 = 5.\n x=5, y=1 -> f(5, 1) = 5 * 1 = 5.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1238, - "title": "Circular Permutation in Binary Representation", - "question": "class Solution:\r\n def circularPermutation(self, n: int, start: int) -> List[int]:\n \"\"\"\n Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that :\r\n p[0] = start\r\n p[i] and p[i+1] differ by only one bit in their binary representation.\r\n p[0] and p[2^n -1] must also differ by only one bit in their binary representation.\r\n Example 1:\r\n Input: n = 2, start = 3\r\n Output: [3,2,0,1]\r\n Explanation: The binary representation of the permutation is (11,10,00,01). \r\n All the adjacent element differ by one bit. Another valid permutation is [3,1,0,2]\r\n Example 2:\r\n Input: n = 3, start = 2\r\n Output: [2,6,7,5,4,0,1,3]\r\n Explanation: The binary representation of the permutation is (010,110,111,101,100,000,001,011).\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1239, - "title": "Maximum Length of a Concatenated String with Unique Characters", - "question": "class Solution:\n def maxLength(self, arr: List[str]) -> int:\n \"\"\"\n 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.\n Return the maximum possible length of s.\n A 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:\n Input: arr = [\"un\",\"iq\",\"ue\"]\n Output: 4\n Explanation: All the valid concatenations are:\n - \"\"\n - \"un\"\n - \"iq\"\n - \"ue\"\n - \"uniq\" (\"un\" + \"iq\")\n - \"ique\" (\"iq\" + \"ue\")\n Maximum length is 4.\n Example 2:\n Input: arr = [\"cha\",\"r\",\"act\",\"ers\"]\n Output: 6\n Explanation: Possible longest valid concatenations are \"chaers\" (\"cha\" + \"ers\") and \"acters\" (\"act\" + \"ers\").\n Example 3:\n Input: arr = [\"abcdefghijklmnopqrstuvwxyz\"]\n Output: 26\n Explanation: The only string in arr has all 26 characters.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1240, - "title": "Tiling a Rectangle with the Fewest Squares", - "question": "class Solution:\n def tilingRectangle(self, n: int, m: int) -> int:\n \"\"\"\n Given a rectangle of size n x m, return the minimum number of integer-sided squares that tile the rectangle.\n Example 1:\n Input: n = 2, m = 3\n Output: 3\n Explanation: 3 squares are necessary to cover the rectangle.\n 2 (squares of 1x1)\n 1 (square of 2x2)\n Example 2:\n Input: n = 5, m = 8\n Output: 5\n Example 3:\n Input: n = 11, m = 13\n Output: 6\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1227, - "title": "Airplane Seat Assignment Probability", - "question": "class Solution:\n def nthPersonGetsNthSeat(self, n: int) -> float:\n \"\"\"\n 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:\n Take their own seat if it is still available, and\n Pick other seats randomly when they find their seat occupied\n Return the probability that the nth person gets his own seat.\n Example 1:\n Input: n = 1\n Output: 1.00000\n Explanation: The first person can only get the first seat.\n Example 2:\n Input: n = 2\n Output: 0.50000\n Explanation: The second person has a probability of 0.5 to get the second seat (when first person gets the first seat).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2309, - "title": "Greatest English Letter in Upper and Lower Case", - "question": "class Solution:\n def greatestLetter(self, s: str) -> str:\n \"\"\"\n 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.\n An English letter b is greater than another letter a if b appears after a in the English alphabet.\n Example 1:\n Input: s = \"lEeTcOdE\"\n Output: \"E\"\n Explanation:\n The letter 'E' is the only letter to appear in both lower and upper case.\n Example 2:\n Input: s = \"arRAzFif\"\n Output: \"R\"\n Explanation:\n The letter 'R' is the greatest letter to appear in both lower and upper case.\n Note that 'A' and 'F' also appear in both lower and upper case, but 'R' is greater than 'F' or 'A'.\n Example 3:\n Input: s = \"AbCdEfGhIjK\"\n Output: \"\"\n Explanation:\n There is no letter that appears in both lower and upper case.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1726, - "title": "Tuple with Same Product", - "question": "class Solution:\n def tupleSameProduct(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [2,3,4,6]\n Output: 8\n Explanation: There are 8 valid tuples:\n (2,6,3,4) , (2,6,4,3) , (6,2,3,4) , (6,2,4,3)\n (3,4,2,6) , (4,3,2,6) , (3,4,6,2) , (4,3,6,2)\n Example 2:\n Input: nums = [1,2,4,5,10]\n Output: 16\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1691, - "title": "Maximum Height by Stacking Cuboids ", - "question": "class Solution:\n def maxHeight(self, cuboids: List[List[int]]) -> int:\n \"\"\"\n Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed). Choose a subset of cuboids and place them on each other.\n You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.\n Return the maximum height of the stacked cuboids.\n Example 1:\n Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]\n Output: 190\n Explanation:\n Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.\n Cuboid 0 is placed next with the 45x20 side facing down with height 50.\n Cuboid 2 is placed next with the 23x12 side facing down with height 45.\n The total height is 95 + 50 + 45 = 190.\n Example 2:\n Input: cuboids = [[38,25,45],[76,35,3]]\n Output: 76\n Explanation:\n You can't place any of the cuboids on the other.\n We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.\n Example 3:\n Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]\n Output: 102\n Explanation:\n After rearranging the cuboids, you can see that all cuboids have the same dimension.\n You can place the 11x7 side down on all cuboids so their heights are 17.\n The maximum height of stacked cuboids is 6 * 17 = 102.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1247, - "title": "Minimum Swaps to Make Strings Equal", - "question": "class Solution:\n def minimumSwap(self, s1: str, s2: str) -> int:\n \"\"\"\n 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].\n Return 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:\n Input: s1 = \"xx\", s2 = \"yy\"\n Output: 1\n Explanation: Swap s1[0] and s2[1], s1 = \"yx\", s2 = \"yx\".\n Example 2:\n Input: s1 = \"xy\", s2 = \"yx\"\n Output: 2\n Explanation: Swap s1[0] and s2[0], s1 = \"yy\", s2 = \"xx\".\n Swap s1[0] and s2[1], s1 = \"xy\", s2 = \"xy\".\n Note that you cannot swap s1[0] and s1[1] to make s1 equal to \"yx\", cause we can only swap chars in different strings.\n Example 3:\n Input: s1 = \"xx\", s2 = \"xy\"\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1248, - "title": "Count Number of Nice Subarrays", - "question": "class Solution:\r\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n \"\"\"\n Given an array of integers nums and an integer k. A continuous subarray is called nice if there are k odd numbers on it.\r\n Return the number of nice sub-arrays.\r\n Example 1:\r\n Input: nums = [1,1,2,1,1], k = 3\r\n Output: 2\r\n Explanation: The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].\r\n Example 2:\r\n Input: nums = [2,4,6], k = 1\r\n Output: 0\r\n Explanation: There is no odd numbers in the array.\r\n Example 3:\r\n Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2\r\n Output: 16\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1249, - "title": "Minimum Remove to Make Valid Parentheses", - "question": "class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n \"\"\"\n Given a string s of '(' , ')' and lowercase English characters.\n Your 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.\n Formally, a parentheses string is valid if and only if:\n It is the empty string, contains only lowercase characters, or\n It can be written as AB (A concatenated with B), where A and B are valid strings, or\n It can be written as (A), where A is a valid string.\n Example 1:\n Input: s = \"lee(t(c)o)de)\"\n Output: \"lee(t(c)o)de\"\n Explanation: \"lee(t(co)de)\" , \"lee(t(c)ode)\" would also be accepted.\n Example 2:\n Input: s = \"a)b(c)d\"\n Output: \"ab(c)d\"\n Example 3:\n Input: s = \"))((\"\n Output: \"\"\n Explanation: An empty string is also valid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1250, - "title": "Check If It Is a Good Array", - "question": "class Solution:\n def isGoodArray(self, nums: List[int]) -> bool:\n \"\"\"\n Given an array nums of positive integers. Your task is to select some subset of nums, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1 from the array by any possible subset and multiplicand.\n Return True if the array is good otherwise return False.\n Example 1:\n Input: nums = [12,5,7,23]\n Output: true\n Explanation: Pick numbers 5 and 7.\n 5*3 + 7*(-2) = 1\n Example 2:\n Input: nums = [29,6,10]\n Output: true\n Explanation: Pick numbers 29, 6 and 10.\n 29*1 + 6*(-3) + 10*(-1) = 1\n Example 3:\n Input: nums = [3,6]\n Output: false\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2217, - "title": "Find Palindrome With Fixed Length", - "question": "class Solution:\n def kthPalindrome(self, queries: List[int], intLength: int) -> List[int]:\n \"\"\"\n 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.\n A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.\n Example 1:\n Input: queries = [1,2,3,4,5,90], intLength = 3\n Output: [101,111,121,131,141,999]\n Explanation:\n The first few palindromes of length 3 are:\n 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, ...\n The 90th palindrome of length 3 is 999.\n Example 2:\n Input: queries = [2,4,6], intLength = 4\n Output: [1111,1331,1551]\n Explanation:\n The first six palindromes of length 4 are:\n 1001, 1111, 1221, 1331, 1441, and 1551.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2312, - "title": "Selling Pieces of Wood", - "question": "class Solution:\n def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:\n \"\"\"\n 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.\n To 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.\n Return the maximum money you can earn after cutting an m x n piece of wood.\n Note that you can cut the piece of wood as many times as you want.\n Example 1:\n Input: m = 3, n = 5, prices = [[1,4,2],[2,2,7],[2,1,3]]\n Output: 19\n Explanation: 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.\n This obtains a total of 14 + 3 + 2 = 19 money earned.\n It can be shown that 19 is the maximum amount of money that can be earned.\n Example 2:\n Input: m = 4, n = 6, prices = [[3,2,10],[1,4,2],[4,1,3]]\n Output: 32\n Explanation: 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.\n This obtains a total of 30 + 2 = 32 money earned.\n It can be shown that 32 is the maximum amount of money that can be earned.\n Notice that we cannot rotate the 1 x 4 piece of wood to obtain a 4 x 1 piece of wood.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1252, - "title": "Cells with Odd Values in a Matrix", - "question": "class Solution:\n def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:\n \"\"\"\n 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.\n For each location indices[i], do both of the following:\n Increment all the cells on row ri.\n Increment all the cells on column ci.\n Given 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:\n Input: m = 2, n = 3, indices = [[0,1],[1,1]]\n Output: 6\n Explanation: Initial matrix = [[0,0,0],[0,0,0]].\n After applying first increment it becomes [[1,2,1],[0,1,0]].\n The final matrix is [[1,3,1],[1,3,1]], which contains 6 odd numbers.\n Example 2:\n Input: m = 2, n = 2, indices = [[1,1],[0,0]]\n Output: 0\n Explanation: Final matrix = [[2,2],[2,2]]. There are no odd numbers in the final matrix.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1253, - "title": "Reconstruct a 2-Row Binary Matrix", - "question": "class Solution:\n def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]:\n \"\"\"\n Given the following details of a matrix with n columns and 2 rows :\n The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.\n The sum of elements of the 0-th(upper) row is given as upper.\n The sum of elements of the 1-st(lower) row is given as lower.\n The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.\n Your task is to reconstruct the matrix with upper, lower and colsum.\n Return it as a 2-D integer array.\n If there are more than one valid solution, any of them will be accepted.\n If no valid solution exists, return an empty 2-D array.\n Example 1:\n Input: upper = 2, lower = 1, colsum = [1,1,1]\n Output: [[1,1,0],[0,0,1]]\n Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.\n Example 2:\n Input: upper = 2, lower = 3, colsum = [2,2,1,1]\n Output: []\n Example 3:\n Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]\n Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1254, - "title": "Number of Closed Islands", - "question": "class Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the number of closed islands.\n Example 1:\n Input: 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]]\n Output: 2\n Explanation: \n Islands in gray are closed because they are completely surrounded by water (group of 1s).\n Example 2:\n Input: grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]\n Output: 1\n Example 3:\n Input: 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]]\n Output: 2\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1255, - "title": "Maximum Score Words Formed by Letters", - "question": "class Solution:\n def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:\n \"\"\"\n Given a list of words, list of single letters (might be repeating) and score of every character.\n Return the maximum score of any valid set of words formed by using the given letters (words[i] cannot be used two or more times).\n It is not necessary to use all characters in letters and each letter can only be used once. Score of letters 'a', 'b', 'c', ... ,'z' is given by score[0], score[1], ... , score[25] respectively.\n Example 1:\n Input: words = [\"dog\",\"cat\",\"dad\",\"good\"], letters = [\"a\",\"a\",\"c\",\"d\",\"d\",\"d\",\"g\",\"o\",\"o\"], score = [1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0]\n Output: 23\n Explanation:\n Score a=1, c=9, d=5, g=3, o=2\n Given letters, we can form the words \"dad\" (5+1+5) and \"good\" (3+2+2+5) with a score of 23.\n Words \"dad\" and \"dog\" only get a score of 21.\n Example 2:\n Input: words = [\"xxxz\",\"ax\",\"bx\",\"cx\"], letters = [\"z\",\"a\",\"b\",\"c\",\"x\",\"x\",\"x\"], score = [4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10]\n Output: 27\n Explanation:\n Score a=4, b=4, c=4, x=5, z=10\n Given letters, we can form the words \"ax\" (4+5), \"bx\" (4+5) and \"cx\" (4+5) with a score of 27.\n Word \"xxxz\" only get a score of 25.\n Example 3:\n Input: words = [\"leetcode\"], letters = [\"l\",\"e\",\"t\",\"c\",\"o\",\"d\"], score = [0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0]\n Output: 0\n Explanation:\n Letter \"e\" can only be used once.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2303, - "title": "Calculate Amount Paid in Taxes", - "question": "class Solution:\n def calculateTax(self, brackets: List[List[int]], income: int) -> float:\n \"\"\"\n 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).\n Tax is calculated as follows:\n The first upper0 dollars earned are taxed at a rate of percent0.\n The next upper1 - upper0 dollars earned are taxed at a rate of percent1.\n The next upper2 - upper1 dollars earned are taxed at a rate of percent2.\n And so on.\n You 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:\n Input: brackets = [[3,50],[7,10],[12,25]], income = 10\n Output: 2.65000\n Explanation:\n Based 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.\n The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.\n In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.\n Example 2:\n Input: brackets = [[1,0],[4,25],[5,50]], income = 2\n Output: 0.25000\n Explanation:\n Based on your income, you have 1 dollar in the 1st tax bracket and 1 dollar in the 2nd tax bracket.\n The tax rate for the two tax brackets is 0% and 25%, respectively.\n In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.\n Example 3:\n Input: brackets = [[2,50]], income = 0\n Output: 0.00000\n Explanation:\n You have no income to tax, so you have to pay a total of $0 in taxes.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1260, - "title": "Shift 2D Grid", - "question": "class Solution:\n def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n \"\"\"\n Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.\n In one shift operation:\n Element at grid[i][j] moves to grid[i][j + 1].\n Element at grid[i][n - 1] moves to grid[i + 1][0].\n Element at grid[m - 1][n - 1] moves to grid[0][0].\n Return the 2D grid after applying shift operation k times.\n Example 1:\n Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1\n Output: [[9,1,2],[3,4,5],[6,7,8]]\n Example 2:\n Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4\n Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]\n Example 3:\n Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9\n Output: [[1,2,3],[4,5,6],[7,8,9]]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1261, - "title": "Find Elements in a Contaminated Binary Tree", - "question": "class FindElements:\n def __init__(self, root: Optional[TreeNode]):\n def find(self, target: int) -> bool:\n \"\"\"\n Given a binary tree with the following rules:\n root.val == 0\n If treeNode.val == x and treeNode.left != null, then treeNode.left.val == 2 * x + 1\n If treeNode.val == x and treeNode.right != null, then treeNode.right.val == 2 * x + 2\n Now the binary tree is contaminated, which means all treeNode.val have been changed to -1.\n Implement the FindElements class:\n FindElements(TreeNode* root) Initializes the object with a contaminated binary tree and recovers it.\n bool find(int target) Returns true if the target value exists in the recovered binary tree.\n Example 1:\n Input\n [\"FindElements\",\"find\",\"find\"]\n [[[-1,null,-1]],[1],[2]]\n Output\n [null,false,true]\n Explanation\n FindElements findElements = new FindElements([-1,null,-1]); \n findElements.find(1); // return False \n findElements.find(2); // return True \n Example 2:\n Input\n [\"FindElements\",\"find\",\"find\",\"find\"]\n [[[-1,-1,-1,-1,-1]],[1],[3],[5]]\n Output\n [null,true,true,false]\n Explanation\n FindElements findElements = new FindElements([-1,-1,-1,-1,-1]);\n findElements.find(1); // return True\n findElements.find(3); // return True\n findElements.find(5); // return False\n Example 3:\n Input\n [\"FindElements\",\"find\",\"find\",\"find\",\"find\"]\n [[[-1,null,-1,-1,null,-1]],[2],[3],[4],[5]]\n Output\n [null,true,false,false,true]\n Explanation\n FindElements findElements = new FindElements([-1,null,-1,-1,null,-1]);\n findElements.find(2); // return True\n findElements.find(3); // return False\n findElements.find(4); // return False\n findElements.find(5); // return True\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1262, - "title": "Greatest Sum Divisible by Three", - "question": "class Solution:\n def maxSumDivThree(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [3,6,5,1,8]\n Output: 18\n Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).\n Example 2:\n Input: nums = [4]\n Output: 0\n Explanation: Since 4 is not divisible by 3, do not pick any number.\n Example 3:\n Input: nums = [1,2,3,4,4]\n Output: 12\n Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1263, - "title": "Minimum Moves to Move a Box to Their Target Location", - "question": "class Solution:\n def minPushBox(self, grid: List[List[str]]) -> int:\n \"\"\"\n A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.\n The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.\n Your task is to move the box 'B' to the target position 'T' under the following rules:\n The character 'S' represents the player. The player can move up, down, left, right in grid if it is a floor (empty cell).\n The character '.' represents the floor which means a free cell to walk.\n The character '#' represents the wall which means an obstacle (impossible to walk there).\n There is only one box 'B' and one target cell 'T' in the grid.\n The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push.\n The player cannot walk through the box.\n Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, return -1.\n Example 1:\n Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n Output: 3\n Explanation: We return only the number of times the box is pushed.\n Example 2:\n Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n Output: -1\n Example 3:\n Input: grid = [[\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\".\",\".\",\"#\",\"#\"],\n [\"#\",\".\",\"#\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\".\",\"#\"],\n [\"#\",\".\",\".\",\".\",\"S\",\"#\"],\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"]]\n Output: 5\n Explanation: push the box down, left, left, up and up.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2215, - "title": "Find the Difference of Two Arrays", - "question": "class Solution:\n def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:\n \"\"\"\n Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:\n answer[0] is a list of all distinct integers in nums1 which are not present in nums2.\n answer[1] is a list of all distinct integers in nums2 which are not present in nums1.\n Note that the integers in the lists may be returned in any order.\n Example 1:\n Input: nums1 = [1,2,3], nums2 = [2,4,6]\n Output: [[1,3],[4,6]]\n Explanation:\n For 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].\n For 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].\n Example 2:\n Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]\n Output: [[3],[]]\n Explanation:\n For 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].\n Every integer in nums2 is present in nums1. Therefore, answer[1] = [].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2218, - "title": "Maximum Value of K Coins From Piles", - "question": "class Solution:\n def maxValueOfCoins(self, piles: List[List[int]], k: int) -> int:\n \"\"\"\n There are n piles of coins on a table. Each pile consists of a positive number of coins of assorted denominations.\n In one move, you can choose any coin on top of any pile, remove it, and add it to your wallet.\n Given 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:\n Input: piles = [[1,100,3],[7,8,9]], k = 2\n Output: 101\n Explanation:\n The above diagram shows the different ways we can choose k coins.\n The maximum total we can obtain is 101.\n Example 2:\n Input: piles = [[100],[100],[100],[100],[100],[100],[1,1,1,1,1,1,700]], k = 7\n Output: 706\n Explanation:\n The maximum total can be obtained if we choose all coins from the last pile.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2304, - "title": "Minimum Path Cost in a Grid", - "question": "class Solution:\n def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:\n \"\"\"\n 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.\n Each 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.\n The 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:\n Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]\n Output: 17\n Explanation: 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.\n So the total cost of the path is 6 + 3 + 8 = 17.\n Example 2:\n Input: 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]]\n Output: 6\n Explanation: 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.\n So the total cost of this path is 5 + 1 = 6.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1266, - "title": "Minimum Time Visiting All Points", - "question": "class Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n \"\"\"\n 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.\n You can move according to these rules:\n In 1 second, you can either:\n move vertically by one unit,\n move horizontally by one unit, or\n move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in 1 second).\n You have to visit the points in the same order as they appear in the array.\n You are allowed to pass through points that appear later in the order, but these do not count as visits.\n Example 1:\n Input: points = [[1,1],[3,4],[-1,0]]\n Output: 7\n Explanation: One optimal path is [1,1] -> [2,2] -> [3,3] -> [3,4] -> [2,3] -> [1,2] -> [0,1] -> [-1,0] \n Time from [1,1] to [3,4] = 3 seconds \n Time from [3,4] to [-1,0] = 4 seconds\n Total time = 7 seconds\n Example 2:\n Input: points = [[3,2],[-2,2]]\n Output: 5\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1267, - "title": "Count Servers that Communicate", - "question": "class Solution:\n def countServers(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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 Return the number of servers that communicate with any other server.\n Example 1:\n Input: grid = [[1,0],[0,1]]\n Output: 0\n Explanation: No servers can communicate with others.\n Example 2:\n Input: grid = [[1,0],[1,1]]\n Output: 3\n Explanation: All three servers can communicate with at least one other server.\n Example 3:\n Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]\n Output: 4\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1268, - "title": "Search Suggestions System", - "question": "class Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n \"\"\"\n You are given an array of strings products and a string searchWord.\n Design 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.\n Return a list of lists of the suggested products after each character of searchWord is typed.\n Example 1:\n Input: products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord = \"mouse\"\n Output: [[\"mobile\",\"moneypot\",\"monitor\"],[\"mobile\",\"moneypot\",\"monitor\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"],[\"mouse\",\"mousepad\"]]\n Explanation: products sorted lexicographically = [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"].\n After typing m and mo all products match and we show user [\"mobile\",\"moneypot\",\"monitor\"].\n After typing mou, mous and mouse the system suggests [\"mouse\",\"mousepad\"].\n Example 2:\n Input: products = [\"havana\"], searchWord = \"havana\"\n Output: [[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\n Explanation: The only word \"havana\" will be always suggested while typing the search word.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1269, - "title": "Number of Ways to Stay in the Same Place After Some Steps", - "question": "class Solution:\n def numWays(self, steps: int, arrLen: int) -> int:\n \"\"\"\n You have a pointer at index 0 in an array of size arrLen. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).\n Given 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:\n Input: steps = 3, arrLen = 2\n Output: 4\n Explanation: There are 4 differents ways to stay at index 0 after 3 steps.\n Right, Left, Stay\n Stay, Right, Left\n Right, Stay, Left\n Stay, Stay, Stay\n Example 2:\n Input: steps = 2, arrLen = 4\n Output: 2\n Explanation: There are 2 differents ways to stay at index 0 after 2 steps\n Right, Left\n Stay, Stay\n Example 3:\n Input: steps = 4, arrLen = 2\n Output: 8\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1275, - "title": "Find Winner on a Tic Tac Toe Game", - "question": "class Solution:\n def tictactoe(self, moves: List[List[int]]) -> str:\n \"\"\"\n Tic-tac-toe is played by two players A and B on a 3 x 3 grid. The rules of Tic-Tac-Toe are:\n Players take turns placing characters into empty squares ' '.\n The 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.\n The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal.\n The game also ends if all squares are non-empty.\n No more moves can be played if the game is over.\n Given 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\".\n You 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:\n Input: moves = [[0,0],[2,0],[1,1],[2,1],[2,2]]\n Output: \"A\"\n Explanation: A wins, they always play first.\n Example 2:\n Input: moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0]]\n Output: \"B\"\n Explanation: B wins.\n Example 3:\n Input: moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,1],[0,1],[0,2],[2,2]]\n Output: \"Draw\"\n Explanation: The game ends in a draw since there are no moves to make.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1276, - "title": "Number of Burgers with No Waste of Ingredients", - "question": "class Solution:\n def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]:\n \"\"\"\n Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:\n Jumbo Burger: 4 tomato slices and 1 cheese slice.\n Small Burger: 2 Tomato slices and 1 cheese slice.\n Return [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:\n Input: tomatoSlices = 16, cheeseSlices = 7\n Output: [1,6]\n Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.\n There will be no remaining ingredients.\n Example 2:\n Input: tomatoSlices = 17, cheeseSlices = 4\n Output: []\n Explantion: There will be no way to use all ingredients to make small and jumbo burgers.\n Example 3:\n Input: tomatoSlices = 4, cheeseSlices = 17\n Output: []\n Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1277, - "title": "Count Square Submatrices with All Ones", - "question": "class Solution:\n def countSquares(self, matrix: List[List[int]]) -> int:\n \"\"\"\n Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.\n Example 1:\n Input: matrix =\n [\n [0,1,1,1],\n [1,1,1,1],\n [0,1,1,1]\n ]\n Output: 15\n Explanation: \n There are 10 squares of side 1.\n There are 4 squares of side 2.\n There is 1 square of side 3.\n Total number of squares = 10 + 4 + 1 = 15.\n Example 2:\n Input: matrix = \n [\n [1,0,1],\n [1,1,0],\n [1,1,0]\n ]\n Output: 7\n Explanation: \n There are 6 squares of side 1. \n There is 1 square of side 2. \n Total number of squares = 6 + 1 = 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1278, - "title": "Palindrome Partitioning III", - "question": "class Solution:\n def palindromePartition(self, s: str, k: int) -> int:\n \"\"\"\n You are given a string s containing lowercase letters and an integer k. You need to :\n First, change some characters of s to other lowercase English letters.\n Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.\n Return the minimal number of characters that you need to change to divide the string.\n Example 1:\n Input: s = \"abc\", k = 2\n Output: 1\n Explanation: You can split the string into \"ab\" and \"c\", and change 1 character in \"ab\" to make it palindrome.\n Example 2:\n Input: s = \"aabbc\", k = 3\n Output: 0\n Explanation: You can split the string into \"aa\", \"bb\" and \"c\", all of them are palindrome.\n Example 3:\n Input: s = \"leetcode\", k = 8\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1281, - "title": "Subtract the Product and Sum of Digits of an Integer", - "question": "class Solution:\n def subtractProductAndSum(self, n: int) -> int:\n \"\"\"\n Given an integer number n, return the difference between the product of its digits and the sum of its digits.\n Example 1:\n Input: n = 234\n Output: 15 \n Explanation: \n Product of digits = 2 * 3 * 4 = 24 \n Sum of digits = 2 + 3 + 4 = 9 \n Result = 24 - 9 = 15\n Example 2:\n Input: n = 4421\n Output: 21\n Explanation: \n Product of digits = 4 * 4 * 2 * 1 = 32 \n Sum of digits = 4 + 4 + 2 + 1 = 11 \n Result = 32 - 11 = 21\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1282, - "title": "Group the People Given the Group Size They Belong To", - "question": "class Solution:\n def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:\n \"\"\"\n 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.\n You 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.\n Return a list of groups such that each person i is in a group of size groupSizes[i].\n Each 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:\n Input: groupSizes = [3,3,3,3,3,1,3]\n Output: [[5],[0,1,2],[3,4,6]]\n Explanation: \n The first group is [5]. The size is 1, and groupSizes[5] = 1.\n The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.\n The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.\n Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].\n Example 2:\n Input: groupSizes = [2,1,3,3,3,2]\n Output: [[1],[0,5],[2,3,4]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1283, - "title": "Find the Smallest Divisor Given a Threshold", - "question": "class Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n \"\"\"\n 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.\n Each 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).\n The test cases are generated so that there will be an answer.\n Example 1:\n Input: nums = [1,2,5,9], threshold = 6\n Output: 5\n Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. \n If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). \n Example 2:\n Input: nums = [44,22,33,11,1], threshold = 5\n Output: 44\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1284, - "title": "Minimum Number of Flips to Convert Binary Matrix to Zero Matrix", - "question": "class Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the minimum number of steps required to convert mat to a zero matrix or -1 if you cannot.\n A binary matrix is a matrix with all cells equal to 0 or 1 only.\n A zero matrix is a matrix with all cells equal to 0.\n Example 1:\n Input: mat = [[0,0],[0,1]]\n Output: 3\n Explanation: One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown.\n Example 2:\n Input: mat = [[0]]\n Output: 0\n Explanation: Given matrix is a zero matrix. We do not need to change it.\n Example 3:\n Input: mat = [[1,0,0],[1,0,0]]\n Output: -1\n Explanation: Given matrix cannot be a zero matrix.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1290, - "title": "Convert Binary Number in a Linked List to Integer", - "question": "class Solution:\n def getDecimalValue(self, head: ListNode) -> int:\n \"\"\"\n 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.\n Return the decimal value of the number in the linked list.\n The most significant bit is at the head of the linked list.\n Example 1:\n Input: head = [1,0,1]\n Output: 5\n Explanation: (101) in base 2 = (5) in base 10\n Example 2:\n Input: head = [0]\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1292, - "title": "Maximum Side Length of a Square with Sum Less than or Equal to Threshold", - "question": "class Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:\n \"\"\"\n 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:\n Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4\n Output: 2\n Explanation: The maximum side length of square with sum less than 4 is 2 as shown.\n Example 2:\n Input: 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\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1293, - "title": "Shortest Path in a Grid with Obstacles Elimination", - "question": "class Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n \"\"\"\n You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.\n Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.\n Example 1:\n Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1\n Output: 6\n Explanation: \n The shortest path without eliminating any obstacle is 10.\n The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).\n Example 2:\n Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1\n Output: -1\n Explanation: We need to eliminate at least two obstacles to find such a walk.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2305, - "title": "Fair Distribution of Cookies", - "question": "class Solution:\n def distributeCookies(self, cookies: List[int], k: int) -> int:\n \"\"\"\n 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.\n The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.\n Return the minimum unfairness of all distributions.\n Example 1:\n Input: cookies = [8,15,10,20,8], k = 2\n Output: 31\n Explanation: 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.\n The unfairness of the distribution is max(31,30) = 31.\n It can be shown that there is no distribution with an unfairness less than 31.\n Example 2:\n Input: cookies = [6,1,3,2,2,4,1,2], k = 3\n Output: 7\n Explanation: 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.\n The unfairness of the distribution is max(7,7,7) = 7.\n It can be shown that there is no distribution with an unfairness less than 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1295, - "title": "Find Numbers with Even Number of Digits", - "question": "class Solution:\n def findNumbers(self, nums: List[int]) -> int:\n \"\"\"\n Given an array nums of integers, return how many of them contain an even number of digits.\n Example 1:\n Input: nums = [12,345,2,6,7896]\n Output: 2\n Explanation: \n 12 contains 2 digits (even number of digits). \n 345 contains 3 digits (odd number of digits). \n 2 contains 1 digit (odd number of digits). \n 6 contains 1 digit (odd number of digits). \n 7896 contains 4 digits (even number of digits). \n Therefore only 12 and 7896 contain an even number of digits.\n Example 2:\n Input: nums = [555,901,482,1771]\n Output: 1 \n Explanation: \n Only 1771 contains an even number of digits.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1296, - "title": "Divide Array in Sets of K Consecutive Numbers", - "question": "class Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n \"\"\"\n 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.\n Return true if it is possible. Otherwise, return false.\n Example 1:\n Input: nums = [1,2,3,3,4,4,5,6], k = 4\n Output: true\n Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].\n Example 2:\n Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\n Output: true\n Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].\n Example 3:\n Input: nums = [1,2,3,4], k = 3\n Output: false\n Explanation: Each array should be divided in subarrays of size 3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1297, - "title": "Maximum Number of Occurrences of a Substring", - "question": "class Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n \"\"\"\n Given a string s, return the maximum number of ocurrences of any substring under the following rules:\n The number of unique characters in the substring must be less than or equal to maxLetters.\n The substring size must be between minSize and maxSize inclusive.\n Example 1:\n Input: s = \"aababcaab\", maxLetters = 2, minSize = 3, maxSize = 4\n Output: 2\n Explanation: Substring \"aab\" has 2 ocurrences in the original string.\n It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).\n Example 2:\n Input: s = \"aaaa\", maxLetters = 1, minSize = 3, maxSize = 3\n Output: 2\n Explanation: Substring \"aaa\" occur 2 times in the string. It can overlap.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1298, - "title": "Maximum Candies You Can Get from Boxes", - "question": "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 \"\"\"\n You have n boxes labeled from 0 to n - 1. You are given four arrays: status, candies, keys, and containedBoxes where:\n status[i] is 1 if the ith box is open and 0 if the ith box is closed,\n candies[i] is the number of candies in the ith box,\n keys[i] is a list of the labels of the boxes you can open after opening the ith box.\n containedBoxes[i] is a list of the boxes you found inside the ith box.\n You 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.\n Return the maximum number of candies you can get following the rules above.\n Example 1:\n Input: status = [1,0,1,0], candies = [7,5,4,100], keys = [[],[],[1],[]], containedBoxes = [[1,2],[3],[],[]], initialBoxes = [0]\n Output: 16\n Explanation: You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2.\n Box 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.\n In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed.\n Total number of candies collected = 7 + 4 + 5 = 16 candy.\n Example 2:\n Input: status = [1,0,0,0,0,0], candies = [1,1,1,1,1,1], keys = [[1,2,3,4,5],[],[],[],[],[]], containedBoxes = [[1,2,3,4,5],[],[],[],[],[]], initialBoxes = [0]\n Output: 6\n Explanation: You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys.\n The total number of candies will be 6.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1304, - "title": "Find N Unique Integers Sum up to Zero", - "question": "class Solution:\n def sumZero(self, n: int) -> List[int]:\n \"\"\"\n Given an integer n, return any array containing n unique integers such that they add up to 0.\n Example 1:\n Input: n = 5\n Output: [-7,-1,1,3,4]\n Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].\n Example 2:\n Input: n = 3\n Output: [-1,0,1]\n Example 3:\n Input: n = 1\n Output: [0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1305, - "title": "All Elements in Two Binary Search Trees", - "question": "class Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n \"\"\"\n 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:\n Input: root1 = [2,1,4], root2 = [1,0,3]\n Output: [0,1,1,2,3,4]\n Example 2:\n Input: root1 = [1,null,8], root2 = [8,1]\n Output: [1,1,8,8]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1306, - "title": "Jump Game III", - "question": "class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n \"\"\"\n 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 to any index with value 0.\n Notice that you can not jump outside of the array at any time.\n Example 1:\n Input: arr = [4,2,3,0,3,1,2], start = 5\n Output: true\n Explanation: \n All possible ways to reach at index 3 with value 0 are: \n index 5 -> index 4 -> index 1 -> index 3 \n index 5 -> index 6 -> index 4 -> index 1 -> index 3 \n Example 2:\n Input: arr = [4,2,3,0,3,1,2], start = 0\n Output: true \n Explanation: \n One possible way to reach at index 3 with value 0 is: \n index 0 -> index 4 -> index 1 -> index 3\n Example 3:\n Input: arr = [3,0,2,1,2], start = 2\n Output: false\n Explanation: There is no way to reach at index 1 with value 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1307, - "title": "Verbal Arithmetic Puzzle", - "question": "class Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n \"\"\"\n Given an equation, represented by words on the left side and the result on the right side.\n You need to check if the equation is solvable under the following rules:\n Each character is decoded as one digit (0 - 9).\n No two characters can map to the same digit.\n Each words[i] and result are decoded as one number without leading zeros.\n Sum of numbers on the left side (words) will equal to the number on the right side (result).\n Return true if the equation is solvable, otherwise return false.\n Example 1:\n Input: words = [\"SEND\",\"MORE\"], result = \"MONEY\"\n Output: true\n Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8, 'Y'->'2'\n Such that: \"SEND\" + \"MORE\" = \"MONEY\" , 9567 + 1085 = 10652\n Example 2:\n Input: words = [\"SIX\",\"SEVEN\",\"SEVEN\"], result = \"TWENTY\"\n Output: true\n Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1, 'W'->'3', 'Y'->4\n Such that: \"SIX\" + \"SEVEN\" + \"SEVEN\" = \"TWENTY\" , 650 + 68782 + 68782 = 138214\n Example 3:\n Input: words = [\"LEET\",\"CODE\"], result = \"POINT\"\n Output: false\n Explanation: There is no possible mapping to satisfy the equation, so we return false.\n Note that two different characters cannot map to the same digit.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2269, - "title": "Find the K-Beauty of a Number", - "question": "class Solution:\n def divisorSubstrings(self, num: int, k: int) -> int:\n \"\"\"\n 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:\n It has a length of k.\n It is a divisor of num.\n Given integers num and k, return the k-beauty of num.\n Note:\n Leading zeros are allowed.\n 0 is not a divisor of any value.\n A substring is a contiguous sequence of characters in a string.\n Example 1:\n Input: num = 240, k = 2\n Output: 2\n Explanation: 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.\n Therefore, the k-beauty is 2.\n Example 2:\n Input: num = 430043, k = 2\n Output: 2\n Explanation: 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.\n Therefore, the k-beauty is 2.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2192, - "title": "All Ancestors of a Node in a Directed Acyclic Graph", - "question": "class Solution:\n def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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).\n You 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.\n Return a list answer, where answer[i] is the list of ancestors of the ith node, sorted in ascending order.\n A node u is an ancestor of another node v if u can reach v via a set of edges.\n Example 1:\n Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]\n Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]\n Explanation:\n The 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.\n Example 2:\n Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]\n Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]]\n Explanation:\n The 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2227, - "title": "Encrypt and Decrypt Strings", - "question": "class Encrypter:\n def __init__(self, keys: List[str], values: List[str], dictionary: List[str]):\n def encrypt(self, word1: str) -> str:\n def decrypt(self, word2: str) -> int:\n \"\"\"\n You are given a character array keys containing unique characters and a string array values containing strings of length 2. You are also given another string array dictionary that contains all permitted original strings after decryption. You should implement a data structure that can encrypt or decrypt a 0-indexed string.\n A string is encrypted with the following process:\n For each character c in the string, we find the index i satisfying keys[i] == c in keys.\n Replace c with values[i] in the string.\n Note that in case a character of the string is not present in keys, the encryption process cannot be carried out, and an empty string \"\" is returned.\n A string is decrypted with the following process:\n For each substring s of length 2 occurring at an even index in the string, we find an i such that values[i] == s. If there are multiple valid i, we choose any one of them. This means a string could have multiple possible strings it can decrypt to.\n Replace s with keys[i] in the string.\n Implement the Encrypter class:\n Encrypter(char[] keys, String[] values, String[] dictionary) Initializes the Encrypter class with keys, values, and dictionary.\n String encrypt(String word1) Encrypts word1 with the encryption process described above and returns the encrypted string.\n int decrypt(String word2) Returns the number of possible strings word2 could decrypt to that also appear in dictionary.\n Example 1:\n Input\n [\"Encrypter\", \"encrypt\", \"decrypt\"]\n [[['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]], [\"abcd\"], [\"eizfeiam\"]]\n Output\n [null, \"eizfeiam\", 2]\n Explanation\n Encrypter encrypter = new Encrypter([['a', 'b', 'c', 'd'], [\"ei\", \"zf\", \"ei\", \"am\"], [\"abcd\", \"acbd\", \"adbc\", \"badc\", \"dacb\", \"cadb\", \"cbda\", \"abad\"]);\n encrypter.encrypt(\"abcd\"); // return \"eizfeiam\". \n // 'a' maps to \"ei\", 'b' maps to \"zf\", 'c' maps to \"ei\", and 'd' maps to \"am\".\n encrypter.decrypt(\"eizfeiam\"); // return 2. \n // \"ei\" can map to 'a' or 'c', \"zf\" maps to 'b', and \"am\" maps to 'd'. \n // Thus, the possible strings after decryption are \"abad\", \"cbad\", \"abcd\", and \"cbcd\". \n // 2 of those strings, \"abad\" and \"abcd\", appear in dictionary, so the answer is 2.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1309, - "title": "Decrypt String from Alphabet to Integer Mapping", - "question": "class Solution:\n def freqAlphabets(self, s: str) -> str:\n \"\"\"\n You are given a string s formed by digits and '#'. We want to map s to English lowercase characters as follows:\n Characters ('a' to 'i') are represented by ('1' to '9') respectively.\n Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.\n Return the string formed after mapping.\n The test cases are generated so that a unique mapping will always exist.\n Example 1:\n Input: s = \"10#11#12\"\n Output: \"jkab\"\n Explanation: \"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".\n Example 2:\n Input: s = \"1326#\"\n Output: \"acz\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1310, - "title": "XOR Queries of a Subarray", - "question": "class Solution:\n def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an array arr of positive integers. You are also given the array queries where queries[i] = [lefti, righti].\n For each query i compute the XOR of elements from lefti to righti (that is, arr[lefti] XOR arr[lefti + 1] XOR ... XOR arr[righti] ).\n Return an array answer where answer[i] is the answer to the ith query.\n Example 1:\n Input: arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]\n Output: [2,7,14,8] \n Explanation: \n The binary representation of the elements in the array are:\n 1 = 0001 \n 3 = 0011 \n 4 = 0100 \n 8 = 1000 \n The XOR values for queries are:\n [0,1] = 1 xor 3 = 2 \n [1,2] = 3 xor 4 = 7 \n [0,3] = 1 xor 3 xor 4 xor 8 = 14 \n [3,3] = 8\n Example 2:\n Input: arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]]\n Output: [8,0,4,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1311, - "title": "Get Watched Videos by Your Friends", - "question": "class Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n \"\"\"\n 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.\n Level 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:\n Input: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 1\n Output: [\"B\",\"C\"] \n Explanation: \n You have id = 0 (green color in the figure) and your friends are (yellow color in the figure):\n Person with id = 1 -> watchedVideos = [\"C\"] \n Person with id = 2 -> watchedVideos = [\"B\",\"C\"] \n The frequencies of watchedVideos by your friends are: \n B -> 1 \n C -> 2\n Example 2:\n Input: watchedVideos = [[\"A\",\"B\"],[\"C\"],[\"B\",\"C\"],[\"D\"]], friends = [[1,2],[0,3],[0,3],[1,2]], id = 0, level = 2\n Output: [\"D\"]\n Explanation: \n You 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1312, - "title": "Minimum Insertion Steps to Make a String Palindrome", - "question": "class Solution:\n def minInsertions(self, s: str) -> int:\n \"\"\"\n Given a string s. In one step you can insert any character at any index of the string.\n Return the minimum number of steps to make s palindrome.\n A Palindrome String is one that reads the same backward as well as forward.\n Example 1:\n Input: s = \"zzazz\"\n Output: 0\n Explanation: The string \"zzazz\" is already palindrome we do not need any insertions.\n Example 2:\n Input: s = \"mbadm\"\n Output: 2\n Explanation: String can be \"mbdadbm\" or \"mdbabdm\".\n Example 3:\n Input: s = \"leetcode\"\n Output: 5\n Explanation: Inserting 5 characters the string becomes \"leetcodocteel\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1317, - "title": "Convert Integer to the Sum of Two No-Zero Integers", - "question": "class Solution:\n def getNoZeroIntegers(self, n: int) -> List[int]:\n \"\"\"\n No-Zero integer is a positive integer that does not contain any 0 in its decimal representation.\n Given an integer n, return a list of two integers [a, b] where:\n a and b are No-Zero integers.\n a + b = n\n The 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:\n Input: n = 2\n Output: [1,1]\n Explanation: Let a = 1 and b = 1.\n Both a and b are no-zero integers, and a + b = 2 = n.\n Example 2:\n Input: n = 11\n Output: [2,9]\n Explanation: Let a = 2 and b = 9.\n Both a and b are no-zero integers, and a + b = 9 = n.\n Note that there are other valid answers as [8, 3] that can be accepted.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1318, - "title": "Minimum Flips to Make a OR b Equal to c", - "question": "class Solution:\n def minFlips(self, a: int, b: int, c: int) -> int:\n \"\"\"\n 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).\r\n Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.\r\n Example 1:\r\n Input: a = 2, b = 6, c = 5\r\n Output: 3\r\n Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)\r\n Example 2:\r\n Input: a = 4, b = 2, c = 7\r\n Output: 1\r\n Example 3:\r\n Input: a = 1, b = 2, c = 3\r\n Output: 0\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1319, - "title": "Number of Operations to Make Network Connected", - "question": "class Solution:\n def makeConnected(self, n: int, connections: List[List[int]]) -> int:\n \"\"\"\n 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.\n You 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.\n Return 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:\n Input: n = 4, connections = [[0,1],[0,2],[1,2]]\n Output: 1\n Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.\n Example 2:\n Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]\n Output: 2\n Example 3:\n Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]\n Output: -1\n Explanation: There are not enough cables.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1320, - "title": "Minimum Distance to Type a Word Using Two Fingers", - "question": "class Solution:\n def minimumDistance(self, word: str) -> int:\n \"\"\"\n You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.\n For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).\n Given the string word, return the minimum total distance to type such string using only two fingers.\n The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.\n Note that the initial positions of your two fingers are considered free so 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:\n Input: word = \"CAKE\"\n Output: 3\n Explanation: Using two fingers, one optimal way to type \"CAKE\" is: \n Finger 1 on letter 'C' -> cost = 0 \n Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2 \n Finger 2 on letter 'K' -> cost = 0 \n Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1 \n Total distance = 3\n Example 2:\n Input: word = \"HAPPY\"\n Output: 6\n Explanation: Using two fingers, one optimal way to type \"HAPPY\" is:\n Finger 1 on letter 'H' -> cost = 0\n Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2\n Finger 2 on letter 'P' -> cost = 0\n Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0\n Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4\n Total distance = 6\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1342, - "title": "Number of Steps to Reduce a Number to Zero", - "question": "class Solution:\n def numberOfSteps(self, num: int) -> int:\n \"\"\"\n Given an integer num, return the number of steps to reduce it to zero.\n In 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:\n Input: num = 14\n Output: 6\n Explanation: \n Step 1) 14 is even; divide by 2 and obtain 7. \n Step 2) 7 is odd; subtract 1 and obtain 6.\n Step 3) 6 is even; divide by 2 and obtain 3. \n Step 4) 3 is odd; subtract 1 and obtain 2. \n Step 5) 2 is even; divide by 2 and obtain 1. \n Step 6) 1 is odd; subtract 1 and obtain 0.\n Example 2:\n Input: num = 8\n Output: 4\n Explanation: \n Step 1) 8 is even; divide by 2 and obtain 4. \n Step 2) 4 is even; divide by 2 and obtain 2. \n Step 3) 2 is even; divide by 2 and obtain 1. \n Step 4) 1 is odd; subtract 1 and obtain 0.\n Example 3:\n Input: num = 123\n Output: 12\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1343, - "title": "Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold", - "question": "class Solution:\n def numOfSubarrays(self, arr: List[int], k: int, threshold: int) -> int:\n \"\"\"\n 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:\n Input: arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4\n Output: 3\n Explanation: Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).\n Example 2:\n Input: arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5\n Output: 6\n Explanation: The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1344, - "title": "Angle Between Hands of a Clock", - "question": "class Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n \"\"\"\n Given two numbers, hour and minutes, return the smaller angle (in degrees) formed between the hour and the minute hand.\n Answers within 10-5 of the actual value will be accepted as correct.\n Example 1:\n Input: hour = 12, minutes = 30\n Output: 165\n Example 2:\n Input: hour = 3, minutes = 30\n Output: 75\n Example 3:\n Input: hour = 3, minutes = 15\n Output: 7.5\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1345, - "title": "Jump Game IV", - "question": "class Solution:\n def minJumps(self, arr: List[int]) -> int:\n \"\"\"\n Given an array of integers arr, you are initially positioned at the first index of the array.\n In one step you can jump from index i to index:\n i + 1 where: i + 1 < arr.length.\n i - 1 where: i - 1 >= 0.\n j where: arr[i] == arr[j] and i != j.\n Return the minimum number of steps to reach the last index of the array.\n Notice that you can not jump outside of the array at any time.\n Example 1:\n Input: arr = [100,-23,-23,404,100,23,23,23,3,404]\n Output: 3\n Explanation: You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.\n Example 2:\n Input: arr = [7]\n Output: 0\n Explanation: Start index is the last index. You do not need to jump.\n Example 3:\n Input: arr = [7,6,9,6,9,6,9,7]\n Output: 1\n Explanation: You can jump directly from index 0 to index 7 which is last index of the array.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1323, - "title": "Maximum 69 Number", - "question": "class Solution:\n def maximum69Number (self, num: int) -> int:\n \"\"\"\n You are given a positive integer num consisting only of digits 6 and 9.\n Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).\n Example 1:\n Input: num = 9669\n Output: 9969\n Explanation: \n Changing the first digit results in 6669.\n Changing the second digit results in 9969.\n Changing the third digit results in 9699.\n Changing the fourth digit results in 9666.\n The maximum number is 9969.\n Example 2:\n Input: num = 9996\n Output: 9999\n Explanation: Changing the last digit 6 to 9 results in the maximum number.\n Example 3:\n Input: num = 9999\n Output: 9999\n Explanation: It is better not to apply any change.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1324, - "title": "Print Words Vertically", - "question": "class Solution:\n def printVertically(self, s: str) -> List[str]:\n \"\"\"\n Given a string s. Return all the words vertically in the same order in which they appear in s.\r\n Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed).\r\n Each word would be put on only one column and that in one column there will be only one word.\r\n Example 1:\r\n Input: s = \"HOW ARE YOU\"\r\n Output: [\"HAY\",\"ORO\",\"WEU\"]\r\n Explanation: Each word is printed vertically. \r\n \"HAY\"\r\n \"ORO\"\r\n \"WEU\"\r\n Example 2:\r\n Input: s = \"TO BE OR NOT TO BE\"\r\n Output: [\"TBONTB\",\"OEROOE\",\" T\"]\r\n Explanation: Trailing spaces is not allowed. \r\n \"TBONTB\"\r\n \"OEROOE\"\r\n \" T\"\r\n Example 3:\r\n Input: s = \"CONTEST IS COMING\"\r\n Output: [\"CIC\",\"OSO\",\"N M\",\"T I\",\"E N\",\"S G\",\"T\"]\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1325, - "title": "Delete Leaves With a Given Value", - "question": "class Solution:\n def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]:\n \"\"\"\n Given a binary tree root and an integer target, delete all the leaf nodes with value target.\n Note 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:\n Input: root = [1,2,3,2,null,2,4], target = 2\n Output: [1,null,3,null,4]\n Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). \n After removing, new nodes become leaf nodes with value (target = 2) (Picture in center).\n Example 2:\n Input: root = [1,3,3,3,2], target = 3\n Output: [1,3,null,null,2]\n Example 3:\n Input: root = [1,2,null,2,null,2], target = 2\n Output: [1]\n Explanation: Leaf nodes in green with value (target = 2) are removed at each step.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1326, - "title": "Minimum Number of Taps to Open to Water a Garden", - "question": "class Solution:\n def minTaps(self, n: int, ranges: List[int]) -> int:\n \"\"\"\n There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).\n There are n + 1 taps located at points [0, 1, ..., n] in the garden.\n Given an integer n and an integer array ranges of length n + 1 where ranges[i] (0-indexed) means the i-th tap can water the area [i - ranges[i], i + ranges[i]] if it was open.\n Return 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:\n Input: n = 5, ranges = [3,4,1,1,0,0]\n Output: 1\n Explanation: The tap at point 0 can cover the interval [-3,3]\n The tap at point 1 can cover the interval [-3,5]\n The tap at point 2 can cover the interval [1,3]\n The tap at point 3 can cover the interval [2,4]\n The tap at point 4 can cover the interval [4,4]\n The tap at point 5 can cover the interval [5,5]\n Opening Only the second tap will water the whole garden [0,5]\n Example 2:\n Input: n = 3, ranges = [0,0,0,0]\n Output: -1\n Explanation: Even if you activate all the four taps you cannot water the whole garden.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1332, - "title": "Remove Palindromic Subsequences", - "question": "class Solution:\n def removePalindromeSub(self, s: str) -> int:\n \"\"\"\n 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.\n Return the minimum number of steps to make the given string empty.\n A 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.\n A string is called palindrome if is one that reads the same backward as well as forward.\n Example 1:\n Input: s = \"ababa\"\n Output: 1\n Explanation: s is already a palindrome, so its entirety can be removed in a single step.\n Example 2:\n Input: s = \"abb\"\n Output: 2\n Explanation: \"abb\" -> \"bb\" -> \"\". \n Remove palindromic subsequence \"a\" then \"bb\".\n Example 3:\n Input: s = \"baabb\"\n Output: 2\n Explanation: \"baabb\" -> \"b\" -> \"\". \n Remove palindromic subsequence \"baab\" then \"b\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1333, - "title": "Filter Restaurants by Vegan-Friendly, Price and Distance", - "question": "class Solution:\n def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:\n \"\"\"\n Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.\n The 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.\n Return 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:\n Input: 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\n Output: [3,1,5] \n Explanation: \n The restaurants are:\n Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10]\n Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5]\n Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4]\n Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3]\n Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] \n After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). \n Example 2:\n Input: 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\n Output: [4,3,2,1,5]\n Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered.\n Example 3:\n Input: 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\n Output: [4,5]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1334, - "title": "Find the City With the Smallest Number of Neighbors at a Threshold Distance", - "question": "class Solution:\n def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:\n \"\"\"\n 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.\n Return 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.\n Notice 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:\n Input: n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4\n Output: 3\n Explanation: The figure above describes the graph. \n The neighboring cities at a distanceThreshold = 4 for each city are:\n City 0 -> [City 1, City 2] \n City 1 -> [City 0, City 2, City 3] \n City 2 -> [City 0, City 1, City 3] \n City 3 -> [City 1, City 2] \n Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.\n Example 2:\n Input: n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2\n Output: 0\n Explanation: The figure above describes the graph. \n The neighboring cities at a distanceThreshold = 2 for each city are:\n City 0 -> [City 1] \n City 1 -> [City 0, City 4] \n City 2 -> [City 3, City 4] \n City 3 -> [City 2, City 4]\n City 4 -> [City 1, City 2, City 3] \n The city 0 has 1 neighboring city at a distanceThreshold = 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1335, - "title": "Minimum Difficulty of a Job Schedule", - "question": "class Solution:\n def minDifficulty(self, jobDifficulty: List[int], d: int) -> int:\n \"\"\"\n 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).\n You have to finish at least one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the d days. The difficulty of a day is the maximum difficulty of a job done on that day.\n You are given an integer array jobDifficulty and an integer d. The difficulty of the ith job is jobDifficulty[i].\n Return the minimum difficulty of a job schedule. If you cannot find a schedule for the jobs return -1.\n Example 1:\n Input: jobDifficulty = [6,5,4,3,2,1], d = 2\n Output: 7\n Explanation: First day you can finish the first 5 jobs, total difficulty = 6.\n Second day you can finish the last job, total difficulty = 1.\n The difficulty of the schedule = 6 + 1 = 7 \n Example 2:\n Input: jobDifficulty = [9,9,9], d = 4\n Output: -1\n Explanation: If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs.\n Example 3:\n Input: jobDifficulty = [1,1,1], d = 3\n Output: 3\n Explanation: The schedule is one job per day. total difficulty will be 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1356, - "title": "Sort Integers by The Number of 1 Bits", - "question": "class Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n \"\"\"\n 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.\n Return the array after sorting it.\n Example 1:\n Input: arr = [0,1,2,3,4,5,6,7,8]\n Output: [0,1,2,4,8,3,5,6,7]\n Explantion: [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.\n The sorted array by bits is [0,1,2,4,8,3,5,6,7]\n Example 2:\n Input: arr = [1024,512,256,128,64,32,16,8,4,2,1]\n Output: [1,2,4,8,16,32,64,128,256,512,1024]\n Explantion: All integers have 1 bit in the binary representation, you should just sort them in ascending order.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1357, - "title": "Apply Discount Every n Orders", - "question": "class Cashier:\n def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):\n def getBill(self, product: List[int], amount: List[int]) -> float:\n \"\"\"\n There is a supermarket that is frequented by many customers. The products sold at the supermarket are represented as two parallel integer arrays products and prices, where the ith product has an ID of products[i] and a price of prices[i].\n When a customer is paying, their bill is represented as two parallel integer arrays product and amount, where the jth product they purchased has an ID of product[j], and amount[j] is how much of the product they bought. Their subtotal is calculated as the sum of each amount[j] * (price of the jth product).\n The supermarket decided to have a sale. Every nth customer paying for their groceries will be given a percentage discount. The discount amount is given by discount, where they will be given discount percent off their subtotal. More formally, if their subtotal is bill, then they would actually pay bill * ((100 - discount) / 100).\n Implement the Cashier class:\n Cashier(int n, int discount, int[] products, int[] prices) Initializes the object with n, the discount, and the products and their prices.\n double getBill(int[] product, int[] amount) Returns the final total of the bill with the discount applied (if any). Answers within 10-5 of the actual value will be accepted.\n Example 1:\n Input\n [\"Cashier\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\",\"getBill\"]\n [[3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]],[[1,2],[1,2]],[[3,7],[10,10]],[[1,2,3,4,5,6,7],[1,1,1,1,1,1,1]],[[4],[10]],[[7,3],[10,10]],[[7,5,3,1,6,4,2],[10,10,10,9,9,9,7]],[[2,3,5],[5,3,2]]]\n Output\n [null,500.0,4000.0,800.0,4000.0,4000.0,7350.0,2500.0]\n Explanation\n Cashier cashier = new Cashier(3,50,[1,2,3,4,5,6,7],[100,200,300,400,300,200,100]);\n cashier.getBill([1,2],[1,2]); // return 500.0. 1st customer, no discount.\n // bill = 1 * 100 + 2 * 200 = 500.\n cashier.getBill([3,7],[10,10]); // return 4000.0. 2nd customer, no discount.\n // bill = 10 * 300 + 10 * 100 = 4000.\n cashier.getBill([1,2,3,4,5,6,7],[1,1,1,1,1,1,1]); // return 800.0. 3rd customer, 50% discount.\n // Original bill = 1600\n // Actual bill = 1600 * ((100 - 50) / 100) = 800.\n cashier.getBill([4],[10]); // return 4000.0. 4th customer, no discount.\n cashier.getBill([7,3],[10,10]); // return 4000.0. 5th customer, no discount.\n cashier.getBill([7,5,3,1,6,4,2],[10,10,10,9,9,9,7]); // return 7350.0. 6th customer, 50% discount.\n // Original bill = 14700, but with\n // Actual bill = 14700 * ((100 - 50) / 100) = 7350.\n cashier.getBill([2,3,5],[5,3,2]); // return 2500.0. 6th customer, no discount.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1358, - "title": "Number of Substrings Containing All Three Characters", - "question": "class Solution:\n def numberOfSubstrings(self, s: str) -> int:\n \"\"\"\n Given a string s consisting only of characters a, b and c.\n Return the number of substrings containing at least one occurrence of all these characters a, b and c.\n Example 1:\n Input: s = \"abcabc\"\n Output: 10\n Explanation: The substrings containing at least one occurrence of the characters a, b and c are \"abc\", \"abca\", \"abcab\", \"abcabc\", \"bca\", \"bcab\", \"bcabc\", \"cab\", \"cabc\" and \"abc\" (again). \n Example 2:\n Input: s = \"aaacb\"\n Output: 3\n Explanation: The substrings containing at least one occurrence of the characters a, b and c are \"aaacb\", \"aacb\" and \"acb\". \n Example 3:\n Input: s = \"abc\"\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1359, - "title": "Count All Valid Pickup and Delivery Options", - "question": "class Solution:\n def countOrders(self, n: int) -> int:\n \"\"\"\n Given n orders, each order consist in pickup and delivery services. \n Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i). \n Since the answer may be too large, return it modulo 10^9 + 7.\n Example 1:\n Input: n = 1\n Output: 1\n Explanation: Unique order (P1, D1), Delivery 1 always is after of Pickup 1.\n Example 2:\n Input: n = 2\n Output: 6\n Explanation: All possible orders: \n (P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).\n This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.\n Example 3:\n Input: n = 3\n Output: 90\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1337, - "title": "The K Weakest Rows in a Matrix", - "question": "class Solution:\n def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:\n \"\"\"\n 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.\n A row i is weaker than a row j if one of the following is true:\n The number of soldiers in row i is less than the number of soldiers in row j.\n Both rows have the same number of soldiers and i < j.\n Return the indices of the k weakest rows in the matrix ordered from weakest to strongest.\n Example 1:\n Input: 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]], \n k = 3\n Output: [2,0,3]\n Explanation: \n The 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 \n The rows ordered from weakest to strongest are [2,0,3,1,4].\n Example 2:\n Input: mat = \n [[1,0,0,0],\n [1,1,1,1],\n [1,0,0,0],\n [1,0,0,0]], \n k = 2\n Output: [0,2]\n Explanation: \n The number of soldiers in each row is: \n - Row 0: 1 \n - Row 1: 4 \n - Row 2: 1 \n - Row 3: 1 \n The rows ordered from weakest to strongest are [0,2,3,1].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1338, - "title": "Reduce Array Size to The Half", - "question": "class Solution:\n def minSetSize(self, arr: List[int]) -> int:\n \"\"\"\n 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.\n Return the minimum size of the set so that at least half of the integers of the array are removed.\n Example 1:\n Input: arr = [3,3,3,3,5,5,5,2,2,7]\n Output: 2\n Explanation: 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).\n Possible sets of size 2 are {3,5},{3,2},{5,2}.\n Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.\n Example 2:\n Input: arr = [7,7,7,7,7,7]\n Output: 1\n Explanation: The only possible set you can choose is {7}. This will make the new array empty.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1339, - "title": "Maximum Product of Splitted Binary Tree", - "question": "class Solution:\n def maxProduct(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n Return the maximum product of the sums of the two subtrees. Since the answer may be too large, return it modulo 109 + 7.\n Note that you need to maximize the answer before taking the mod and not after taking it.\n Example 1:\n Input: root = [1,2,3,4,5,6]\n Output: 110\n Explanation: Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)\n Example 2:\n Input: root = [1,null,2,3,4,null,null,5,6]\n Output: 90\n Explanation: Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1340, - "title": "Jump Game V", - "question": "class Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n \"\"\"\n Given an array of integers arr and an integer d. In one step you can jump from index i to index:\n i + x where: i + x < arr.length and 0 < x <= d.\n i - x where: i - x >= 0 and 0 < x <= d.\n In addition, you can only jump from index i to index j if arr[i] > arr[j] and arr[i] > arr[k] for all indices k between i and j (More formally min(i, j) < k < max(i, j)).\n You can choose any index of the array and start jumping. Return the maximum number of indices you can visit.\n Notice that you can not jump outside of the array at any time.\n Example 1:\n Input: arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2\n Output: 4\n Explanation: You can start at index 10. You can jump 10 --> 8 --> 6 --> 7 as shown.\n Note that if you start at index 6 you can only jump to index 7. You cannot jump to index 5 because 13 > 9. You cannot jump to index 4 because index 5 is between index 4 and 6 and 13 > 9.\n Similarly You cannot jump from index 3 to index 2 or index 1.\n Example 2:\n Input: arr = [3,3,3,3,3], d = 3\n Output: 1\n Explanation: You can start at any index. You always cannot jump to any index.\n Example 3:\n Input: arr = [7,6,5,4,3,2,1], d = 1\n Output: 7\n Explanation: Start at index 0. You can visit all the indicies. \n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1346, - "title": "Check If N and Its Double Exist", - "question": "class Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n \"\"\"\n Given an array arr of integers, check if there exist two indices i and j such that :\n i != j\n 0 <= i, j < arr.length\n arr[i] == 2 * arr[j]\n Example 1:\n Input: arr = [10,2,5,3]\n Output: true\n Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]\n Example 2:\n Input: arr = [3,1,7,11]\n Output: false\n Explanation: There is no i and j that satisfy the conditions.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1347, - "title": "Minimum Number of Steps to Make Two Strings Anagram", - "question": "class Solution:\n def minSteps(self, s: str, t: str) -> int:\n \"\"\"\n 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.\n Return the minimum number of steps to make t an anagram of s.\n An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.\n Example 1:\n Input: s = \"bab\", t = \"aba\"\n Output: 1\n Explanation: Replace the first 'a' in t with b, t = \"bba\" which is anagram of s.\n Example 2:\n Input: s = \"leetcode\", t = \"practice\"\n Output: 5\n Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.\n Example 3:\n Input: s = \"anagram\", t = \"mangaar\"\n Output: 0\n Explanation: \"anagram\" and \"mangaar\" are anagrams. \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1348, - "title": "Tweet Counts Per Frequency", - "question": "class TweetCounts:\n def __init__(self):\n def recordTweet(self, tweetName: str, time: int) -> None:\n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:\n \"\"\"\n A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller time chunks based on a certain frequency (every minute, hour, or day).\n For example, the period [10, 10000] (in seconds) would be partitioned into the following time chunks with these frequencies:\n Every minute (60-second chunks): [10,69], [70,129], [130,189], ..., [9970,10000]\n Every hour (3600-second chunks): [10,3609], [3610,7209], [7210,10000]\n Every day (86400-second chunks): [10,10000]\n Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (10000 in the above example).\n Design and implement an API to help the company with their analysis.\n Implement the TweetCounts class:\n TweetCounts() Initializes the TweetCounts object.\n void recordTweet(String tweetName, int time) Stores the tweetName at the recorded time (in seconds).\n List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime) Returns a list of integers representing the number of tweets with tweetName in each time chunk for the given period of time [startTime, endTime] (in seconds) and frequency freq.\n freq is one of \"minute\", \"hour\", or \"day\" representing a frequency of every minute, hour, or day respectively.\n Example:\n Input\n [\"TweetCounts\",\"recordTweet\",\"recordTweet\",\"recordTweet\",\"getTweetCountsPerFrequency\",\"getTweetCountsPerFrequency\",\"recordTweet\",\"getTweetCountsPerFrequency\"]\n [[],[\"tweet3\",0],[\"tweet3\",60],[\"tweet3\",10],[\"minute\",\"tweet3\",0,59],[\"minute\",\"tweet3\",0,60],[\"tweet3\",120],[\"hour\",\"tweet3\",0,210]]\n Output\n [null,null,null,null,[2],[2,1],null,[4]]\n Explanation\n TweetCounts tweetCounts = new TweetCounts();\n tweetCounts.recordTweet(\"tweet3\", 0); // New tweet \"tweet3\" at time 0\n tweetCounts.recordTweet(\"tweet3\", 60); // New tweet \"tweet3\" at time 60\n tweetCounts.recordTweet(\"tweet3\", 10); // New tweet \"tweet3\" at time 10\n tweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 59); // return [2]; chunk [0,59] had 2 tweets\n tweetCounts.getTweetCountsPerFrequency(\"minute\", \"tweet3\", 0, 60); // return [2,1]; chunk [0,59] had 2 tweets, chunk [60,60] had 1 tweet\n tweetCounts.recordTweet(\"tweet3\", 120); // New tweet \"tweet3\" at time 120\n tweetCounts.getTweetCountsPerFrequency(\"hour\", \"tweet3\", 0, 210); // return [4]; chunk [0,210] had 4 tweets\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1349, - "title": "Maximum Students Taking Exam", - "question": "class Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n \"\"\"\n Given a m * n matrix seats that represent seats distributions in a classroom. If a seat is broken, it is denoted by '#' character otherwise it is denoted by a '.' character.\n Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the maximum number of students that can take the exam together without any cheating being possible..\n Students must be placed in seats in good condition.\n Example 1:\n Input: seats = [[\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\".\",\"#\",\"#\",\"#\",\"#\",\".\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"]]\n Output: 4\n Explanation: Teacher can place 4 students in available seats so they don't cheat on the exam. \n Example 2:\n Input: seats = [[\".\",\"#\"],\n [\"#\",\"#\"],\n [\"#\",\".\"],\n [\"#\",\"#\"],\n [\".\",\"#\"]]\n Output: 3\n Explanation: Place all students in available seats. \n Example 3:\n Input: seats = [[\"#\",\".\",\".\",\".\",\"#\"],\n [\".\",\"#\",\".\",\"#\",\".\"],\n [\".\",\".\",\"#\",\".\",\".\"],\n [\".\",\"#\",\".\",\"#\",\".\"],\n [\"#\",\".\",\".\",\".\",\"#\"]]\n Output: 10\n Explanation: Place students in available seats in column 1, 3 and 5.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1370, - "title": "Increasing Decreasing String", - "question": "class Solution:\n def sortString(self, s: str) -> str:\n \"\"\"\n You are given a string s. Reorder the string using the following algorithm:\n Pick the smallest character from s and append it to the result.\n Pick the smallest character from s which is greater than the last appended character to the result and append it.\n Repeat step 2 until you cannot pick more characters.\n Pick the largest character from s and append it to the result.\n Pick the largest character from s which is smaller than the last appended character to the result and append it.\n Repeat step 5 until you cannot pick more characters.\n Repeat the steps from 1 to 6 until you pick all characters from s.\n In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.\n Return the result string after sorting s with this algorithm.\n Example 1:\n Input: s = \"aaaabbbbcccc\"\n Output: \"abccbaabccba\"\n Explanation: After steps 1, 2 and 3 of the first iteration, result = \"abc\"\n After steps 4, 5 and 6 of the first iteration, result = \"abccba\"\n First iteration is done. Now s = \"aabbcc\" and we go back to step 1\n After steps 1, 2 and 3 of the second iteration, result = \"abccbaabc\"\n After steps 4, 5 and 6 of the second iteration, result = \"abccbaabccba\"\n Example 2:\n Input: s = \"rat\"\n Output: \"art\"\n Explanation: The word \"rat\" becomes \"art\" after re-ordering it with the mentioned algorithm.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1371, - "title": "Find the Longest Substring Containing Vowels in Even Counts", - "question": "class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n \"\"\"\n 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:\n Input: s = \"eleetminicoworoep\"\n Output: 13\n Explanation: The longest substring is \"leetminicowor\" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.\n Example 2:\n Input: s = \"leetcodeisgreat\"\n Output: 5\n Explanation: The longest substring is \"leetc\" which contains two e's.\n Example 3:\n Input: s = \"bcbcbc\"\n Output: 6\n Explanation: In this case, the given string \"bcbcbc\" is the longest because all vowels: a, e, i, o and u appear zero times.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1372, - "title": "Longest ZigZag Path in a Binary Tree", - "question": "class Solution:\n def longestZigZag(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n You are given the root of a binary tree.\n A ZigZag path for a binary tree is defined as follow:\n Choose any node in the binary tree and a direction (right or left).\n If the current direction is right, move to the right child of the current node; otherwise, move to the left child.\n Change the direction from right to left or from left to right.\n Repeat the second and third steps until you can't move in the tree.\n Zigzag length is defined as the number of nodes visited - 1. (A single node has a length of 0).\n Return the longest ZigZag path contained in that tree.\n Example 1:\n Input: root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]\n Output: 3\n Explanation: Longest ZigZag path in blue nodes (right -> left -> right).\n Example 2:\n Input: root = [1,1,1,null,1,null,null,1,1,null,1]\n Output: 4\n Explanation: Longest ZigZag path in blue nodes (left -> right -> left -> right).\n Example 3:\n Input: root = [1]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1373, - "title": "Maximum Sum BST in Binary Tree", - "question": "class Solution:\n def maxSumBST(self, root: Optional[TreeNode]) -> int:\n \"\"\"\n Given a binary tree root, return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).\n Assume a BST is defined as follows:\n The left subtree of a node contains only nodes with keys less than the node's key.\n The right subtree of a node contains only nodes with keys greater than the node's key.\n Both the left and right subtrees must also be binary search trees.\n Example 1:\n Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\n Output: 20\n Explanation: Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.\n Example 2:\n Input: root = [4,3,null,1,2]\n Output: 2\n Explanation: Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.\n Example 3:\n Input: root = [-4,-2,-5]\n Output: 0\n Explanation: All values are negatives. Return an empty BST.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1351, - "title": "Count Negative Numbers in a Sorted Matrix", - "question": "class Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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:\n Input: grid = [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]]\n Output: 8\n Explanation: There are 8 negatives number in the matrix.\n Example 2:\n Input: grid = [[3,2],[1,0]]\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1352, - "title": "Product of the Last K Numbers", - "question": "class ProductOfNumbers:\n def __init__(self):\n def add(self, num: int) -> None:\n def getProduct(self, k: int) -> int:\n \"\"\"\n Design an algorithm that accepts a stream of integers and retrieves the product of the last k integers of the stream.\n Implement the ProductOfNumbers class:\n ProductOfNumbers() Initializes the object with an empty stream.\n void add(int num) Appends the integer num to the stream.\n int getProduct(int k) Returns the product of the last k numbers in the current list. You can assume that always the current list has at least k numbers.\n The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing.\n Example:\n Input\n [\"ProductOfNumbers\",\"add\",\"add\",\"add\",\"add\",\"add\",\"getProduct\",\"getProduct\",\"getProduct\",\"add\",\"getProduct\"]\n [[],[3],[0],[2],[5],[4],[2],[3],[4],[8],[2]]\n Output\n [null,null,null,null,null,null,20,40,0,null,32]\n Explanation\n ProductOfNumbers productOfNumbers = new ProductOfNumbers();\n productOfNumbers.add(3); // [3]\n productOfNumbers.add(0); // [3,0]\n productOfNumbers.add(2); // [3,0,2]\n productOfNumbers.add(5); // [3,0,2,5]\n productOfNumbers.add(4); // [3,0,2,5,4]\n productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 * 4 = 20\n productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 * 5 * 4 = 40\n productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 * 2 * 5 * 4 = 0\n productOfNumbers.add(8); // [3,0,2,5,4,8]\n productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 * 8 = 32 \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1353, - "title": "Maximum Number of Events That Can Be Attended", - "question": "class Solution:\n def maxEvents(self, events: List[List[int]]) -> int:\n \"\"\"\n You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.\n You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.\n Return the maximum number of events you can attend.\n Example 1:\n Input: events = [[1,2],[2,3],[3,4]]\n Output: 3\n Explanation: You can attend all the three events.\n One way to attend them all is as shown.\n Attend the first event on day 1.\n Attend the second event on day 2.\n Attend the third event on day 3.\n Example 2:\n Input: events= [[1,2],[2,3],[3,4],[1,2]]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1354, - "title": "Construct Target Array With Multiple Sums", - "question": "class Solution:\n def isPossible(self, target: List[int]) -> bool:\n \"\"\"\n 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 :\n let x be the sum of all elements currently in your array.\n choose index i, such that 0 <= i < n and set the value of arr at index i to x.\n You may repeat this procedure as many times as needed.\n Return true if it is possible to construct the target array from arr, otherwise, return false.\n Example 1:\n Input: target = [9,3,5]\n Output: true\n Explanation: Start with arr = [1, 1, 1] \n [1, 1, 1], sum = 3 choose index 1\n [1, 3, 1], sum = 5 choose index 2\n [1, 3, 5], sum = 9 choose index 0\n [9, 3, 5] Done\n Example 2:\n Input: target = [1,1,1,2]\n Output: false\n Explanation: Impossible to create target array from [1,1,1,1].\n Example 3:\n Input: target = [8,5]\n Output: true\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1365, - "title": "How Many Numbers Are Smaller Than the Current Number", - "question": "class Solution:\n def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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].\n Return the answer in an array.\n Example 1:\n Input: nums = [8,1,2,2,3]\n Output: [4,0,1,1,3]\n Explanation: \n For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3). \n For nums[1]=1 does not exist any smaller number than it.\n For nums[2]=2 there exist one smaller number than it (1). \n For nums[3]=2 there exist one smaller number than it (1). \n For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).\n Example 2:\n Input: nums = [6,5,4,8]\n Output: [2,1,0,3]\n Example 3:\n Input: nums = [7,7,7,7]\n Output: [0,0,0,0]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1366, - "title": "Rank Teams by Votes", - "question": "class Solution:\n def rankTeams(self, votes: List[str]) -> str:\n \"\"\"\n In a special ranking system, each voter gives a rank from highest to lowest to all teams participating in the competition.\n The 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.\n You 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.\n Return a string of all teams sorted by the ranking system.\n Example 1:\n Input: votes = [\"ABC\",\"ACB\",\"ABC\",\"ACB\",\"ACB\"]\n Output: \"ACB\"\n Explanation: \n Team A was ranked first place by 5 voters. No other team was voted as first place, so team A is the first team.\n Team B was ranked second by 2 voters and ranked third by 3 voters.\n Team C was ranked second by 3 voters and ranked third by 2 voters.\n As most of the voters ranked C second, team C is the second team, and team B is the third.\n Example 2:\n Input: votes = [\"WXYZ\",\"XYZW\"]\n Output: \"XWYZ\"\n Explanation:\n X is the winner due to the tie-breaking rule. X has the same votes as W for the first position, but X has one vote in the second position, while W does not have any votes in the second position. \n Example 3:\n Input: votes = [\"ZMNAGUEDSJYLBOPHRQICWFXTVK\"]\n Output: \"ZMNAGUEDSJYLBOPHRQICWFXTVK\"\n Explanation: Only one voter, so their votes are used for the ranking.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1367, - "title": "Linked List in Binary Tree", - "question": "class Solution:\n def isSubPath(self, head: Optional[ListNode], root: Optional[TreeNode]) -> bool:\n \"\"\"\n Given a binary tree root and a linked list with head as the first node. \n Return 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.\n In this context downward path means a path that starts at some node and goes downwards.\n Example 1:\n Input: head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n Output: true\n Explanation: Nodes in blue form a subpath in the binary Tree. \n Example 2:\n Input: head = [1,4,2,6], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n Output: true\n Example 3:\n Input: head = [1,4,2,6,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]\n Output: false\n Explanation: There is no path in the binary tree that contains all the elements of the linked list from head.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1368, - "title": "Minimum Cost to Make at Least One Valid Path in a Grid", - "question": "class Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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:\n 1 which means go to the cell to the right. (i.e go from grid[i][j] to grid[i][j + 1])\n 2 which means go to the cell to the left. (i.e go from grid[i][j] to grid[i][j - 1])\n 3 which means go to the lower cell. (i.e go from grid[i][j] to grid[i + 1][j])\n 4 which means go to the upper cell. (i.e go from grid[i][j] to grid[i - 1][j])\n Notice that there could be some signs on the cells of the grid that point outside the grid.\n You 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.\n You can modify the sign on a cell with cost = 1. You can modify the sign on a cell one time only.\n Return the minimum cost to make the grid have at least one valid path.\n Example 1:\n Input: grid = [[1,1,1,1],[2,2,2,2],[1,1,1,1],[2,2,2,2]]\n Output: 3\n Explanation: You will start at point (0, 0).\n The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3)\n The total cost = 3.\n Example 2:\n Input: grid = [[1,1,3],[3,2,2],[1,1,4]]\n Output: 0\n Explanation: You can follow the path from (0, 0) to (2, 2).\n Example 3:\n Input: grid = [[1,2],[4,3]]\n Output: 1\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1385, - "title": "Find the Distance Value Between Two Arrays", - "question": "class Solution:\n def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -> int:\n \"\"\"\n Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays.\n The 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:\n Input: arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2\n Output: 2\n Explanation: \n For 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 \n For 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\n For arr1[2]=8 we have:\n |8-10|=2 <= d=2\n |8-9|=1 <= d=2\n |8-1|=7 > d=2\n |8-8|=0 <= d=2\n Example 2:\n Input: arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3\n Output: 2\n Example 3:\n Input: arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1386, - "title": "Cinema Seat Allocation", - "question": "class Solution:\n def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:\n \"\"\"\n 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.\n Given 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.\n Return 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:\n Input: n = 3, reservedSeats = [[1,2],[1,3],[1,8],[2,6],[3,1],[3,10]]\n Output: 4\n Explanation: The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.\n Example 2:\n Input: n = 2, reservedSeats = [[2,1],[1,8],[2,6]]\n Output: 2\n Example 3:\n Input: n = 4, reservedSeats = [[4,3],[1,4],[4,6],[1,7]]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1387, - "title": "Sort Integers by The Power Value", - "question": "class Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n \"\"\"\n The power of an integer x is defined as the number of steps needed to transform x into 1 using the following steps:\n if x is even then x = x / 2\n if x is odd then x = 3 * x + 1\n For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1).\n Given 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.\n Return the kth integer in the range [lo, hi] sorted by the power value.\n Notice 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:\n Input: lo = 12, hi = 15, k = 2\n Output: 13\n Explanation: The power of 12 is 9 (12 --> 6 --> 3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1)\n The power of 13 is 9\n The power of 14 is 17\n The power of 15 is 17\n The interval sorted by the power value [12,13,14,15]. For k = 2 answer is the second element which is 13.\n Notice that 12 and 13 have the same power value and we sorted them in ascending order. Same for 14 and 15.\n Example 2:\n Input: lo = 7, hi = 11, k = 4\n Output: 7\n Explanation: The power array corresponding to the interval [7, 8, 9, 10, 11] is [16, 3, 19, 6, 14].\n The interval sorted by power is [8, 10, 11, 7, 9].\n The fourth number in the sorted array is 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1388, - "title": "Pizza With 3n Slices", - "question": "class Solution:\n def maxSizeSlices(self, slices: List[int]) -> int:\n \"\"\"\n There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:\n You will pick any pizza slice.\n Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.\n Your friend Bob will pick the next slice in the clockwise direction of your pick.\n Repeat until there are no more slices of pizzas.\n Given 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:\n Input: slices = [1,2,3,4,5,6]\n Output: 10\n Explanation: Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.\n Example 2:\n Input: slices = [8,9,8,6,1,1]\n Output: 16\n Explanation: Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1374, - "title": "Generate a String With Characters That Have Odd Counts", - "question": "class Solution:\n def generateTheString(self, n: int) -> str:\n \"\"\"\n Given an integer n, return a string with n characters such that each character in such string occurs an odd number of times.\n The returned string must contain only lowercase English letters. If there are multiples valid strings, return any of them. \n Example 1:\n Input: n = 4\n Output: \"pppz\"\n Explanation: \"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\".\n Example 2:\n Input: n = 2\n Output: \"xy\"\n Explanation: \"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\".\n Example 3:\n Input: n = 7\n Output: \"holasss\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1375, - "title": "Number of Times Binary String Is Prefix-Aligned", - "question": "class Solution:\n def numTimesAllBlue(self, flips: List[int]) -> int:\n \"\"\"\n 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.\n A 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.\n Return the number of times the binary string is prefix-aligned during the flipping process.\n Example 1:\n Input: flips = [3,2,4,1,5]\n Output: 2\n Explanation: The binary string is initially \"00000\".\n After applying step 1: The string becomes \"00100\", which is not prefix-aligned.\n After applying step 2: The string becomes \"01100\", which is not prefix-aligned.\n After applying step 3: The string becomes \"01110\", which is not prefix-aligned.\n After applying step 4: The string becomes \"11110\", which is prefix-aligned.\n After applying step 5: The string becomes \"11111\", which is prefix-aligned.\n We can see that the string was prefix-aligned 2 times, so we return 2.\n Example 2:\n Input: flips = [4,1,2,3]\n Output: 1\n Explanation: The binary string is initially \"0000\".\n After applying step 1: The string becomes \"0001\", which is not prefix-aligned.\n After applying step 2: The string becomes \"1001\", which is not prefix-aligned.\n After applying step 3: The string becomes \"1101\", which is not prefix-aligned.\n After applying step 4: The string becomes \"1111\", which is prefix-aligned.\n We can see that the string was prefix-aligned 1 time, so we return 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1376, - "title": "Time Needed to Inform All Employees", - "question": "class Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n \"\"\"\n 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.\n Each 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.\n The 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.\n The 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).\n Return the number of minutes needed to inform all the employees about the urgent news.\n Example 1:\n Input: n = 1, headID = 0, manager = [-1], informTime = [0]\n Output: 0\n Explanation: The head of the company is the only employee in the company.\n Example 2:\n Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]\n Output: 1\n Explanation: 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.\n The tree structure of the employees in the company is shown.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1377, - "title": "Frog Position After T Seconds", - "question": "class Solution:\n def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:\n \"\"\"\n Given an undirected tree consisting of n vertices numbered from 1 to n. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex.\n The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi.\n Return 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:\n Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 2, target = 4\n Output: 0.16666666666666666 \n Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 probability to the vertex 2 after second 1 and then jumping with 1/2 probability to vertex 4 after second 2. Thus the probability for the frog is on the vertex 4 after 2 seconds is 1/3 * 1/2 = 1/6 = 0.16666666666666666. \n Example 2:\n Input: n = 7, edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]], t = 1, target = 7\n Output: 0.3333333333333333\n Explanation: The figure above shows the given graph. The frog starts at vertex 1, jumping with 1/3 = 0.3333333333333333 probability to the vertex 7 after second 1. \n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1380, - "title": "Lucky Numbers in a Matrix", - "question": "class Solution:\n def luckyNumbers (self, matrix: List[List[int]]) -> List[int]:\n \"\"\"\n Given an m x n matrix of distinct numbers, return all lucky numbers in the matrix in any order.\n A 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:\n Input: matrix = [[3,7,8],[9,11,13],[15,16,17]]\n Output: [15]\n Explanation: 15 is the only lucky number since it is the minimum in its row and the maximum in its column.\n Example 2:\n Input: matrix = [[1,10,4,2],[9,3,8,7],[15,16,17,12]]\n Output: [12]\n Explanation: 12 is the only lucky number since it is the minimum in its row and the maximum in its column.\n Example 3:\n Input: matrix = [[7,8],[1,2]]\n Output: [7]\n Explanation: 7 is the only lucky number since it is the minimum in its row and the maximum in its column.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1381, - "title": "Design a Stack With Increment Operation", - "question": "class CustomStack:\n def __init__(self, maxSize: int):\n def push(self, x: int) -> None:\n def pop(self) -> int:\n def increment(self, k: int, val: int) -> None:\n \"\"\"\n Design a stack that supports increment operations on its elements.\n Implement the CustomStack class:\n CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack.\n void push(int x) Adds x to the top of the stack if the stack has not reached the maxSize.\n int pop() Pops and returns the top of the stack or -1 if the stack is empty.\n void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, increment all the elements in the stack.\n Example 1:\n Input\n [\"CustomStack\",\"push\",\"push\",\"pop\",\"push\",\"push\",\"push\",\"increment\",\"increment\",\"pop\",\"pop\",\"pop\",\"pop\"]\n [[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]\n Output\n [null,null,null,2,null,null,null,null,null,103,202,201,-1]\n Explanation\n CustomStack stk = new CustomStack(3); // Stack is Empty []\n stk.push(1); // stack becomes [1]\n stk.push(2); // stack becomes [1, 2]\n stk.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]\n stk.push(2); // stack becomes [1, 2]\n stk.push(3); // stack becomes [1, 2, 3]\n stk.push(4); // stack still [1, 2, 3], Do not add another elements as size is 4\n stk.increment(5, 100); // stack becomes [101, 102, 103]\n stk.increment(2, 100); // stack becomes [201, 202, 103]\n stk.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]\n stk.pop(); // return 202 --> Return top of the stack 202, stack becomes [201]\n stk.pop(); // return 201 --> Return top of the stack 201, stack becomes []\n stk.pop(); // return -1 --> Stack is empty return -1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1379, - "title": "Find a Corresponding Node of a Binary Tree in a Clone of That Tree", - "question": "class Solution:\n def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:\n \"\"\"\n Given two binary trees original and cloned and given a reference to a node target in the original tree.\n The cloned tree is a copy of the original tree.\n Return a reference to the same node in the cloned tree.\n Note 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:\n Input: tree = [7,4,3,null,null,6,19], target = 3\n Output: 3\n Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.\n Example 2:\n Input: tree = [7], target = 7\n Output: 7\n Example 3:\n Input: tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4\n Output: 4\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1383, - "title": "Maximum Performance of a Team", - "question": "class Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n \"\"\"\n 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.\n Choose at most k different engineers out of the n engineers to form a team with the maximum performance.\n The performance of a team is the sum of their engineers' speeds multiplied by the minimum efficiency among their engineers.\n Return the maximum performance of this team. Since the answer can be a huge number, return it modulo 109 + 7.\n Example 1:\n Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 2\n Output: 60\n Explanation: \n We have the maximum performance of the team by selecting engineer 2 (with speed=10 and efficiency=4) and engineer 5 (with speed=5 and efficiency=7). That is, performance = (10 + 5) * min(4, 7) = 60.\n Example 2:\n Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 3\n Output: 68\n Explanation:\n This is the same example as the first but k = 3. We can select engineer 1, engineer 2 and engineer 5 to get the maximum performance of the team. That is, performance = (2 + 10 + 5) * min(5, 4, 7) = 68.\n Example 3:\n Input: n = 6, speed = [2,10,3,1,5,8], efficiency = [5,4,3,9,7,2], k = 4\n Output: 72\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1399, - "title": "Count Largest Group", - "question": "class Solution:\n def countLargestGroup(self, n: int) -> int:\n \"\"\"\n You are given an integer n.\n Each number from 1 to n is grouped according to the sum of its digits.\n Return the number of groups that have the largest size.\n Example 1:\n Input: n = 13\n Output: 4\n Explanation: 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].\n There are 4 groups with largest size.\n Example 2:\n Input: n = 2\n Output: 2\n Explanation: There are 2 groups [1], [2] of size 1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1401, - "title": "Circle and Rectangle Overlapping", - "question": "class Solution:\n def checkOverlap(self, radius: int, xCenter: int, yCenter: int, x1: int, y1: int, x2: int, y2: int) -> bool:\n \"\"\"\n 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.\n Return 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:\n Input: radius = 1, xCenter = 0, yCenter = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1\n Output: true\n Explanation: Circle and rectangle share the point (1,0).\n Example 2:\n Input: radius = 1, xCenter = 1, yCenter = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1\n Output: false\n Example 3:\n Input: radius = 1, xCenter = 0, yCenter = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1400, - "title": "Construct K Palindrome Strings", - "question": "class Solution:\n def canConstruct(self, s: str, k: int) -> bool:\n \"\"\"\n 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:\n Input: s = \"annabelle\", k = 2\n Output: true\n Explanation: You can construct two palindromes using all characters in s.\n Some possible constructions \"anna\" + \"elble\", \"anbna\" + \"elle\", \"anellena\" + \"b\"\n Example 2:\n Input: s = \"leetcode\", k = 3\n Output: false\n Explanation: It is impossible to construct 3 palindromes using all the characters of s.\n Example 3:\n Input: s = \"true\", k = 4\n Output: true\n Explanation: The only possible solution is to put each character in a separate string.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1402, - "title": "Reducing Dishes", - "question": "class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n \"\"\"\n A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.\n Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].\n Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.\n Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.\n Example 1:\n Input: satisfaction = [-1,-8,0,5,-9]\n Output: 14\n Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).\n Each dish is prepared in one unit of time.\n Example 2:\n Input: satisfaction = [4,3,2]\n Output: 20\n Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)\n Example 3:\n Input: satisfaction = [-1,-4,-5]\n Output: 0\n Explanation: People do not like the dishes. No dish is prepared.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1389, - "title": "Create Target Array in the Given Order", - "question": "class Solution:\n def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:\n \"\"\"\n Given two arrays of integers nums and index. Your task is to create target array under the following rules:\n Initially target array is empty.\n From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.\n Repeat the previous step until there are no elements to read in nums and index.\n Return the target array.\n It is guaranteed that the insertion operations will be valid.\n Example 1:\n Input: nums = [0,1,2,3,4], index = [0,1,2,2,1]\n Output: [0,4,1,3,2]\n Explanation:\n nums index target\n 0 0 [0]\n 1 1 [0,1]\n 2 2 [0,1,2]\n 3 2 [0,1,3,2]\n 4 1 [0,4,1,3,2]\n Example 2:\n Input: nums = [1,2,3,4,0], index = [0,1,2,3,0]\n Output: [0,1,2,3,4]\n Explanation:\n nums index target\n 1 0 [1]\n 2 1 [1,2]\n 3 2 [1,2,3]\n 4 3 [1,2,3,4]\n 0 0 [0,1,2,3,4]\n Example 3:\n Input: nums = [1], index = [0]\n Output: [1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1391, - "title": "Check if There is a Valid Path in a Grid", - "question": "class Solution:\n def hasValidPath(self, grid: List[List[int]]) -> bool:\n \"\"\"\n You are given an m x n grid. Each cell of grid represents a street. The street of grid[i][j] can be:\n 1 which means a street connecting the left cell and the right cell.\n 2 which means a street connecting the upper cell and the lower cell.\n 3 which means a street connecting the left cell and the lower cell.\n 4 which means a street connecting the right cell and the lower cell.\n 5 which means a street connecting the left cell and the upper cell.\n 6 which means a street connecting the right cell and the upper cell.\n You 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.\n Notice that you are not allowed to change any street.\n Return true if there is a valid path in the grid or false otherwise.\n Example 1:\n Input: grid = [[2,4,3],[6,5,2]]\n Output: true\n Explanation: As shown you can start at cell (0, 0) and visit all the cells of the grid to reach (m - 1, n - 1).\n Example 2:\n Input: grid = [[1,2,1],[1,2,1]]\n Output: false\n Explanation: As shown you the street at cell (0, 0) is not connected with any street of any other cell and you will get stuck at cell (0, 0)\n Example 3:\n Input: grid = [[1,1,2]]\n Output: false\n Explanation: You will get stuck at cell (0, 1) and you cannot reach cell (0, 2).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1392, - "title": "Longest Happy Prefix", - "question": "class Solution:\n def longestPrefix(self, s: str) -> str:\n \"\"\"\n A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).\n Given a string s, return the longest happy prefix of s. Return an empty string \"\" if no such prefix exists.\n Example 1:\n Input: s = \"level\"\n Output: \"l\"\n Explanation: s contains 4 prefix excluding itself (\"l\", \"le\", \"lev\", \"leve\"), and suffix (\"l\", \"el\", \"vel\", \"evel\"). The largest prefix which is also suffix is given by \"l\".\n Example 2:\n Input: s = \"ababab\"\n Output: \"abab\"\n Explanation: \"abab\" is the largest prefix which is also suffix. They can overlap in the original string.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1394, - "title": "Find Lucky Integer in an Array", - "question": "class Solution:\n def findLucky(self, arr: List[int]) -> int:\n \"\"\"\n Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.\n Return the largest lucky integer in the array. If there is no lucky integer return -1.\n Example 1:\n Input: arr = [2,2,3,4]\n Output: 2\n Explanation: The only lucky number in the array is 2 because frequency[2] == 2.\n Example 2:\n Input: arr = [1,2,2,3,3,3]\n Output: 3\n Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.\n Example 3:\n Input: arr = [2,2,2,3,3]\n Output: -1\n Explanation: There are no lucky numbers in the array.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1395, - "title": "Count Number of Teams", - "question": "class Solution:\n def numTeams(self, rating: List[int]) -> int:\n \"\"\"\n There are n soldiers standing in a line. Each soldier is assigned a unique rating value.\n You have to form a team of 3 soldiers amongst them under the following rules:\n Choose 3 soldiers with index (i, j, k) with rating (rating[i], rating[j], rating[k]).\n A team is valid if: (rating[i] < rating[j] < rating[k]) or (rating[i] > rating[j] > rating[k]) where (0 <= i < j < k < n).\n Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).\n Example 1:\n Input: rating = [2,5,3,4,1]\n Output: 3\n Explanation: We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). \n Example 2:\n Input: rating = [2,1,3]\n Output: 0\n Explanation: We can't form any team given the conditions.\n Example 3:\n Input: rating = [1,2,3,4]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1396, - "title": "Design Underground System", - "question": "class UndergroundSystem:\n def __init__(self):\n def checkIn(self, id: int, stationName: str, t: int) -> None:\n def checkOut(self, id: int, stationName: str, t: int) -> None:\n def getAverageTime(self, startStation: str, endStation: str) -> float:\n \"\"\"\n An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.\n Implement the UndergroundSystem class:\n void checkIn(int id, string stationName, int t)\n A customer with a card ID equal to id, checks in at the station stationName at time t.\n A customer can only be checked into one place at a time.\n void checkOut(int id, string stationName, int t)\n A customer with a card ID equal to id, checks out from the station stationName at time t.\n double getAverageTime(string startStation, string endStation)\n Returns the average time it takes to travel from startStation to endStation.\n The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.\n The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.\n There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.\n You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.\n Example 1:\n Input\n [\"UndergroundSystem\",\"checkIn\",\"checkIn\",\"checkIn\",\"checkOut\",\"checkOut\",\"checkOut\",\"getAverageTime\",\"getAverageTime\",\"checkIn\",\"getAverageTime\",\"checkOut\",\"getAverageTime\"]\n [[],[45,\"Leyton\",3],[32,\"Paradise\",8],[27,\"Leyton\",10],[45,\"Waterloo\",15],[27,\"Waterloo\",20],[32,\"Cambridge\",22],[\"Paradise\",\"Cambridge\"],[\"Leyton\",\"Waterloo\"],[10,\"Leyton\",24],[\"Leyton\",\"Waterloo\"],[10,\"Waterloo\",38],[\"Leyton\",\"Waterloo\"]]\n Output\n [null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]\n Explanation\n UndergroundSystem undergroundSystem = new UndergroundSystem();\n undergroundSystem.checkIn(45, \"Leyton\", 3);\n undergroundSystem.checkIn(32, \"Paradise\", 8);\n undergroundSystem.checkIn(27, \"Leyton\", 10);\n undergroundSystem.checkOut(45, \"Waterloo\", 15); // Customer 45 \"Leyton\" -> \"Waterloo\" in 15-3 = 12\n undergroundSystem.checkOut(27, \"Waterloo\", 20); // Customer 27 \"Leyton\" -> \"Waterloo\" in 20-10 = 10\n undergroundSystem.checkOut(32, \"Cambridge\", 22); // Customer 32 \"Paradise\" -> \"Cambridge\" in 22-8 = 14\n undergroundSystem.getAverageTime(\"Paradise\", \"Cambridge\"); // return 14.00000. One trip \"Paradise\" -> \"Cambridge\", (14) / 1 = 14\n undergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000. Two trips \"Leyton\" -> \"Waterloo\", (10 + 12) / 2 = 11\n undergroundSystem.checkIn(10, \"Leyton\", 24);\n undergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 11.00000\n undergroundSystem.checkOut(10, \"Waterloo\", 38); // Customer 10 \"Leyton\" -> \"Waterloo\" in 38-24 = 14\n undergroundSystem.getAverageTime(\"Leyton\", \"Waterloo\"); // return 12.00000. Three trips \"Leyton\" -> \"Waterloo\", (10 + 12 + 14) / 3 = 12\n Example 2:\n Input\n [\"UndergroundSystem\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\",\"checkIn\",\"checkOut\",\"getAverageTime\"]\n [[],[10,\"Leyton\",3],[10,\"Paradise\",8],[\"Leyton\",\"Paradise\"],[5,\"Leyton\",10],[5,\"Paradise\",16],[\"Leyton\",\"Paradise\"],[2,\"Leyton\",21],[2,\"Paradise\",30],[\"Leyton\",\"Paradise\"]]\n Output\n [null,null,null,5.00000,null,null,5.50000,null,null,6.66667]\n Explanation\n UndergroundSystem undergroundSystem = new UndergroundSystem();\n undergroundSystem.checkIn(10, \"Leyton\", 3);\n undergroundSystem.checkOut(10, \"Paradise\", 8); // Customer 10 \"Leyton\" -> \"Paradise\" in 8-3 = 5\n undergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.00000, (5) / 1 = 5\n undergroundSystem.checkIn(5, \"Leyton\", 10);\n undergroundSystem.checkOut(5, \"Paradise\", 16); // Customer 5 \"Leyton\" -> \"Paradise\" in 16-10 = 6\n undergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 5.50000, (5 + 6) / 2 = 5.5\n undergroundSystem.checkIn(2, \"Leyton\", 21);\n undergroundSystem.checkOut(2, \"Paradise\", 30); // Customer 2 \"Leyton\" -> \"Paradise\" in 30-21 = 9\n undergroundSystem.getAverageTime(\"Leyton\", \"Paradise\"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1397, - "title": "Find All Good Strings", - "question": "class Solution:\n def findGoodStrings(self, n: int, s1: str, s2: str, evil: str) -> int:\n \"\"\"\n Given the strings s1 and s2 of size n and the string evil, return the number of good strings.\n A good string has size n, it is alphabetically greater than or equal to s1, it is alphabetically smaller than or equal to s2, and it does not contain the string evil as a substring. Since the answer can be a huge number, return this modulo 109 + 7.\n Example 1:\n Input: n = 2, s1 = \"aa\", s2 = \"da\", evil = \"b\"\n Output: 51 \n Explanation: There are 25 good strings starting with 'a': \"aa\",\"ac\",\"ad\",...,\"az\". Then there are 25 good strings starting with 'c': \"ca\",\"cc\",\"cd\",...,\"cz\" and finally there is one good string starting with 'd': \"da\". \n Example 2:\n Input: n = 8, s1 = \"leetcode\", s2 = \"leetgoes\", evil = \"leet\"\n Output: 0 \n Explanation: All strings greater than or equal to s1 and smaller than or equal to s2 start with the prefix \"leet\", therefore, there is not any good string.\n Example 3:\n Input: n = 2, s1 = \"gx\", s2 = \"gz\", evil = \"x\"\n Output: 2\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1413, - "title": "Minimum Value to Get Positive Step by Step Sum", - "question": "class Solution:\n def minStartValue(self, nums: List[int]) -> int:\n \"\"\"\n Given an array of integers nums, you start with an initial positive value startValue.\n In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).\n Return the minimum positive value of startValue such that the step by step sum is never less than 1.\n Example 1:\n Input: nums = [-3,2,-3,4,2]\n Output: 5\n Explanation: If you choose startValue = 4, in the third iteration your step by step sum is less than 1.\n step by step sum\n startValue = 4 | startValue = 5 | nums\n (4 -3 ) = 1 | (5 -3 ) = 2 | -3\n (1 +2 ) = 3 | (2 +2 ) = 4 | 2\n (3 -3 ) = 0 | (4 -3 ) = 1 | -3\n (0 +4 ) = 4 | (1 +4 ) = 5 | 4\n (4 +2 ) = 6 | (5 +2 ) = 7 | 2\n Example 2:\n Input: nums = [1,2]\n Output: 1\n Explanation: Minimum start value should be positive. \n Example 3:\n Input: nums = [1,-2,-3]\n Output: 5\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1414, - "title": "Find the Minimum Number of Fibonacci Numbers Whose Sum Is K", - "question": "class Solution:\n def findMinFibonacciNumbers(self, k: int) -> int:\n \"\"\"\n 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.\n The Fibonacci numbers are defined as:\n F1 = 1\n F2 = 1\n Fn = Fn-1 + Fn-2 for n > 2.\n It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.\n Example 1:\n Input: k = 7\n Output: 2 \n Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... \n For k = 7 we can use 2 + 5 = 7.\n Example 2:\n Input: k = 10\n Output: 2 \n Explanation: For k = 10 we can use 2 + 8 = 10.\n Example 3:\n Input: k = 19\n Output: 3 \n Explanation: For k = 19 we can use 1 + 5 + 13 = 19.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1415, - "title": "The k-th Lexicographical String of All Happy Strings of Length n", - "question": "class Solution:\n def getHappyString(self, n: int, k: int) -> str:\n \"\"\"\n A happy string is a string that:\n consists only of letters of the set ['a', 'b', 'c'].\n s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed).\n For example, strings \"abc\", \"ac\", \"b\" and \"abcbabcbcb\" are all happy strings and strings \"aa\", \"baa\" and \"ababbc\" are not happy strings.\n Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.\n Return 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:\n Input: n = 1, k = 3\n Output: \"c\"\n Explanation: The list [\"a\", \"b\", \"c\"] contains all happy strings of length 1. The third string is \"c\".\n Example 2:\n Input: n = 1, k = 4\n Output: \"\"\n Explanation: There are only 3 happy strings of length 1.\n Example 3:\n Input: n = 3, k = 9\n Output: \"cab\"\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1416, - "title": "Restore The Array", - "question": "class Solution:\n def numberOfArrays(self, s: str, k: int) -> int:\n \"\"\"\n 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.\n Given 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:\n Input: s = \"1000\", k = 10000\n Output: 1\n Explanation: The only possible array is [1000]\n Example 2:\n Input: s = \"1000\", k = 10\n Output: 0\n Explanation: There cannot be an array that was printed this way and has all integer >= 1 and <= 10.\n Example 3:\n Input: s = \"1317\", k = 2000\n Output: 8\n Explanation: Possible arrays are [1317],[131,7],[13,17],[1,317],[13,1,7],[1,31,7],[1,3,17],[1,3,1,7]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1403, - "title": "Minimum Subsequence in Non-Increasing Order", - "question": "class Solution:\n def minSubsequence(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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. \n If 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. \n Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.\n Example 1:\n Input: nums = [4,3,10,9,8]\n Output: [10,9] \n Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included. However, the subsequence [10,9] has the maximum total sum of its elements. \n Example 2:\n Input: nums = [4,4,7,6,7]\n Output: [7,7,6] \n Explanation: 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-decreasing order. \n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1404, - "title": "Number of Steps to Reduce a Number in Binary Representation to One", - "question": "class Solution:\n def numSteps(self, s: str) -> int:\n \"\"\"\n 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:\n If the current number is even, you have to divide it by 2.\n If the current number is odd, you have to add 1 to it.\n It is guaranteed that you can always reach one for all test cases.\n Example 1:\n Input: s = \"1101\"\n Output: 6\n Explanation: \"1101\" corressponds to number 13 in their decimal representation.\n Step 1) 13 is odd, add 1 and obtain 14. \n Step 2) 14 is even, divide by 2 and obtain 7.\n Step 3) 7 is odd, add 1 and obtain 8.\n Step 4) 8 is even, divide by 2 and obtain 4. \n Step 5) 4 is even, divide by 2 and obtain 2. \n Step 6) 2 is even, divide by 2 and obtain 1. \n Example 2:\n Input: s = \"10\"\n Output: 1\n Explanation: \"10\" corressponds to number 2 in their decimal representation.\n Step 1) 2 is even, divide by 2 and obtain 1. \n Example 3:\n Input: s = \"1\"\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1406, - "title": "Stone Game III", - "question": "class Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n \"\"\"\n Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\n Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.\n The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.\n The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.\n Assume Alice and Bob play optimally.\n Return \"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:\n Input: values = [1,2,3,7]\n Output: \"Bob\"\n Explanation: Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.\n Example 2:\n Input: values = [1,2,3,-9]\n Output: \"Alice\"\n Explanation: Alice must choose all the three piles at the first move to win and leave Bob with negative score.\n If 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.\n If 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.\n Remember that both play optimally so here Alice will choose the scenario that makes her win.\n Example 3:\n Input: values = [1,2,3,6]\n Output: \"Tie\"\n Explanation: Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1408, - "title": "String Matching in an Array", - "question": "class Solution:\n def stringMatching(self, words: List[str]) -> List[str]:\n \"\"\"\n 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.\n A substring is a contiguous sequence of characters within a string\n Example 1:\n Input: words = [\"mass\",\"as\",\"hero\",\"superhero\"]\n Output: [\"as\",\"hero\"]\n Explanation: \"as\" is substring of \"mass\" and \"hero\" is substring of \"superhero\".\n [\"hero\",\"as\"] is also a valid answer.\n Example 2:\n Input: words = [\"leetcode\",\"et\",\"code\"]\n Output: [\"et\",\"code\"]\n Explanation: \"et\", \"code\" are substring of \"leetcode\".\n Example 3:\n Input: words = [\"blue\",\"green\",\"bu\"]\n Output: []\n Explanation: No string of words is substring of another string.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1409, - "title": "Queries on a Permutation With Key", - "question": "class Solution:\n def processQueries(self, queries: List[int], m: int) -> List[int]:\n \"\"\"\n 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:\r\n In the beginning, you have the permutation P=[1,2,3,...,m].\r\n For 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].\r\n Return an array containing the result for the given queries.\r\n Example 1:\r\n Input: queries = [3,1,2,1], m = 5\r\n Output: [2,1,2,1] \r\n Explanation: The queries are processed as follow: \r\n For 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]. \r\n For 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]. \r\n For 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]. \r\n For 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]. \r\n Therefore, the array containing the result is [2,1,2,1]. \r\n Example 2:\r\n Input: queries = [4,1,2,2], m = 4\r\n Output: [3,1,2,0]\r\n Example 3:\r\n Input: queries = [7,5,5,8,3], m = 8\r\n Output: [6,5,0,7,5]\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1410, - "title": "HTML Entity Parser", - "question": "class Solution:\n def entityParser(self, text: str) -> str:\n \"\"\"\n 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.\n The special characters and their entities for HTML are:\n Quotation Mark: the entity is " and symbol character is \".\n Single Quote Mark: the entity is ' and symbol character is '.\n Ampersand: the entity is & and symbol character is &.\n Greater Than Sign: the entity is > and symbol character is >.\n Less Than Sign: the entity is < and symbol character is <.\n Slash: the entity is ⁄ and symbol character is /.\n Given the input text string to the HTML parser, you have to implement the entity parser.\n Return the text after replacing the entities by the special characters.\n Example 1:\n Input: text = \"& is an HTML entity but &ambassador; is not.\"\n Output: \"& is an HTML entity but &ambassador; is not.\"\n Explanation: The parser will replace the & entity by &\n Example 2:\n Input: text = \"and I quote: "..."\"\n Output: \"and I quote: \\\"...\\\"\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1411, - "title": "Number of Ways to Paint N \u00d7 3 Grid", - "question": "class Solution:\n def numOfWays(self, n: int) -> int:\n \"\"\"\n You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).\n Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.\n Example 1:\n Input: n = 1\n Output: 12\n Explanation: There are 12 possible way to paint the grid as shown.\n Example 2:\n Input: n = 5000\n Output: 30228214\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1431, - "title": "Kids With the Greatest Number of Candies", - "question": "class Solution:\n def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:\n \"\"\"\n 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.\n Return 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.\n Note that multiple kids can have the greatest number of candies.\n Example 1:\n Input: candies = [2,3,5,1,3], extraCandies = 3\n Output: [true,true,true,false,true] \n Explanation: If you give all extraCandies to:\n - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.\n - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.\n - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.\n - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.\n Example 2:\n Input: candies = [4,2,1,1,2], extraCandies = 1\n Output: [true,false,false,false,false] \n Explanation: There is only 1 extra candy.\n Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.\n Example 3:\n Input: candies = [12,1,12], extraCandies = 10\n Output: [true,false,true]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1432, - "title": "Max Difference You Can Get From Changing an Integer", - "question": "class Solution:\n def maxDiff(self, num: int) -> int:\n \"\"\"\n You are given an integer num. You will apply the following steps exactly two times:\n Pick a digit x (0 <= x <= 9).\n Pick another digit y (0 <= y <= 9). The digit y can be equal to x.\n Replace all the occurrences of x in the decimal representation of num by y.\n The new integer cannot have any leading zeros, also the new integer cannot be 0.\n Let a and b be the results of applying the operations to num the first and second times, respectively.\n Return the max difference between a and b.\n Example 1:\n Input: num = 555\n Output: 888\n Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.\n The second time pick x = 5 and y = 1 and store the new integer in b.\n We have now a = 999 and b = 111 and max difference = 888\n Example 2:\n Input: num = 9\n Output: 8\n Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.\n The second time pick x = 9 and y = 1 and store the new integer in b.\n We have now a = 9 and b = 1 and max difference = 8\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1433, - "title": "Check If a String Can Break Another String", - "question": "class Solution:\n def checkIfCanBreak(self, s1: str, s2: str) -> bool:\n \"\"\"\n 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.\n A 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:\n Input: s1 = \"abc\", s2 = \"xya\"\n Output: true\n Explanation: \"ayx\" is a permutation of s2=\"xya\" which can break to string \"abc\" which is a permutation of s1=\"abc\".\n Example 2:\n Input: s1 = \"abe\", s2 = \"acd\"\n Output: false \n Explanation: All permutations for s1=\"abe\" are: \"abe\", \"aeb\", \"bae\", \"bea\", \"eab\" and \"eba\" and all permutation for s2=\"acd\" are: \"acd\", \"adc\", \"cad\", \"cda\", \"dac\" and \"dca\". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.\n Example 3:\n Input: s1 = \"leetcodee\", s2 = \"interview\"\n Output: true\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1434, - "title": "Number of Ways to Wear Different Hats to Each Other", - "question": "class Solution:\n def numberWays(self, hats: List[List[int]]) -> int:\n \"\"\"\n There are n people and 40 types of hats labeled from 1 to 40.\n Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.\n Return the number of ways that the n people wear different hats to each other.\n Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\n Input: hats = [[3,4],[4,5],[5]]\n Output: 1\n Explanation: There is only one way to choose hats given the conditions. \n First person choose hat 3, Second person choose hat 4 and last one hat 5.\n Example 2:\n Input: hats = [[3,5,1],[3,5]]\n Output: 4\n Explanation: There are 4 ways to choose hats:\n (3,5), (5,3), (1,3) and (1,5)\n Example 3:\n Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]\n Output: 24\n Explanation: Each person can choose hats labeled from 1 to 4.\n Number of Permutations of (1,2,3,4) = 24.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1417, - "title": "Reformat The String", - "question": "class Solution:\n def reformat(self, s: str) -> str:\n \"\"\"\n You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).\n You 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.\n Return the reformatted string or return an empty string if it is impossible to reformat the string.\n Example 1:\n Input: s = \"a0b1c2\"\n Output: \"0a1b2c\"\n Explanation: No two adjacent characters have the same type in \"0a1b2c\". \"a0b1c2\", \"0a1b2c\", \"0c2a1b\" are also valid permutations.\n Example 2:\n Input: s = \"leetcode\"\n Output: \"\"\n Explanation: \"leetcode\" has only characters so we cannot separate them by digits.\n Example 3:\n Input: s = \"1229857369\"\n Output: \"\"\n Explanation: \"1229857369\" has only digits so we cannot separate them by characters.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1418, - "title": "Display Table of Food Orders in a Restaurant", - "question": "class Solution:\r\n def displayTable(self, orders: List[List[str]]) -> List[List[str]]:\n \"\"\"\n 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.\r\n Return 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.\r\n Example 1:\r\n Input: orders = [[\"David\",\"3\",\"Ceviche\"],[\"Corina\",\"10\",\"Beef Burrito\"],[\"David\",\"3\",\"Fried Chicken\"],[\"Carla\",\"5\",\"Water\"],[\"Carla\",\"5\",\"Ceviche\"],[\"Rous\",\"3\",\"Ceviche\"]]\r\n Output: [[\"Table\",\"Beef Burrito\",\"Ceviche\",\"Fried Chicken\",\"Water\"],[\"3\",\"0\",\"2\",\"1\",\"0\"],[\"5\",\"0\",\"1\",\"0\",\"1\"],[\"10\",\"1\",\"0\",\"0\",\"0\"]] \r\n Explanation:\r\n The displaying table looks like:\r\n Table,Beef Burrito,Ceviche,Fried Chicken,Water\r\n 3 ,0 ,2 ,1 ,0\r\n 5 ,0 ,1 ,0 ,1\r\n 10 ,1 ,0 ,0 ,0\r\n For the table 3: David orders \"Ceviche\" and \"Fried Chicken\", and Rous orders \"Ceviche\".\r\n For the table 5: Carla orders \"Water\" and \"Ceviche\".\r\n For the table 10: Corina orders \"Beef Burrito\". \r\n Example 2:\r\n Input: orders = [[\"James\",\"12\",\"Fried Chicken\"],[\"Ratesh\",\"12\",\"Fried Chicken\"],[\"Amadeus\",\"12\",\"Fried Chicken\"],[\"Adam\",\"1\",\"Canadian Waffles\"],[\"Brianna\",\"1\",\"Canadian Waffles\"]]\r\n Output: [[\"Table\",\"Canadian Waffles\",\"Fried Chicken\"],[\"1\",\"2\",\"0\"],[\"12\",\"0\",\"3\"]] \r\n Explanation: \r\n For the table 1: Adam and Brianna order \"Canadian Waffles\".\r\n For the table 12: James, Ratesh and Amadeus order \"Fried Chicken\".\r\n Example 3:\r\n Input: orders = [[\"Laura\",\"2\",\"Bean Burrito\"],[\"Jhon\",\"2\",\"Beef Burrito\"],[\"Melissa\",\"2\",\"Soda\"]]\r\n Output: [[\"Table\",\"Bean Burrito\",\"Beef Burrito\",\"Soda\"],[\"2\",\"1\",\"1\",\"1\"]]\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1419, - "title": "Minimum Number of Frogs Croaking", - "question": "class Solution:\n def minNumberOfFrogs(self, croakOfFrogs: str) -> int:\n \"\"\"\n 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.\n Return the minimum number of different frogs to finish all the croaks in the given string.\n A 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:\n Input: croakOfFrogs = \"croakcroak\"\n Output: 1 \n Explanation: One frog yelling \"croak\" twice.\n Example 2:\n Input: croakOfFrogs = \"crcoakroak\"\n Output: 2 \n Explanation: The minimum number of frogs is two. \n The first frog could yell \"crcoakroak\".\n The second frog could yell later \"crcoakroak\".\n Example 3:\n Input: croakOfFrogs = \"croakcrook\"\n Output: -1\n Explanation: The given string is an invalid combination of \"croak\" from different frogs.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1420, - "title": "Build Array Where You Can Find The Maximum Exactly K Comparisons", - "question": "class Solution:\n def numOfArrays(self, n: int, m: int, k: int) -> int:\n \"\"\"\n You are given three integers n, m and k. Consider the following algorithm to find the maximum element of an array of positive integers:\n You should build the array arr which has the following properties:\n arr has exactly n integers.\n 1 <= arr[i] <= m where (0 <= i < n).\n After applying the mentioned algorithm to arr, the value search_cost is equal to k.\n Return the number of ways to build the array arr under the mentioned conditions. As the answer may grow large, the answer must be computed modulo 109 + 7.\n Example 1:\n Input: n = 2, m = 3, k = 1\n Output: 6\n Explanation: The possible arrays are [1, 1], [2, 1], [2, 2], [3, 1], [3, 2] [3, 3]\n Example 2:\n Input: n = 5, m = 2, k = 3\n Output: 0\n Explanation: There are no possible arrays that satisify the mentioned conditions.\n Example 3:\n Input: n = 9, m = 1, k = 1\n Output: 1\n Explanation: The only possible array is [1, 1, 1, 1, 1, 1, 1, 1, 1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1422, - "title": "Maximum Score After Splitting a String", - "question": "class Solution:\n def maxScore(self, s: str) -> int:\n \"\"\"\n 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).\n The 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:\n Input: s = \"011101\"\n Output: 5 \n Explanation: \n All possible ways of splitting s into two non-empty substrings are:\n left = \"0\" and right = \"11101\", score = 1 + 4 = 5 \n left = \"01\" and right = \"1101\", score = 1 + 3 = 4 \n left = \"011\" and right = \"101\", score = 1 + 2 = 3 \n left = \"0111\" and right = \"01\", score = 1 + 1 = 2 \n left = \"01110\" and right = \"1\", score = 2 + 1 = 3\n Example 2:\n Input: s = \"00111\"\n Output: 5\n Explanation: When left = \"00\" and right = \"111\", we get the maximum score = 2 + 3 = 5\n Example 3:\n Input: s = \"1111\"\n Output: 3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1423, - "title": "Maximum Points You Can Obtain from Cards", - "question": "class Solution:\n def maxScore(self, cardPoints: List[int], k: int) -> int:\n \"\"\"\n 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.\n In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.\n Your score is the sum of the points of the cards you have taken.\n Given the integer array cardPoints and the integer k, return the maximum score you can obtain.\n Example 1:\n Input: cardPoints = [1,2,3,4,5,6,1], k = 3\n Output: 12\n Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.\n Example 2:\n Input: cardPoints = [2,2,2], k = 2\n Output: 4\n Explanation: Regardless of which two cards you take, your score will always be 4.\n Example 3:\n Input: cardPoints = [9,7,7,9,7,7,9], k = 7\n Output: 55\n Explanation: You have to take all the cards. Your score is the sum of points of all cards.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1424, - "title": "Diagonal Traverse II", - "question": "class Solution:\n def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:\n \"\"\"\n Given a 2D integer array nums, return all elements of nums in diagonal order as shown in the below images.\n Example 1:\n Input: nums = [[1,2,3],[4,5,6],[7,8,9]]\n Output: [1,4,2,7,5,3,8,6,9]\n Example 2:\n Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]\n Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1446, - "title": "Consecutive Characters", - "question": "class Solution:\n def maxPower(self, s: str) -> int:\n \"\"\"\n The power of the string is the maximum length of a non-empty substring that contains only one unique character.\n Given a string s, return the power of s.\n Example 1:\n Input: s = \"leetcode\"\n Output: 2\n Explanation: The substring \"ee\" is of length 2 with the character 'e' only.\n Example 2:\n Input: s = \"abbcccddddeeeeedcba\"\n Output: 5\n Explanation: The substring \"eeeee\" is of length 5 with the character 'e' only.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1447, - "title": "Simplified Fractions", - "question": "class Solution:\n def simplifiedFractions(self, n: int) -> List[str]:\n \"\"\"\n 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:\n Input: n = 2\n Output: [\"1/2\"]\n Explanation: \"1/2\" is the only unique fraction with a denominator less-than-or-equal-to 2.\n Example 2:\n Input: n = 3\n Output: [\"1/2\",\"1/3\",\"2/3\"]\n Example 3:\n Input: n = 4\n Output: [\"1/2\",\"1/3\",\"1/4\",\"2/3\",\"3/4\"]\n Explanation: \"2/4\" is not a simplified fraction because it can be simplified to \"1/2\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1448, - "title": "Count Good Nodes in Binary Tree", - "question": "class Solution:\n def goodNodes(self, root: TreeNode) -> int:\n \"\"\"\n 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.\r\n Return the number of good nodes in the binary tree.\r\n Example 1:\r\n Input: root = [3,1,4,3,null,1,5]\r\n Output: 4\r\n Explanation: Nodes in blue are good.\r\n Root Node (3) is always a good node.\r\n Node 4 -> (3,4) is the maximum value in the path starting from the root.\r\n Node 5 -> (3,4,5) is the maximum value in the path\r\n Node 3 -> (3,1,3) is the maximum value in the path.\r\n Example 2:\r\n Input: root = [3,3,null,4,2]\r\n Output: 3\r\n Explanation: Node 2 -> (3, 3, 2) is not good, because \"3\" is higher than it.\r\n Example 3:\r\n Input: root = [1]\r\n Output: 1\r\n Explanation: Root is considered as good.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1449, - "title": "Form Largest Integer With Digits That Add up to Target", - "question": "class Solution:\n def largestNumber(self, cost: List[int], target: int) -> str:\n \"\"\"\n Given an array of integers cost and an integer target, return the maximum integer you can paint under the following rules:\n The cost of painting a digit (i + 1) is given by cost[i] (0-indexed).\n The total cost used must be equal to target.\n The integer does not have 0 digits.\n Since 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:\n Input: cost = [4,3,2,5,6,7,2,5,5], target = 9\n Output: \"7772\"\n Explanation: The cost to paint the digit '7' is 2, and the digit '2' is 3. Then cost(\"7772\") = 2*3+ 3*1 = 9. You could also paint \"977\", but \"7772\" is the largest number.\n Digit cost\n 1 -> 4\n 2 -> 3\n 3 -> 2\n 4 -> 5\n 5 -> 6\n 6 -> 7\n 7 -> 2\n 8 -> 5\n 9 -> 5\n Example 2:\n Input: cost = [7,6,5,5,5,6,8,7,8], target = 12\n Output: \"85\"\n Explanation: The cost to paint the digit '8' is 7, and the digit '5' is 5. Then cost(\"85\") = 7 + 5 = 12.\n Example 3:\n Input: cost = [2,4,6,2,4,6,4,4,4], target = 5\n Output: \"0\"\n Explanation: It is impossible to paint any integer with total cost equal to target.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1436, - "title": "Destination City", - "question": "class Solution:\n def destCity(self, paths: List[List[str]]) -> str:\n \"\"\"\n 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.\n It is guaranteed that the graph of paths forms a line without any loop, therefore, there will be exactly one destination city.\n Example 1:\n Input: paths = [[\"London\",\"New York\"],[\"New York\",\"Lima\"],[\"Lima\",\"Sao Paulo\"]]\n Output: \"Sao Paulo\" \n Explanation: 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\".\n Example 2:\n Input: paths = [[\"B\",\"C\"],[\"D\",\"B\"],[\"C\",\"A\"]]\n Output: \"A\"\n Explanation: All possible trips are: \n \"D\" -> \"B\" -> \"C\" -> \"A\". \n \"B\" -> \"C\" -> \"A\". \n \"C\" -> \"A\". \n \"A\". \n Clearly the destination city is \"A\".\n Example 3:\n Input: paths = [[\"A\",\"Z\"]]\n Output: \"Z\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1437, - "title": "Check If All 1\"s Are at Least Length K Places Away", - "question": "class Solution:\n def kLengthApart(self, nums: List[int], k: int) -> bool:\n \"\"\"\n 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:\n Input: nums = [1,0,0,0,1,0,0,1], k = 2\n Output: true\n Explanation: Each of the 1s are at least 2 places away from each other.\n Example 2:\n Input: nums = [1,0,0,1,0,1], k = 2\n Output: false\n Explanation: The second 1 and third 1 are only one apart from each other.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1438, - "title": "Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit", - "question": "class Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n \"\"\"\n 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:\n Input: nums = [8,2,4,7], limit = 4\n Output: 2 \n Explanation: 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. \n Therefore, the size of the longest subarray is 2.\n Example 2:\n Input: nums = [10,1,2,4,7,2], limit = 5\n Output: 4 \n Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.\n Example 3:\n Input: nums = [4,2,2,2,4,4,2,2], limit = 0\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1439, - "title": "Find the Kth Smallest Sum of a Matrix With Sorted Rows", - "question": "class Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n \"\"\"\n You are given an m x n matrix mat that has its rows sorted in non-decreasing order and an integer k.\n You are allowed to choose exactly one element from each row to form an array.\n Return the kth smallest array sum among all possible arrays.\n Example 1:\n Input: mat = [[1,3,11],[2,4,6]], k = 5\n Output: 7\n Explanation: Choosing one element from each row, the first k smallest sum are:\n [1,2], [1,4], [3,2], [3,4], [1,6]. Where the 5th sum is 7.\n Example 2:\n Input: mat = [[1,3,11],[2,4,6]], k = 9\n Output: 17\n Example 3:\n Input: mat = [[1,10,10],[1,4,5],[2,3,6]], k = 7\n Output: 9\n Explanation: Choosing one element from each row, the first k smallest sum are:\n [1,1,2], [1,1,3], [1,4,2], [1,4,3], [1,1,6], [1,5,2], [1,5,3]. Where the 7th sum is 9. \n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1441, - "title": "Build an Array With Stack Operations", - "question": "class Solution:\n def buildArray(self, target: List[int], n: int) -> List[str]:\n \"\"\"\n You are given an integer array target and an integer n.\n You 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.\n You also have a stream of the integers in the range [1, n].\n Use 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:\n If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.\n If the stack is not empty, pop the integer at the top of the stack.\n If, 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.\n Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.\n Example 1:\n Input: target = [1,3], n = 3\n Output: [\"Push\",\"Push\",\"Pop\",\"Push\"]\n Explanation: Initially the stack s is empty. The last element is the top of the stack.\n Read 1 from the stream and push it to the stack. s = [1].\n Read 2 from the stream and push it to the stack. s = [1,2].\n Pop the integer on the top of the stack. s = [1].\n Read 3 from the stream and push it to the stack. s = [1,3].\n Example 2:\n Input: target = [1,2,3], n = 3\n Output: [\"Push\",\"Push\",\"Push\"]\n Explanation: Initially the stack s is empty. The last element is the top of the stack.\n Read 1 from the stream and push it to the stack. s = [1].\n Read 2 from the stream and push it to the stack. s = [1,2].\n Read 3 from the stream and push it to the stack. s = [1,2,3].\n Example 3:\n Input: target = [1,2], n = 4\n Output: [\"Push\",\"Push\"]\n Explanation: Initially the stack s is empty. The last element is the top of the stack.\n Read 1 from the stream and push it to the stack. s = [1].\n Read 2 from the stream and push it to the stack. s = [1,2].\n Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.\n The answers that read integer 3 from the stream are not accepted.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1442, - "title": "Count Triplets That Can Form Two Arrays of Equal XOR", - "question": "class Solution:\n def countTriplets(self, arr: List[int]) -> int:\n \"\"\"\n Given an array of integers arr.\n We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).\n Let's define a and b as follows:\n a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]\n b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]\n Note that ^ denotes the bitwise-xor operation.\n Return the number of triplets (i, j and k) Where a == b.\n Example 1:\n Input: arr = [2,3,1,6,7]\n Output: 4\n Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)\n Example 2:\n Input: arr = [1,1,1,1,1]\n Output: 10\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1443, - "title": "Minimum Time to Collect All Apples in a Tree", - "question": "class Solution:\n def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:\n \"\"\"\n 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.\n The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. 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:\n Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]\n Output: 8 \n Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \n Example 2:\n Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]\n Output: 6\n Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. \n Example 3:\n Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1444, - "title": "Number of Ways of Cutting a Pizza", - "question": "class Solution:\n def ways(self, pizza: List[str], k: int) -> int:\n \"\"\"\n 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. \r\n For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person.\r\n Return the number of ways of cutting the pizza such that each piece contains at least one apple. Since the answer can be a huge number, return this modulo 10^9 + 7.\r\n Example 1:\r\n Input: pizza = [\"A..\",\"AAA\",\"...\"], k = 3\r\n Output: 3 \r\n Explanation: The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple.\r\n Example 2:\r\n Input: pizza = [\"A..\",\"AA.\",\"...\"], k = 3\r\n Output: 1\r\n Example 3:\r\n Input: pizza = [\"A..\",\"A..\",\"...\"], k = 1\r\n Output: 1\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1460, - "title": "Make Two Arrays Equal by Reversing Subarrays", - "question": "class Solution:\n def canBeEqual(self, target: List[int], arr: List[int]) -> bool:\n \"\"\"\n 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.\n Return true if you can make arr equal to target or false otherwise.\n Example 1:\n Input: target = [1,2,3,4], arr = [2,4,1,3]\n Output: true\n Explanation: You can follow the next steps to convert arr to target:\n 1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]\n 2- Reverse subarray [4,2], arr becomes [1,2,4,3]\n 3- Reverse subarray [4,3], arr becomes [1,2,3,4]\n There are multiple ways to convert arr to target, this is not the only way to do so.\n Example 2:\n Input: target = [7], arr = [7]\n Output: true\n Explanation: arr is equal to target without any reverses.\n Example 3:\n Input: target = [3,7,9], arr = [3,7,11]\n Output: false\n Explanation: arr does not have value 9 and it can never be converted to target.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1461, - "title": "Check If a String Contains All Binary Codes of Size K", - "question": "class Solution:\n def hasAllCodes(self, s: str, k: int) -> bool:\n \"\"\"\n 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:\n Input: s = \"00110110\", k = 2\n Output: true\n Explanation: The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\n Example 2:\n Input: s = \"0110\", k = 1\n Output: true\n Explanation: The binary codes of length 1 are \"0\" and \"1\", it is clear that both exist as a substring. \n Example 3:\n Input: s = \"0110\", k = 2\n Output: false\n Explanation: The binary code \"00\" is of length 2 and does not exist in the array.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1462, - "title": "Course Schedule IV", - "question": "class Solution:\n def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \"\"\"\n 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.\n For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.\n Prerequisites 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.\n You 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.\n Return a boolean array answer, where answer[j] is the answer to the jth query.\n Example 1:\n Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]\n Output: [false,true]\n Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.\n Course 0 is not a prerequisite of course 1, but the opposite is true.\n Example 2:\n Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]\n Output: [false,false]\n Explanation: There are no prerequisites, and each course is independent.\n Example 3:\n Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]\n Output: [true,true]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1463, - "title": "Cherry Pickup II", - "question": "class Solution:\n def cherryPickup(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n You have two robots that can collect cherries for you:\n Robot #1 is located at the top-left corner (0, 0), and\n Robot #2 is located at the top-right corner (0, cols - 1).\n Return the maximum number of cherries collection using both robots by following the rules below:\n From a cell (i, j), robots can move to cell (i + 1, j - 1), (i + 1, j), or (i + 1, j + 1).\n When any robot passes through a cell, It picks up all cherries, and the cell becomes an empty cell.\n When both robots stay in the same cell, only one takes the cherries.\n Both robots cannot move outside of the grid at any moment.\n Both robots should reach the bottom row in grid.\n Example 1:\n Input: grid = [[3,1,1],[2,5,1],[1,5,5],[2,1,1]]\n Output: 24\n Explanation: Path of robot #1 and #2 are described in color green and blue respectively.\n Cherries taken by Robot #1, (3 + 2 + 5 + 2) = 12.\n Cherries taken by Robot #2, (1 + 5 + 5 + 1) = 12.\n Total of cherries: 12 + 12 = 24.\n Example 2:\n Input: grid = [[1,0,0,0,0,0,1],[2,0,0,0,0,3,0],[2,0,9,0,0,0,0],[0,3,0,5,4,0,0],[1,0,2,3,0,0,6]]\n Output: 28\n Explanation: Path of robot #1 and #2 are described in color green and blue respectively.\n Cherries taken by Robot #1, (1 + 9 + 5 + 2) = 17.\n Cherries taken by Robot #2, (1 + 3 + 4 + 3) = 11.\n Total of cherries: 17 + 11 = 28.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1450, - "title": "Number of Students Doing Homework at a Given Time", - "question": "class Solution:\n def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:\n \"\"\"\n Given two integer arrays startTime and endTime and given an integer queryTime.\n The ith student started doing their homework at the time startTime[i] and finished it at time endTime[i].\n Return 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:\n Input: startTime = [1,2,3], endTime = [3,2,7], queryTime = 4\n Output: 1\n Explanation: We have 3 students where:\n The first student started doing homework at time 1 and finished at time 3 and wasn't doing anything at time 4.\n The second student started doing homework at time 2 and finished at time 2 and also wasn't doing anything at time 4.\n The third student started doing homework at time 3 and finished at time 7 and was the only student doing homework at time 4.\n Example 2:\n Input: startTime = [4], endTime = [4], queryTime = 4\n Output: 1\n Explanation: The only student was doing their homework at the queryTime.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1451, - "title": "Rearrange Words in a Sentence", - "question": "class Solution:\n def arrangeWords(self, text: str) -> str:\n \"\"\"\n Given a sentence text (A sentence is a string of space-separated words) in the following format:\n First letter is in upper case.\n Each word in text are separated by a single space.\n Your 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.\n Return the new text following the format shown above.\n Example 1:\n Input: text = \"Leetcode is cool\"\n Output: \"Is cool leetcode\"\n Explanation: There are 3 words, \"Leetcode\" of length 8, \"is\" of length 2 and \"cool\" of length 4.\n Output is ordered by length and the new first word starts with capital letter.\n Example 2:\n Input: text = \"Keep calm and code on\"\n Output: \"On and keep calm code\"\n Explanation: Output is ordered as follows:\n \"On\" 2 letters.\n \"and\" 3 letters.\n \"keep\" 4 letters in case of tie order by position in original text.\n \"calm\" 4 letters.\n \"code\" 4 letters.\n Example 3:\n Input: text = \"To be or not to be\"\n Output: \"To be or to be not\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1452, - "title": "People Whose List of Favorite Companies Is Not a Subset of Another List", - "question": "class Solution:\n def peopleIndexes(self, favoriteCompanies: List[List[str]]) -> List[int]:\n \"\"\"\n Given the array favoriteCompanies where favoriteCompanies[i] is the list of favorites companies for the ith person (indexed from 0).\n Return 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:\n Input: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"google\",\"microsoft\"],[\"google\",\"facebook\"],[\"google\"],[\"amazon\"]]\n Output: [0,1,4] \n Explanation: \n Person 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. \n Person with index=3 has favoriteCompanies[3]=[\"google\"] which is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"] and favoriteCompanies[1]=[\"google\",\"microsoft\"]. \n Other lists of favorite companies are not a subset of another list, therefore, the answer is [0,1,4].\n Example 2:\n Input: favoriteCompanies = [[\"leetcode\",\"google\",\"facebook\"],[\"leetcode\",\"amazon\"],[\"facebook\",\"google\"]]\n Output: [0,1] \n Explanation: In this case favoriteCompanies[2]=[\"facebook\",\"google\"] is a subset of favoriteCompanies[0]=[\"leetcode\",\"google\",\"facebook\"], therefore, the answer is [0,1].\n Example 3:\n Input: favoriteCompanies = [[\"leetcode\"],[\"google\"],[\"facebook\"],[\"amazon\"]]\n Output: [0,1,2,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1453, - "title": "Maximum Number of Darts Inside of a Circular Dartboard", - "question": "class Solution:\n def numPoints(self, darts: List[List[int]], r: int) -> int:\n \"\"\"\n 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.\n Bob 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 lies on the dartboard.\n Given the integer r, return the maximum number of darts that can lie on the dartboard.\n Example 1:\n Input: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2\n Output: 4\n Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.\n Example 2:\n Input: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5\n Output: 5\n Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1455, - "title": "Check If a Word Occurs As a Prefix of Any Word in a Sentence", - "question": "class Solution:\n def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:\n \"\"\"\n 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.\n Return 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.\n A prefix of a string s is any leading contiguous substring of s.\n Example 1:\n Input: sentence = \"i love eating burger\", searchWord = \"burg\"\n Output: 4\n Explanation: \"burg\" is prefix of \"burger\" which is the 4th word in the sentence.\n Example 2:\n Input: sentence = \"this problem is an easy problem\", searchWord = \"pro\"\n Output: 2\n Explanation: \"pro\" is prefix of \"problem\" which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index.\n Example 3:\n Input: sentence = \"i am tired\", searchWord = \"you\"\n Output: -1\n Explanation: \"you\" is not a prefix of any word in the sentence.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1456, - "title": "Maximum Number of Vowels in a Substring of Given Length", - "question": "class Solution:\n def maxVowels(self, s: str, k: int) -> int:\n \"\"\"\n Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.\n Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.\n Example 1:\n Input: s = \"abciiidef\", k = 3\n Output: 3\n Explanation: The substring \"iii\" contains 3 vowel letters.\n Example 2:\n Input: s = \"aeiou\", k = 2\n Output: 2\n Explanation: Any substring of length 2 contains 2 vowels.\n Example 3:\n Input: s = \"leetcode\", k = 3\n Output: 2\n Explanation: \"lee\", \"eet\" and \"ode\" contain 2 vowels.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1457, - "title": "Pseudo-Palindromic Paths in a Binary Tree", - "question": "class Solution:\n def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:\n \"\"\"\n 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.\n Return the number of pseudo-palindromic paths going from the root node to leaf nodes.\n Example 1:\n Input: root = [2,3,1,3,1,null,1]\n Output: 2 \n Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).\n Example 2:\n Input: root = [2,1,1,1,3,null,null,null,null,null,1]\n Output: 1 \n Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).\n Example 3:\n Input: root = [9]\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1458, - "title": "Max Dot Product of Two Subsequences", - "question": "class Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n Given two arrays nums1 and nums2.\n Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.\n A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).\n Example 1:\n Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6]\n Output: 18\n Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.\n Their dot product is (2*3 + (-2)*(-6)) = 18.\n Example 2:\n Input: nums1 = [3,-2], nums2 = [2,-6,7]\n Output: 21\n Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2.\n Their dot product is (3*7) = 21.\n Example 3:\n Input: nums1 = [-1,-1], nums2 = [1,1]\n Output: -1\n Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2.\n Their dot product is -1.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1475, - "title": "Final Prices With a Special Discount in a Shop", - "question": "class Solution:\n def finalPrices(self, prices: List[int]) -> List[int]:\n \"\"\"\n You are given an integer array prices where prices[i] is the price of the ith item in a shop.\n There 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.\n Return 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:\n Input: prices = [8,4,6,2,3]\n Output: [4,2,4,2,3]\n Explanation: \n For 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.\n For 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.\n For 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.\n For items 3 and 4 you will not receive any discount at all.\n Example 2:\n Input: prices = [1,2,3,4,5]\n Output: [1,2,3,4,5]\n Explanation: In this case, for all items, you will not receive any discount at all.\n Example 3:\n Input: prices = [10,1,1,6]\n Output: [9,0,1,6]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1478, - "title": "Allocate Mailboxes", - "question": "class Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n \"\"\"\n 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.\n Return the minimum total distance between each house and its nearest mailbox.\n The test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\n Input: houses = [1,4,8,10,20], k = 3\n Output: 5\n Explanation: Allocate mailboxes in position 3, 9 and 20.\n Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 \n Example 2:\n Input: houses = [2,3,5,12,18], k = 2\n Output: 9\n Explanation: Allocate mailboxes in position 3 and 14.\n Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1476, - "title": "Subrectangle Queries", - "question": "class SubrectangleQueries:\n def __init__(self, rectangle: List[List[int]]):\n def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:\n def getValue(self, row: int, col: int) -> int:\n \"\"\"\n Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:\n 1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)\n Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).\n 2. getValue(int row, int col)\n Returns the current value of the coordinate (row,col) from the rectangle.\n Example 1:\n Input\n [\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\"]\n [[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]\n Output\n [null,1,null,5,5,null,10,5]\n Explanation\n SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]); \n // The initial rectangle (4x3) looks like:\n // 1 2 1\n // 4 3 4\n // 3 2 1\n // 1 1 1\n subrectangleQueries.getValue(0, 2); // return 1\n subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);\n // After this update the rectangle looks like:\n // 5 5 5\n // 5 5 5\n // 5 5 5\n // 5 5 5 \n subrectangleQueries.getValue(0, 2); // return 5\n subrectangleQueries.getValue(3, 1); // return 5\n subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);\n // After this update the rectangle looks like:\n // 5 5 5\n // 5 5 5\n // 5 5 5\n // 10 10 10 \n subrectangleQueries.getValue(3, 1); // return 10\n subrectangleQueries.getValue(0, 2); // return 5\n Example 2:\n Input\n [\"SubrectangleQueries\",\"getValue\",\"updateSubrectangle\",\"getValue\",\"getValue\",\"updateSubrectangle\",\"getValue\"]\n [[[[1,1,1],[2,2,2],[3,3,3]]],[0,0],[0,0,2,2,100],[0,0],[2,2],[1,1,2,2,20],[2,2]]\n Output\n [null,1,null,100,100,null,20]\n Explanation\n SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,1,1],[2,2,2],[3,3,3]]);\n subrectangleQueries.getValue(0, 0); // return 1\n subrectangleQueries.updateSubrectangle(0, 0, 2, 2, 100);\n subrectangleQueries.getValue(0, 0); // return 100\n subrectangleQueries.getValue(2, 2); // return 100\n subrectangleQueries.updateSubrectangle(1, 1, 2, 2, 20);\n subrectangleQueries.getValue(2, 2); // return 20\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1477, - "title": "Find Two Non-overlapping Sub-arrays Each With Target Sum", - "question": "class Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n \"\"\"\n You are given an array of integers arr and an integer target.\n You 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.\n Return 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:\n Input: arr = [3,2,2,4,3], target = 3\n Output: 2\n Explanation: Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.\n Example 2:\n Input: arr = [7,3,4,7], target = 7\n Output: 2\n Explanation: Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.\n Example 3:\n Input: arr = [4,3,2,6,2,3,4], target = 6\n Output: -1\n Explanation: We have only one sub-array of sum = 6.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1464, - "title": "Maximum Product of Two Elements in an Array", - "question": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n Input: nums = [3,4,5,2]\n Output: 12 \n Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. \n Example 2:\n Input: nums = [1,5,4,5]\n Output: 16\n Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.\n Example 3:\n Input: nums = [3,7]\n Output: 12\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1465, - "title": "Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts", - "question": "class Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n \"\"\"\n You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:\n horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and\n verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.\n Return 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:\n Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]\n Output: 4 \n Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.\n Example 2:\n Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]\n Output: 6\n Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.\n Example 3:\n Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]\n Output: 9\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1466, - "title": "Reorder Routes to Make All Paths Lead to the City Zero", - "question": "class Solution:\n def minReorder(self, n: int, connections: List[List[int]]) -> int:\n \"\"\"\n There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.\n Roads are represented by connections where connections[i] = [ai, bi] represents a road from city ai to city bi.\n This year, there will be a big event in the capital (city 0), and many people want to travel to this city.\n Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.\n It's guaranteed that each city can reach city 0 after reorder.\n Example 1:\n Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]\n Output: 3\n Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n Example 2:\n Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]\n Output: 2\n Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).\n Example 3:\n Input: n = 3, connections = [[1,0],[2,0]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1467, - "title": "Probability of a Two Boxes Having The Same Number of Distinct Balls", - "question": "class Solution:\n def getProbability(self, balls: List[int]) -> float:\n \"\"\"\n Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i.\n All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).\n Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).\n Return 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:\n Input: balls = [1,1]\n Output: 1.00000\n Explanation: Only 2 ways to divide the balls equally:\n - A ball of color 1 to box 1 and a ball of color 2 to box 2\n - A ball of color 2 to box 1 and a ball of color 1 to box 2\n In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1\n Example 2:\n Input: balls = [2,1,1]\n Output: 0.66667\n Explanation: We have the set of balls [1, 1, 2, 3]\n This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with 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]\n After that, we add the first two balls to the first box and the second two balls to the second box.\n We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.\n Probability is 8/12 = 0.66667\n Example 3:\n Input: balls = [1,2,1,2]\n Output: 0.60000\n Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.\n Probability = 108 / 180 = 0.6\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1470, - "title": "Shuffle the Array", - "question": "class Solution:\n def shuffle(self, nums: List[int], n: int) -> List[int]:\n \"\"\"\n Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].\r\n Return the array in the form [x1,y1,x2,y2,...,xn,yn].\r\n Example 1:\r\n Input: nums = [2,5,1,3,4,7], n = 3\r\n Output: [2,3,5,4,1,7] \r\n Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].\r\n Example 2:\r\n Input: nums = [1,2,3,4,4,3,2,1], n = 4\r\n Output: [1,4,2,3,3,2,4,1]\r\n Example 3:\r\n Input: nums = [1,1,2,2], n = 2\r\n Output: [1,2,1,2]\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1471, - "title": "The k Strongest Values in an Array", - "question": "class Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n \"\"\"\n Given an array of integers arr and an integer k.\n A 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.\n If |arr[i] - m| == |arr[j] - m|, then arr[i] is said to be stronger than arr[j] if arr[i] > arr[j].\n Return a list of the strongest k values in the array. return the answer in any arbitrary order.\n Median 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).\n For 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.\n For 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:\n Input: arr = [1,2,3,4,5], k = 2\n Output: [5,1]\n Explanation: 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.\n Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.\n Example 2:\n Input: arr = [1,1,3,5,5], k = 2\n Output: [5,5]\n Explanation: 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].\n Example 3:\n Input: arr = [6,7,11,7,6,8], k = 5\n Output: [11,8,6,6,7]\n Explanation: Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7].\n Any permutation of [11,8,6,6,7] is accepted.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1472, - "title": "Design Browser History", - "question": "class BrowserHistory:\n def __init__(self, homepage: str):\n def visit(self, url: str) -> None:\n def back(self, steps: int) -> str:\n def forward(self, steps: int) -> str:\n \"\"\"\n You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.\n Implement the BrowserHistory class:\n BrowserHistory(string homepage) Initializes the object with the homepage of the browser.\n void visit(string url) Visits url from the current page. It clears up all the forward history.\n string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.\n string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.\n Example:\n Input:\n [\"BrowserHistory\",\"visit\",\"visit\",\"visit\",\"back\",\"back\",\"forward\",\"visit\",\"forward\",\"back\",\"back\"]\n [[\"leetcode.com\"],[\"google.com\"],[\"facebook.com\"],[\"youtube.com\"],[1],[1],[1],[\"linkedin.com\"],[2],[2],[7]]\n Output:\n [null,null,null,null,\"facebook.com\",\"google.com\",\"facebook.com\",null,\"linkedin.com\",\"google.com\",\"leetcode.com\"]\n Explanation:\n BrowserHistory browserHistory = new BrowserHistory(\"leetcode.com\");\n browserHistory.visit(\"google.com\"); // You are in \"leetcode.com\". Visit \"google.com\"\n browserHistory.visit(\"facebook.com\"); // You are in \"google.com\". Visit \"facebook.com\"\n browserHistory.visit(\"youtube.com\"); // You are in \"facebook.com\". Visit \"youtube.com\"\n browserHistory.back(1); // You are in \"youtube.com\", move back to \"facebook.com\" return \"facebook.com\"\n browserHistory.back(1); // You are in \"facebook.com\", move back to \"google.com\" return \"google.com\"\n browserHistory.forward(1); // You are in \"google.com\", move forward to \"facebook.com\" return \"facebook.com\"\n browserHistory.visit(\"linkedin.com\"); // You are in \"facebook.com\". Visit \"linkedin.com\"\n browserHistory.forward(2); // You are in \"linkedin.com\", you cannot move forward any steps.\n browserHistory.back(2); // You are in \"linkedin.com\", move back two steps to \"facebook.com\" then to \"google.com\". return \"google.com\"\n browserHistory.back(7); // You are in \"google.com\", you can move back only one step to \"leetcode.com\". return \"leetcode.com\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1473, - "title": "Paint House III", - "question": "class Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n \"\"\"\n There is a row of m houses in a small city, each house must be painted with one of the n colors (labeled from 1 to n), some houses that have been painted last summer should not be painted again.\n A neighborhood is a maximal group of continuous houses that are painted with the same color.\n For example: houses = [1,2,2,3,3,2,1,1] contains 5 neighborhoods [{1}, {2,2}, {3,3}, {2}, {1,1}].\n Given an array houses, an m x n matrix cost and an integer target where:\n houses[i]: is the color of the house i, and 0 if the house is not painted yet.\n cost[i][j]: is the cost of paint the house i with the color j + 1.\n Return the minimum cost of painting all the remaining houses in such a way that there are exactly target neighborhoods. If it is not possible, return -1.\n Example 1:\n Input: houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n Output: 9\n Explanation: Paint houses of this way [1,2,2,1,1]\n This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].\n Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.\n Example 2:\n Input: houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3\n Output: 11\n Explanation: Some houses are already painted, Paint the houses of this way [2,2,1,2,2]\n This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}]. \n Cost of paint the first and last house (10 + 1) = 11.\n Example 3:\n Input: houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3\n Output: -1\n Explanation: Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1491, - "title": "Average Salary Excluding the Minimum and Maximum Salary", - "question": "class Solution:\n def average(self, salary: List[int]) -> float:\n \"\"\"\n You are given an array of unique integers salary where salary[i] is the salary of the ith employee.\n Return the average salary of employees excluding the minimum and maximum salary. Answers within 10-5 of the actual answer will be accepted.\n Example 1:\n Input: salary = [4000,3000,1000,2000]\n Output: 2500.00000\n Explanation: Minimum salary and maximum salary are 1000 and 4000 respectively.\n Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500\n Example 2:\n Input: salary = [1000,2000,3000]\n Output: 2000.00000\n Explanation: Minimum salary and maximum salary are 1000 and 3000 respectively.\n Average salary excluding minimum and maximum salary is (2000) / 1 = 2000\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1492, - "title": "The kth Factor of n", - "question": "class Solution:\n def kthFactor(self, n: int, k: int) -> int:\n \"\"\"\n 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.\n Consider 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:\n Input: n = 12, k = 3\n Output: 3\n Explanation: Factors list is [1, 2, 3, 4, 6, 12], the 3rd factor is 3.\n Example 2:\n Input: n = 7, k = 2\n Output: 7\n Explanation: Factors list is [1, 7], the 2nd factor is 7.\n Example 3:\n Input: n = 4, k = 4\n Output: -1\n Explanation: Factors list is [1, 2, 4], there is only 3 factors. We should return -1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1493, - "title": "Longest Subarray of 1\"s After Deleting One Element", - "question": "class Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n \"\"\"\n Given a binary array nums, you should delete one element from it.\n Return 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:\n Input: nums = [1,1,0,1]\n Output: 3\n Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.\n Example 2:\n Input: nums = [0,1,1,1,0,1,1,0,1]\n Output: 5\n Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].\n Example 3:\n Input: nums = [1,1,1]\n Output: 2\n Explanation: You must delete one element.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1494, - "title": "Parallel Courses II", - "question": "class Solution:\n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n \"\"\"\n 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.\n In 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.\n Return 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:\n Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2\n Output: 3\n Explanation: The figure above represents the given graph.\n In the first semester, you can take courses 2 and 3.\n In the second semester, you can take course 1.\n In the third semester, you can take course 4.\n Example 2:\n Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2\n Output: 4\n Explanation: The figure above represents the given graph.\n In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.\n In the second semester, you can take course 4.\n In the third semester, you can take course 1.\n In the fourth semester, you can take course 5.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1480, - "title": "Running Sum of 1d Array", - "question": "class Solution:\r\n def runningSum(self, nums: List[int]) -> List[int]:\n \"\"\"\n Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]\u2026nums[i]).\r\n Return the running sum of nums.\r\n Example 1:\r\n Input: nums = [1,2,3,4]\r\n Output: [1,3,6,10]\r\n Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].\r\n Example 2:\r\n Input: nums = [1,1,1,1,1]\r\n Output: [1,2,3,4,5]\r\n Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].\r\n Example 3:\r\n Input: nums = [3,1,2,10,1]\r\n Output: [3,4,6,16,17]\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1481, - "title": "Least Number of Unique Integers after K Removals", - "question": "class Solution:\r\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n \"\"\"\n Given an array of integers arr and an integer k. Find the least number of unique integers after removing exactly k elements.\r\n Example 1:\r\n Input: arr = [5,5,4], k = 1\r\n Output: 1\r\n Explanation: Remove the single 4, only 5 is left.\r\n Example 2:\r\n Input: arr = [4,3,1,1,3,3,2], k = 3\r\n Output: 2\r\n Explanation: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1482, - "title": "Minimum Number of Days to Make m Bouquets", - "question": "class Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:\n \"\"\"\n You are given an integer array bloomDay, an integer m and an integer k.\n You want to make m bouquets. To make a bouquet, you need to use k adjacent flowers from the garden.\n The garden consists of n flowers, the ith flower will bloom in the bloomDay[i] and then can be used in exactly one bouquet.\n Return 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:\n Input: bloomDay = [1,10,3,10,2], m = 3, k = 1\n Output: 3\n Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden.\n We need 3 bouquets each should contain 1 flower.\n After day 1: [x, _, _, _, _] // we can only make one bouquet.\n After day 2: [x, _, _, _, x] // we can only make two bouquets.\n After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.\n Example 2:\n Input: bloomDay = [1,10,3,10,2], m = 3, k = 2\n Output: -1\n Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.\n Example 3:\n Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3\n Output: 12\n Explanation: We need 2 bouquets each should have 3 flowers.\n Here is the garden after the 7 and 12 days:\n After day 7: [x, x, x, x, _, x, x]\n We 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.\n After day 12: [x, x, x, x, x, x, x]\n It is obvious that we can make two bouquets in different ways.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1486, - "title": "XOR Operation in an Array", - "question": "class Solution:\n def xorOperation(self, n: int, start: int) -> int:\n \"\"\"\n You are given an integer n and an integer start.\n Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.\n Return the bitwise XOR of all elements of nums.\n Example 1:\n Input: n = 5, start = 0\n Output: 8\n Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0 ^ 2 ^ 4 ^ 6 ^ 8) = 8.\n Where \"^\" corresponds to bitwise XOR operator.\n Example 2:\n Input: n = 4, start = 3\n Output: 8\n Explanation: Array nums is equal to [3, 5, 7, 9] where (3 ^ 5 ^ 7 ^ 9) = 8.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1487, - "title": "Making File Names Unique", - "question": "class Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n \"\"\"\n 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].\n Since 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.\n Return 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:\n Input: names = [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\n Output: [\"pes\",\"fifa\",\"gta\",\"pes(2019)\"]\n Explanation: Let's see how the file system creates folder names:\n \"pes\" --> not assigned before, remains \"pes\"\n \"fifa\" --> not assigned before, remains \"fifa\"\n \"gta\" --> not assigned before, remains \"gta\"\n \"pes(2019)\" --> not assigned before, remains \"pes(2019)\"\n Example 2:\n Input: names = [\"gta\",\"gta(1)\",\"gta\",\"avalon\"]\n Output: [\"gta\",\"gta(1)\",\"gta(2)\",\"avalon\"]\n Explanation: Let's see how the file system creates folder names:\n \"gta\" --> not assigned before, remains \"gta\"\n \"gta(1)\" --> not assigned before, remains \"gta(1)\"\n \"gta\" --> the name is reserved, system adds (k), since \"gta(1)\" is also reserved, systems put k = 2. it becomes \"gta(2)\"\n \"avalon\" --> not assigned before, remains \"avalon\"\n Example 3:\n Input: names = [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece\"]\n Output: [\"onepiece\",\"onepiece(1)\",\"onepiece(2)\",\"onepiece(3)\",\"onepiece(4)\"]\n Explanation: When the last folder is created, the smallest positive valid k is 4, and it becomes \"onepiece(4)\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1488, - "title": "Avoid Flood in The City", - "question": "class Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n \"\"\"\n 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.\n Given an integer array rains where:\n rains[i] > 0 means there will be rains over the rains[i] lake.\n rains[i] == 0 means there are no rains this day and you can choose one lake this day and dry it.\n Return an array ans where:\n ans.length == rains.length\n ans[i] == -1 if rains[i] > 0.\n ans[i] is the lake you choose to dry in the ith day if rains[i] == 0.\n If there are multiple valid answers return any of them. If it is impossible to avoid flood return an empty array.\n Notice 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:\n Input: rains = [1,2,3,4]\n Output: [-1,-1,-1,-1]\n Explanation: After the first day full lakes are [1]\n After the second day full lakes are [1,2]\n After the third day full lakes are [1,2,3]\n After the fourth day full lakes are [1,2,3,4]\n There's no day to dry any lake and there is no flood in any lake.\n Example 2:\n Input: rains = [1,2,0,0,2,1]\n Output: [-1,-1,2,1,-1,-1]\n Explanation: After the first day full lakes are [1]\n After the second day full lakes are [1,2]\n After the third day, we dry lake 2. Full lakes are [1]\n After the fourth day, we dry lake 1. There is no full lakes.\n After the fifth day, full lakes are [2].\n After the sixth day, full lakes are [1,2].\n It is easy that this scenario is flood-free. [-1,-1,1,2,-1,-1] is another acceptable scenario.\n Example 3:\n Input: rains = [1,2,0,1,2]\n Output: []\n Explanation: After the second day, full lakes are [1,2]. We have to dry one lake in the third day.\n After 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1489, - "title": "Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree", - "question": "class Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n \"\"\"\n Given a weighted undirected connected graph with n vertices numbered from 0 to n - 1, and an array edges where edges[i] = [ai, bi, weighti] represents a bidirectional and weighted edge between nodes ai and bi. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.\n Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.\n Note that you can return the indices of the edges in any order.\n Example 1:\n Input: n = 5, edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\n Output: [[0,1],[2,3,4,5]]\n Explanation: The figure above describes the graph.\n The following figure shows all the possible MSTs:\n Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.\n The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.\n Example 2:\n Input: n = 4, edges = [[0,1,1],[1,2,1],[2,3,1],[0,3,1]]\n Output: [[],[0,1,2,3]]\n Explanation: We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1508, - "title": "Range Sum of Sorted Subarray Sums", - "question": "class Solution:\n def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int:\n \"\"\"\n 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.\n Return 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:\n Input: nums = [1,2,3,4], n = 4, left = 1, right = 5\n Output: 13 \n Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. \n Example 2:\n Input: nums = [1,2,3,4], n = 4, left = 3, right = 4\n Output: 6\n Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.\n Example 3:\n Input: nums = [1,2,3,4], n = 4, left = 1, right = 10\n Output: 50\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1509, - "title": "Minimum Difference Between Largest and Smallest Value in Three Moves", - "question": "class Solution:\n def minDifference(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums.\n In one move, you can choose one element of nums and change it to any value.\n Return the minimum difference between the largest and smallest value of nums after performing at most three moves.\n Example 1:\n Input: nums = [5,3,2,4]\n Output: 0\n Explanation: We can make at most 3 moves.\n In the first move, change 2 to 3. nums becomes [5,3,3,4].\n In the second move, change 4 to 3. nums becomes [5,3,3,3].\n In the third move, change 5 to 3. nums becomes [3,3,3,3].\n After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.\n Example 2:\n Input: nums = [1,5,0,10,14]\n Output: 1\n Explanation: We can make at most 3 moves.\n In the first move, change 5 to 0. nums becomes [1,0,0,10,14].\n In the second move, change 10 to 0. nums becomes [1,0,0,0,14].\n In the third move, change 14 to 1. nums becomes [1,0,0,0,1].\n After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.\n It can be shown that there is no way to make the difference 0 in 3 moves.\n Example 3:\n Input: nums = [3,100,20]\n Output: 0\n Explanation: We can make at most 3 moves.\n In the first move, change 100 to 7. nums becomes [4,7,20].\n In the second move, change 20 to 7. nums becomes [4,7,7].\n In the third move, change 4 to 3. nums becomes [7,7,7].\n After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1510, - "title": "Stone Game IV", - "question": "class Solution:\n def winnerSquareGame(self, n: int) -> bool:\n \"\"\"\n Alice and Bob take turns playing a game, with Alice starting first.\n Initially, there are n stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.\n Also, if a player cannot make a move, he/she loses the game.\n Given a positive integer n, return true if and only if Alice wins the game otherwise return false, assuming both players play optimally.\n Example 1:\n Input: n = 1\n Output: true\n Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.\n Example 2:\n Input: n = 2\n Output: false\n Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).\n Example 3:\n Input: n = 4\n Output: true\n Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1496, - "title": "Path Crossing", - "question": "class Solution:\n def isPathCrossing(self, path: str) -> bool:\n \"\"\"\n 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.\n Return 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:\n Input: path = \"NES\"\n Output: false \n Explanation: Notice that the path doesn't cross any point more than once.\n Example 2:\n Input: path = \"NESWW\"\n Output: true\n Explanation: Notice that the path visits the origin twice.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1497, - "title": "Check If Array Pairs Are Divisible by k", - "question": "class Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n \"\"\"\n Given an array of integers arr of even length n and an integer k.\n We want to divide the array into exactly n / 2 pairs such that the sum of each pair is divisible by k.\n Return true If you can find a way to do that or false otherwise.\n Example 1:\n Input: arr = [1,2,3,4,5,10,6,7,8,9], k = 5\n Output: true\n Explanation: Pairs are (1,9),(2,8),(3,7),(4,6) and (5,10).\n Example 2:\n Input: arr = [1,2,3,4,5,6], k = 7\n Output: true\n Explanation: Pairs are (1,6),(2,5) and(3,4).\n Example 3:\n Input: arr = [1,2,3,4,5,6], k = 10\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1498, - "title": "Number of Subsequences That Satisfy the Given Sum Condition", - "question": "class Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n \"\"\"\n You are given an array of integers nums and an integer target.\n Return 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:\n Input: nums = [3,5,6,7], target = 9\n Output: 4\n Explanation: 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)\n Example 2:\n Input: nums = [3,3,6,8], target = 10\n Output: 6\n Explanation: 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]\n Example 3:\n Input: nums = [2,3,3,4,6,7], target = 12\n Output: 61\n Explanation: There are 63 non-empty subsequences, two of them do not satisfy the condition ([6,7], [7]).\n Number of valid subsequences (63 - 2 = 61).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1499, - "title": "Max Value of Equation", - "question": "class Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n \"\"\"\n 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.\n Return the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length.\n It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.\n Example 1:\n Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\n Output: 4\n Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\n No other pairs satisfy the condition, so we return the max of 4 and 1.\n Example 2:\n Input: points = [[0,0],[3,0],[9,2]], k = 3\n Output: 3\n Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1502, - "title": "Can Make Arithmetic Progression From Sequence", - "question": "class Solution:\n def canMakeArithmeticProgression(self, arr: List[int]) -> bool:\n \"\"\"\n A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.\n Given an array of numbers arr, return true if the array can be rearranged to form an arithmetic progression. Otherwise, return false.\n Example 1:\n Input: arr = [3,5,1]\n Output: true\n Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.\n Example 2:\n Input: arr = [1,2,4]\n Output: false\n Explanation: There is no way to reorder the elements to obtain an arithmetic progression.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1503, - "title": "Last Moment Before All Ants Fall Out of a Plank", - "question": "class Solution:\n def getLastMoment(self, n: int, left: List[int], right: List[int]) -> int:\n \"\"\"\n 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.\n When 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.\n When an ant reaches one end of the plank at a time t, it falls out of the plank immediately.\n Given 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:\n Input: n = 4, left = [4,3], right = [0,1]\n Output: 4\n Explanation: 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.\n The 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).\n Example 2:\n Input: n = 7, left = [], right = [0,1,2,3,4,5,6,7]\n Output: 7\n Explanation: All ants are going to the right, the ant at index 0 needs 7 seconds to fall.\n Example 3:\n Input: n = 7, left = [0,1,2,3,4,5,6,7], right = []\n Output: 7\n Explanation: All ants are going to the left, the ant at index 7 needs 7 seconds to fall.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1504, - "title": "Count Submatrices With All Ones", - "question": "class Solution:\n def numSubmat(self, mat: List[List[int]]) -> int:\n \"\"\"\n Given an m x n binary matrix mat, return the number of submatrices that have all ones.\n Example 1:\n Input: mat = [[1,0,1],[1,1,0],[1,1,0]]\n Output: 13\n Explanation: \n There are 6 rectangles of side 1x1.\n There are 2 rectangles of side 1x2.\n There are 3 rectangles of side 2x1.\n There is 1 rectangle of side 2x2. \n There is 1 rectangle of side 3x1.\n Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.\n Example 2:\n Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]\n Output: 24\n Explanation: \n There are 8 rectangles of side 1x1.\n There are 5 rectangles of side 1x2.\n There are 2 rectangles of side 1x3. \n There are 4 rectangles of side 2x1.\n There are 2 rectangles of side 2x2. \n There are 2 rectangles of side 3x1. \n There is 1 rectangle of side 3x2. \n Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1505, - "title": "Minimum Possible Integer After at Most K Adjacent Swaps On Digits", - "question": "class Solution:\n def minInteger(self, num: str, k: int) -> str:\n \"\"\"\n 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.\n Return the minimum integer you can obtain also as a string.\n Example 1:\n Input: num = \"4321\", k = 4\n Output: \"1342\"\n Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.\n Example 2:\n Input: num = \"100\", k = 1\n Output: \"010\"\n Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.\n Example 3:\n Input: num = \"36789\", k = 1000\n Output: \"36789\"\n Explanation: We can keep the number without any swaps.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1523, - "title": "Count Odd Numbers in an Interval Range", - "question": "class Solution:\n def countOdds(self, low: int, high: int) -> int:\n \"\"\"\n Given two non-negative integers low and high. Return the count of odd numbers between low and high (inclusive).\r\n Example 1:\r\n Input: low = 3, high = 7\r\n Output: 3\r\n Explanation: The odd numbers between 3 and 7 are [3,5,7].\r\n Example 2:\r\n Input: low = 8, high = 10\r\n Output: 1\r\n Explanation: The odd numbers between 8 and 10 are [9].\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1524, - "title": "Number of Sub-arrays With Odd Sum", - "question": "class Solution:\n def numOfSubarrays(self, arr: List[int]) -> int:\n \"\"\"\n Given an array of integers arr, return the number of subarrays with an odd sum.\n Since the answer can be very large, return it modulo 109 + 7.\n Example 1:\n Input: arr = [1,3,5]\n Output: 4\n Explanation: All subarrays are [[1],[1,3],[1,3,5],[3],[3,5],[5]]\n All sub-arrays sum are [1,4,9,3,8,5].\n Odd sums are [1,9,3,5] so the answer is 4.\n Example 2:\n Input: arr = [2,4,6]\n Output: 0\n Explanation: All subarrays are [[2],[2,4],[2,4,6],[4],[4,6],[6]]\n All sub-arrays sum are [2,6,12,4,10,6].\n All sub-arrays have even sum and the answer is 0.\n Example 3:\n Input: arr = [1,2,3,4,5,6,7]\n Output: 16\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1525, - "title": "Number of Good Ways to Split a String", - "question": "class Solution:\n def numSplits(self, s: str) -> int:\n \"\"\"\n You are given a string s.\n A 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.\n Return the number of good splits you can make in s.\n Example 1:\n Input: s = \"aacaba\"\n Output: 2\n Explanation: There are 5 ways to split \"aacaba\" and 2 of them are good. \n (\"a\", \"acaba\") Left string and right string contains 1 and 3 different letters respectively.\n (\"aa\", \"caba\") Left string and right string contains 1 and 3 different letters respectively.\n (\"aac\", \"aba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n (\"aaca\", \"ba\") Left string and right string contains 2 and 2 different letters respectively (good split).\n (\"aacab\", \"a\") Left string and right string contains 3 and 1 different letters respectively.\n Example 2:\n Input: s = \"abcd\"\n Output: 1\n Explanation: Split the string as follows (\"ab\", \"cd\").\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1526, - "title": "Minimum Number of Increments on Subarrays to Form a Target Array", - "question": "class Solution:\n def minNumberOperations(self, target: List[int]) -> int:\n \"\"\"\n You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.\n In one operation you can choose any subarray from initial and increment each value by one.\n Return the minimum number of operations to form a target array from initial.\n The test cases are generated so that the answer fits in a 32-bit integer.\n Example 1:\n Input: target = [1,2,3,2,1]\n Output: 3\n Explanation: We need at least 3 operations to form the target array from the initial array.\n [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).\n [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).\n [1,2,2,2,1] increment 1 at index 2.\n [1,2,3,2,1] target array is formed.\n Example 2:\n Input: target = [3,1,1,2]\n Output: 4\n Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]\n Example 3:\n Input: target = [3,1,5,4,2]\n Output: 7\n Explanation: [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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1512, - "title": "Number of Good Pairs", - "question": "class Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n \"\"\"\n Given an array of integers nums, return the number of good pairs.\n A pair (i, j) is called good if nums[i] == nums[j] and i < j.\n Example 1:\n Input: nums = [1,2,3,1,1,3]\n Output: 4\n Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.\n Example 2:\n Input: nums = [1,1,1,1]\n Output: 6\n Explanation: Each pair in the array are good.\n Example 3:\n Input: nums = [1,2,3]\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1513, - "title": "Number of Substrings With Only 1s", - "question": "class Solution:\n def numSub(self, s: str) -> int:\n \"\"\"\n 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:\n Input: s = \"0110111\"\n Output: 9\n Explanation: There are 9 substring in total with only 1's characters.\n \"1\" -> 5 times.\n \"11\" -> 3 times.\n \"111\" -> 1 time.\n Example 2:\n Input: s = \"101\"\n Output: 2\n Explanation: Substring \"1\" is shown 2 times in s.\n Example 3:\n Input: s = \"111111\"\n Output: 21\n Explanation: Each substring contains only 1's characters.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1531, - "title": "String Compression II", - "question": "class Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n \"\"\"\n Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string \"aabccc\" we replace \"aa\" by \"a2\" and replace \"ccc\" by \"c3\". Thus the compressed string becomes \"a2bc3\".\n Notice that in this problem, we are not adding '1' after single characters.\n Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.\n Find the minimum length of the run-length encoded version of s after deleting at most k characters.\n Example 1:\n Input: s = \"aaabcccd\", k = 2\n Output: 4\n Explanation: Compressing s without deleting anything will give us \"a3bc3d\" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = \"abcccd\" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be \"a3c3\" of length 4.\n Example 2:\n Input: s = \"aabbaa\", k = 2\n Output: 2\n Explanation: If we delete both 'b' characters, the resulting compressed string would be \"a4\" of length 2.\n Example 3:\n Input: s = \"aaaaaaaaaaa\", k = 0\n Output: 3\n Explanation: Since k is zero, we cannot delete anything. The compressed string is \"a11\" of length 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1515, - "title": "Best Position for a Service Centre", - "question": "class Solution:\n def getMinDistSum(self, positions: List[List[int]]) -> float:\n \"\"\"\n 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.\n Given an array positions where positions[i] = [xi, yi] is the position of the ith customer on the map, return the minimum sum of the euclidean distances to all customers.\n In other words, you need to choose the position of the service center [xcentre, ycentre] such that the following formula is minimized:\n Answers within 10-5 of the actual value will be accepted.\n Example 1:\n Input: positions = [[0,1],[1,0],[1,2],[2,1]]\n Output: 4.00000\n Explanation: As shown, you can see that choosing [xcentre, ycentre] = [1, 1] will make the distance to each customer = 1, the sum of all distances is 4 which is the minimum possible we can achieve.\n Example 2:\n Input: positions = [[1,1],[3,3]]\n Output: 2.82843\n Explanation: The minimum possible sum of distances = sqrt(2) + sqrt(2) = 2.82843\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1518, - "title": "Water Bottles", - "question": "class Solution:\n def numWaterBottles(self, numBottles: int, numExchange: int) -> int:\n \"\"\"\n 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.\n The operation of drinking a full water bottle turns it into an empty bottle.\n Given the two integers numBottles and numExchange, return the maximum number of water bottles you can drink.\n Example 1:\n Input: numBottles = 9, numExchange = 3\n Output: 13\n Explanation: You can exchange 3 empty bottles to get 1 full water bottle.\n Number of water bottles you can drink: 9 + 3 + 1 = 13.\n Example 2:\n Input: numBottles = 15, numExchange = 4\n Output: 19\n Explanation: You can exchange 4 empty bottles to get 1 full water bottle. \n Number of water bottles you can drink: 15 + 3 + 1 = 19.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1519, - "title": "Number of Nodes in the Sub-Tree With the Same Label", - "question": "class Solution:\n def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]:\n \"\"\"\n 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]).\n The 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.\n Return 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.\n A subtree of a tree T is the tree consisting of a node in T and all of its descendant nodes.\n Example 1:\n Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], labels = \"abaedcd\"\n Output: [2,1,1,1,1,1,1]\n Explanation: 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.\n Node 1 has a label 'b'. The sub-tree of node 1 contains nodes 1,4 and 5, as nodes 4 and 5 have different labels than node 1, the answer is just 1 (the node itself).\n Example 2:\n Input: n = 4, edges = [[0,1],[1,2],[0,3]], labels = \"bbbb\"\n Output: [4,2,1,1]\n Explanation: The sub-tree of node 2 contains only node 2, so the answer is 1.\n The sub-tree of node 3 contains only node 3, so the answer is 1.\n The sub-tree of node 1 contains nodes 1 and 2, both have label 'b', thus the answer is 2.\n The sub-tree of node 0 contains nodes 0, 1, 2 and 3, all with label 'b', thus the answer is 4.\n Example 3:\n Input: n = 5, edges = [[0,1],[0,2],[1,3],[0,4]], labels = \"aabab\"\n Output: [3,2,1,1,1]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1520, - "title": "Maximum Number of Non-Overlapping Substrings", - "question": "class Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n \"\"\"\n Given a string s of lowercase letters, you need to find the maximum number of non-empty substrings of s that meet the following conditions:\n The substrings do not overlap, that is for any two substrings s[i..j] and s[x..y], either j < x or i > y is true.\n A substring that contains a certain character c must also contain all occurrences of c.\n Find the maximum number of substrings that meet the above conditions. If there are multiple solutions with the same number of substrings, return the one with minimum total length. It can be shown that there exists a unique solution of minimum total length.\n Notice that you can return the substrings in any order.\n Example 1:\n Input: s = \"adefaddaccc\"\n Output: [\"e\",\"f\",\"ccc\"]\n Explanation: The following are all the possible substrings that meet the conditions:\n [\n \"adefaddaccc\"\n \"adefadda\",\n \"ef\",\n \"e\",\n \"f\",\n \"ccc\",\n ]\n If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose \"adefadda\", we are left with \"ccc\" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose \"ef\" since it can be split into two. Therefore, the optimal way is to choose [\"e\",\"f\",\"ccc\"] which gives us 3 substrings. No other solution of the same number of substrings exist.\n Example 2:\n Input: s = \"abbaccd\"\n Output: [\"d\",\"bb\",\"cc\"]\n Explanation: Notice that while the set of substrings [\"d\",\"abba\",\"cc\"] also has length 3, it's considered incorrect since it has larger total length.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1521, - "title": "Find a Value of a Mysterious Function Closest to Target", - "question": "class Solution:\n def closestToTarget(self, arr: List[int], target: int) -> int:\n \"\"\"\n Winston was given the above mysterious function func. He has an integer array arr and an integer target and he wants to find the values l and r that make the value |func(arr, l, r) - target| minimum possible.\n Return the minimum possible value of |func(arr, l, r) - target|.\n Notice that func should be called with the values l and r where 0 <= l, r < arr.length.\n Example 1:\n Input: arr = [9,12,3,7,15], target = 5\n Output: 2\n Explanation: Calling func with all the pairs of [l,r] = [[0,0],[1,1],[2,2],[3,3],[4,4],[0,1],[1,2],[2,3],[3,4],[0,2],[1,3],[2,4],[0,3],[1,4],[0,4]], Winston got the following results [9,12,3,7,15,8,0,3,7,0,0,3,0,0,0]. The value closest to 5 is 7 and 3, thus the minimum difference is 2.\n Example 2:\n Input: arr = [1000000,1000000,1000000], target = 1\n Output: 999999\n Explanation: Winston called the func with all possible values of [l,r] and he always got 1000000, thus the min difference is 999999.\n Example 3:\n Input: arr = [1,2,4,8,16], target = 0\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1539, - "title": "Kth Missing Positive Number", - "question": "class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n \"\"\"\n Given an array arr of positive integers sorted in a strictly increasing order, and an integer k.\n Return the kth positive integer that is missing from this array.\n Example 1:\n Input: arr = [2,3,4,7,11], k = 5\n Output: 9\n Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.\n Example 2:\n Input: arr = [1,2,3,4], k = 2\n Output: 6\n Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1540, - "title": "Can Convert String in K Moves", - "question": "class Solution:\n def canConvertString(self, s: str, t: str, k: int) -> bool:\n \"\"\"\n Given two strings s and t, your goal is to convert s into t in k moves or less.\n During the ith (1 <= i <= k) move you can:\n Choose 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.\n Do nothing.\n Shifting 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.\n Remember that any index j can be picked at most once.\n Return true if it's possible to convert s into t in no more than k moves, otherwise return false.\n Example 1:\n Input: s = \"input\", t = \"ouput\", k = 9\n Output: true\n Explanation: In the 6th move, we shift 'i' 6 times to get 'o'. And in the 7th move we shift 'n' to get 'u'.\n Example 2:\n Input: s = \"abc\", t = \"bcd\", k = 10\n Output: false\n Explanation: We need to shift each character in s one time to convert it into t. We can shift 'a' to 'b' during the 1st move. However, there is no way to shift the other characters in the remaining moves to obtain t from s.\n Example 3:\n Input: s = \"aab\", t = \"bbb\", k = 27\n Output: true\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1541, - "title": "Minimum Insertions to Balance a Parentheses String", - "question": "class Solution:\n def minInsertions(self, s: str) -> int:\n \"\"\"\n Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if:\n Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.\n Left parenthesis '(' must go before the corresponding two consecutive right parenthesis '))'.\n In other words, we treat '(' as an opening parenthesis and '))' as a closing parenthesis.\n For example, \"())\", \"())(())))\" and \"(())())))\" are balanced, \")()\", \"()))\" and \"(()))\" are not balanced.\n You can insert the characters '(' and ')' at any position of the string to balance it if needed.\n Return the minimum number of insertions needed to make s balanced.\n Example 1:\n Input: s = \"(()))\"\n Output: 1\n Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be \"(())))\" which is balanced.\n Example 2:\n Input: s = \"())\"\n Output: 0\n Explanation: The string is already balanced.\n Example 3:\n Input: s = \"))())(\"\n Output: 3\n Explanation: Add '(' to match the first '))', Add '))' to match the last '('.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1546, - "title": "Maximum Number of Non-Overlapping Subarrays With Sum Equals Target", - "question": "class Solution:\n def maxNonOverlapping(self, nums: List[int], target: int) -> int:\n \"\"\"\n 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:\n Input: nums = [1,1,1,1,1], target = 2\n Output: 2\n Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).\n Example 2:\n Input: nums = [-1,3,5,1,4,2,-9], target = 6\n Output: 2\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1528, - "title": "Shuffle String", - "question": "class Solution:\r\n def restoreString(self, s: str, indices: List[int]) -> str:\n \"\"\"\n 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.\n Return the shuffled string.\n Example 1:\n Input: s = \"codeleet\", indices = [4,5,6,7,0,2,1,3]\n Output: \"leetcode\"\n Explanation: As shown, \"codeleet\" becomes \"leetcode\" after shuffling.\n Example 2:\n Input: s = \"abc\", indices = [0,1,2]\n Output: \"abc\"\n Explanation: After shuffling, each character remains in its position.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1529, - "title": "Minimum Suffix Flips", - "question": "class Solution:\n def minFlips(self, target: str) -> int:\n \"\"\"\n 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.\n In 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'.\n Return the minimum number of operations needed to make s equal to target.\n Example 1:\n Input: target = \"10111\"\n Output: 3\n Explanation: Initially, s = \"00000\".\n Choose index i = 2: \"00000\" -> \"00111\"\n Choose index i = 0: \"00111\" -> \"11000\"\n Choose index i = 1: \"11000\" -> \"10111\"\n We need at least 3 flip operations to form target.\n Example 2:\n Input: target = \"101\"\n Output: 3\n Explanation: Initially, s = \"000\".\n Choose index i = 0: \"000\" -> \"111\"\n Choose index i = 1: \"111\" -> \"100\"\n Choose index i = 2: \"100\" -> \"101\"\n We need at least 3 flip operations to form target.\n Example 3:\n Input: target = \"00000\"\n Output: 0\n Explanation: We do not need any operations since the initial s already equals target.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1530, - "title": "Number of Good Leaf Nodes Pairs", - "question": "class Solution:\n def countPairs(self, root: TreeNode, distance: int) -> int:\n \"\"\"\n 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.\n Return the number of good leaf node pairs in the tree.\n Example 1:\n Input: root = [1,2,3,null,4], distance = 3\n Output: 1\n Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.\n Example 2:\n Input: root = [1,2,3,4,5,6,7], distance = 3\n Output: 2\n Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.\n Example 3:\n Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3\n Output: 1\n Explanation: The only good pair is [2,5].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1534, - "title": "Count Good Triplets", - "question": "class Solution:\n def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:\n \"\"\"\n Given an array of integers arr, and three integers a, b and c. You need to find the number of good triplets.\r\n A triplet (arr[i], arr[j], arr[k]) is good if the following conditions are true:\r\n 0 <= i < j < k < arr.length\r\n |arr[i] - arr[j]| <= a\r\n |arr[j] - arr[k]| <= b\r\n |arr[i] - arr[k]| <= c\r\n Where |x| denotes the absolute value of x.\r\n Return the number of good triplets.\r\n Example 1:\r\n Input: arr = [3,0,1,1,9,7], a = 7, b = 2, c = 3\r\n Output: 4\r\n Explanation: There are 4 good triplets: [(3,0,1), (3,0,1), (3,1,1), (0,1,1)].\r\n Example 2:\r\n Input: arr = [1,1,2,2,3], a = 0, b = 0, c = 1\r\n Output: 0\r\n Explanation: No triplet satisfies all conditions.\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1535, - "title": "Find the Winner of an Array Game", - "question": "class Solution:\n def getWinner(self, arr: List[int], k: int) -> int:\n \"\"\"\n Given an integer array arr of distinct integers and an integer k.\n A 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.\n Return the integer which will win the game.\n It is guaranteed that there will be a winner of the game.\n Example 1:\n Input: arr = [2,1,3,5,4,6,7], k = 2\n Output: 5\n Explanation: Let's see the rounds of the game:\n Round | 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\n So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.\n Example 2:\n Input: arr = [3,2,1], k = 10\n Output: 3\n Explanation: 3 will win the first 10 rounds consecutively.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1536, - "title": "Minimum Swaps to Arrange a Binary Grid", - "question": "class Solution:\n def minSwaps(self, grid: List[List[int]]) -> int:\n \"\"\"\n Given an n x n binary grid, in one step you can choose two adjacent rows of the grid and swap them.\n A grid is said to be valid if all the cells above the main diagonal are zeros.\n Return the minimum number of steps needed to make the grid valid, or -1 if the grid cannot be valid.\n The main diagonal of a grid is the diagonal that starts at cell (1, 1) and ends at cell (n, n).\n Example 1:\n Input: grid = [[0,0,1],[1,1,0],[1,0,0]]\n Output: 3\n Example 2:\n Input: grid = [[0,1,1,0],[0,1,1,0],[0,1,1,0],[0,1,1,0]]\n Output: -1\n Explanation: All rows are similar, swaps have no effect on the grid.\n Example 3:\n Input: grid = [[1,0,0],[1,1,0],[1,1,1]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1537, - "title": "Get the Maximum Score", - "question": "class Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n You are given two sorted arrays of distinct integers nums1 and nums2.\n A valid path is defined as follows:\n Choose array nums1 or nums2 to traverse (from index-0).\n Traverse the current array from left to right.\n If you are reading any value that is present in nums1 and nums2 you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path).\n The score is defined as the sum of uniques values in a valid path.\n Return 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:\n Input: nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]\n Output: 30\n Explanation: Valid paths:\n [2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10], (starting from nums1)\n [4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10] (starting from nums2)\n The maximum is obtained with the path in green [2,4,6,8,10].\n Example 2:\n Input: nums1 = [1,3,5,7,9], nums2 = [3,5,100]\n Output: 109\n Explanation: Maximum sum is obtained with the path [1,3,5,100].\n Example 3:\n Input: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]\n Output: 40\n Explanation: There are no common elements between nums1 and nums2.\n Maximum sum is obtained with the path [6,7,8,9,10].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1556, - "title": "Thousand Separator", - "question": "class Solution:\n def thousandSeparator(self, n: int) -> str:\n \"\"\"\n Given an integer n, add a dot (\".\") as the thousands separator and return it in string format.\n Example 1:\n Input: n = 987\n Output: \"987\"\n Example 2:\n Input: n = 1234\n Output: \"1.234\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1557, - "title": "Minimum Number of Vertices to Reach All Nodes", - "question": "class Solution:\n def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\r\n Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.\r\n Notice that you can return the vertices in any order.\r\n Example 1:\r\n Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]\r\n Output: [0,3]\r\n Explanation: 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].\r\n Example 2:\r\n Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]]\r\n Output: [0,2,3]\r\n Explanation: 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.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1558, - "title": "Minimum Numbers of Function Calls to Make Target Array", - "question": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n You want to use the modify function to covert arr to nums using the minimum number of calls.\n Return the minimum number of function calls to make nums from arr.\n The test cases are generated so that the answer fits in a 32-bit signed integer.\n Example 1:\n Input: nums = [1,5]\n Output: 5\n Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).\n Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).\n Increment by 1 (both elements) [0, 4] -> [1, 4] -> [1, 5] (2 operations).\n Total of operations: 1 + 2 + 2 = 5.\n Example 2:\n Input: nums = [2,2]\n Output: 3\n Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).\n Double all the elements: [1, 1] -> [2, 2] (1 operation).\n Total of operations: 2 + 1 = 3.\n Example 3:\n Input: nums = [4,2,5]\n Output: 6\n Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1559, - "title": "Detect Cycles in 2D Grid", - "question": "class Solution:\n def containsCycle(self, grid: List[List[str]]) -> bool:\n \"\"\"\n Given a 2D array of characters grid of size m x n, you need to find if there exists any cycle consisting of the same value in grid.\n A cycle is a path of length 4 or more in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the same value of the current cell.\n Also, you cannot move to the cell that you visited in your last move. For example, the cycle (1, 1) -> (1, 2) -> (1, 1) is invalid because from (1, 2) we visited (1, 1) which was the last visited cell.\n Return true if any cycle of the same value exists in grid, otherwise, return false.\n Example 1:\n Input: grid = [[\"a\",\"a\",\"a\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"b\",\"b\",\"a\"],[\"a\",\"a\",\"a\",\"a\"]]\n Output: true\n Explanation: There are two valid cycles shown in different colors in the image below:\n Example 2:\n Input: grid = [[\"c\",\"c\",\"c\",\"a\"],[\"c\",\"d\",\"c\",\"c\"],[\"c\",\"c\",\"e\",\"c\"],[\"f\",\"c\",\"c\",\"c\"]]\n Output: true\n Explanation: There is only one valid cycle highlighted in the image below:\n Example 3:\n Input: grid = [[\"a\",\"b\",\"b\"],[\"b\",\"z\",\"b\"],[\"b\",\"b\",\"a\"]]\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1544, - "title": "Make The String Great", - "question": "class Solution:\n def makeGood(self, s: str) -> str:\n \"\"\"\n Given a string s of lower and upper case English letters.\n A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:\n 0 <= i <= s.length - 2\n s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.\n To 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.\n Return the string after making it good. The answer is guaranteed to be unique under the given constraints.\n Notice that an empty string is also good.\n Example 1:\n Input: s = \"leEeetcode\"\n Output: \"leetcode\"\n Explanation: In the first step, either you choose i = 1 or i = 2, both will result \"leEeetcode\" to be reduced to \"leetcode\".\n Example 2:\n Input: s = \"abBAcC\"\n Output: \"\"\n Explanation: We have many possible scenarios, and all lead to the same answer. For example:\n \"abBAcC\" --> \"aAcC\" --> \"cC\" --> \"\"\n \"abBAcC\" --> \"abBA\" --> \"aA\" --> \"\"\n Example 3:\n Input: s = \"s\"\n Output: \"s\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1545, - "title": "Find Kth Bit in Nth Binary String", - "question": "class Solution:\n def findKthBit(self, n: int, k: int) -> str:\n \"\"\"\n Given two positive integers n and k, the binary string Sn is formed as follows:\n S1 = \"0\"\n Si = Si - 1 + \"1\" + reverse(invert(Si - 1)) for i > 1\n Where + 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).\n For example, the first four strings in the above sequence are:\n S1 = \"0\"\n S2 = \"011\"\n S3 = \"0111001\"\n S4 = \"011100110110001\"\n Return the kth bit in Sn. It is guaranteed that k is valid for the given n.\n Example 1:\n Input: n = 3, k = 1\n Output: \"0\"\n Explanation: S3 is \"0111001\".\n The 1st bit is \"0\".\n Example 2:\n Input: n = 4, k = 11\n Output: \"1\"\n Explanation: S4 is \"011100110110001\".\n The 11th bit is \"1\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1542, - "title": "Find Longest Awesome Substring", - "question": "class Solution:\n def longestAwesome(self, s: str) -> int:\n \"\"\"\n 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.\n Return the length of the maximum length awesome substring of s.\n Example 1:\n Input: s = \"3242415\"\n Output: 5\n Explanation: \"24241\" is the longest awesome substring, we can form the palindrome \"24142\" with some swaps.\n Example 2:\n Input: s = \"12345678\"\n Output: 1\n Example 3:\n Input: s = \"213123\"\n Output: 6\n Explanation: \"213123\" is the longest awesome substring, we can form the palindrome \"231132\" with some swaps.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1547, - "title": "Minimum Cost to Cut a Stick", - "question": "class Solution:\n def minCost(self, n: int, cuts: List[int]) -> int:\n \"\"\"\n Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows:\n Given an integer array cuts where cuts[i] denotes a position you should perform a cut at.\n You should perform the cuts in order, you can change the order of the cuts as you wish.\n The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation.\n Return the minimum total cost of the cuts.\n Example 1:\n Input: n = 7, cuts = [1,3,4,5]\n Output: 16\n Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario:\n The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20.\n Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).\n Example 2:\n Input: n = 9, cuts = [5,6,1,4,2]\n Output: 22\n Explanation: If you try the given cuts ordering the cost will be 25.\n There are much ordering with total cost <= 25, for example, the order [4, 6, 5, 2, 1] has total cost = 22 which is the minimum possible.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1551, - "title": "Minimum Operations to Make Array Equal", - "question": "class Solution:\n def minOperations(self, n: int) -> int:\n \"\"\"\n 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).\n In 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.\n Given 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:\n Input: n = 3\n Output: 2\n Explanation: arr = [1, 3, 5]\n First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]\n In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].\n Example 2:\n Input: n = 6\n Output: 9\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1552, - "title": "Magnetic Force Between Two Balls", - "question": "class Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n \"\"\"\n 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.\n Rick stated that magnetic force between two different balls at positions x and y is |x - y|.\n Given the integer array position and the integer m. Return the required force.\n Example 1:\n Input: position = [1,2,3,4,7], m = 3\n Output: 3\n Explanation: Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.\n Example 2:\n Input: position = [5,4,3,2,1,1000000000], m = 2\n Output: 999999999\n Explanation: We can use baskets 1 and 1000000000.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1553, - "title": "Minimum Number of Days to Eat N Oranges", - "question": "class Solution:\n def minDays(self, n: int) -> int:\n \"\"\"\n There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:\n Eat one orange.\n If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.\n If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.\n You can only choose one of the actions per day.\n Given the integer n, return the minimum number of days to eat n oranges.\n Example 1:\n Input: n = 10\n Output: 4\n Explanation: You have 10 oranges.\n Day 1: Eat 1 orange, 10 - 1 = 9. \n Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)\n Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. \n Day 4: Eat the last orange 1 - 1 = 0.\n You need at least 4 days to eat the 10 oranges.\n Example 2:\n Input: n = 6\n Output: 3\n Explanation: You have 6 oranges.\n Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).\n Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)\n Day 3: Eat the last orange 1 - 1 = 0.\n You need at least 3 days to eat the 6 oranges.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1572, - "title": "Matrix Diagonal Sum", - "question": "class Solution:\n def diagonalSum(self, mat: List[List[int]]) -> int:\n \"\"\"\n Given a square matrix mat, return the sum of the matrix diagonals.\n Only 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:\n Input: mat = [[1,2,3],\n [4,5,6],\n [7,8,9]]\n Output: 25\n Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25\n Notice that element mat[1][1] = 5 is counted only once.\n Example 2:\n Input: mat = [[1,1,1,1],\n [1,1,1,1],\n [1,1,1,1],\n [1,1,1,1]]\n Output: 8\n Example 3:\n Input: mat = [[5]]\n Output: 5\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1573, - "title": "Number of Ways to Split a String", - "question": "class Solution:\n def numWays(self, s: str) -> int:\n \"\"\"\n Given a binary string s, you can split s into 3 non-empty strings s1, s2, and s3 where s1 + s2 + s3 = s.\n Return 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:\n Input: s = \"10101\"\n Output: 4\n Explanation: There are four ways to split s in 3 parts where each part contain the same number of letters '1'.\n \"1|010|1\"\n \"1|01|01\"\n \"10|10|1\"\n \"10|1|01\"\n Example 2:\n Input: s = \"1001\"\n Output: 0\n Example 3:\n Input: s = \"0000\"\n Output: 3\n Explanation: There are three ways to split s in 3 parts.\n \"0|0|00\"\n \"0|00|0\"\n \"00|0|0\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1574, - "title": "Shortest Subarray to be Removed to Make Array Sorted", - "question": "class Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n \"\"\"\n Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing.\n Return the length of the shortest subarray to remove.\n A subarray is a contiguous subsequence of the array.\n Example 1:\n Input: arr = [1,2,3,10,4,2,3,5]\n Output: 3\n Explanation: 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.\n Another correct solution is to remove the subarray [3,10,4].\n Example 2:\n Input: arr = [5,4,3,2,1]\n Output: 4\n Explanation: Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].\n Example 3:\n Input: arr = [1,2,3]\n Output: 0\n Explanation: The array is already non-decreasing. We do not need to remove any elements.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1575, - "title": "Count All Possible Routes", - "question": "class Solution:\n def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:\n \"\"\"\n You are given an array of distinct positive integers locations where locations[i] represents the position of city i. You are also given integers start, finish and fuel representing the starting city, ending city, and the initial amount of fuel you have, respectively.\n At each step, if you are at city i, you can pick any city j such that j != i and 0 <= j < locations.length and move to city j. Moving from city i to city j reduces the amount of fuel you have by |locations[i] - locations[j]|. Please notice that |x| denotes the absolute value of x.\n Notice that fuel cannot become negative at any point in time, and that you are allowed to visit any city more than once (including start and finish).\n Return 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:\n Input: locations = [2,3,6,8,4], start = 1, finish = 3, fuel = 5\n Output: 4\n Explanation: The following are all possible routes, each uses 5 units of fuel:\n 1 -> 3\n 1 -> 2 -> 3\n 1 -> 4 -> 3\n 1 -> 4 -> 2 -> 3\n Example 2:\n Input: locations = [4,3,1], start = 1, finish = 0, fuel = 6\n Output: 5\n Explanation: The following are all possible routes:\n 1 -> 0, used fuel = 1\n 1 -> 2 -> 0, used fuel = 5\n 1 -> 2 -> 1 -> 0, used fuel = 5\n 1 -> 0 -> 1 -> 0, used fuel = 3\n 1 -> 0 -> 1 -> 0 -> 1 -> 0, used fuel = 5\n Example 3:\n Input: locations = [5,2,1], start = 0, finish = 2, fuel = 3\n Output: 0\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1560, - "title": "Most Visited Sector in a Circular Track", - "question": "class Solution:\n def mostVisited(self, n: int, rounds: List[int]) -> List[int]:\n \"\"\"\n 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]\n Return an array of the most visited sectors sorted in ascending order.\n Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).\n Example 1:\n Input: n = 4, rounds = [1,3,1,2]\n Output: [1,2]\n Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:\n 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)\n We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.\n Example 2:\n Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]\n Output: [2]\n Example 3:\n Input: n = 7, rounds = [1,3,5,7]\n Output: [1,2,3,4,5,6,7]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1561, - "title": "Maximum Number of Coins You Can Get", - "question": "class Solution:\n def maxCoins(self, piles: List[int]) -> int:\n \"\"\"\n There are 3n piles of coins of varying size, you and your friends will take piles of coins as follows:\n In each step, you will choose any 3 piles of coins (not necessarily consecutive).\n Of your choice, Alice will pick the pile with the maximum number of coins.\n You will pick the next pile with the maximum number of coins.\n Your friend Bob will pick the last pile.\n Repeat until there are no more piles of coins.\n Given an array of integers piles where piles[i] is the number of coins in the ith pile.\n Return the maximum number of coins that you can have.\n Example 1:\n Input: piles = [2,4,1,2,7,8]\n Output: 9\n Explanation: Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with 7 coins and Bob the last one.\n Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with 2 coins and Bob the last one.\n The maximum number of coins which you can have are: 7 + 2 = 9.\n On 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.\n Example 2:\n Input: piles = [2,4,5]\n Output: 4\n Example 3:\n Input: piles = [9,8,7,6,5,1,2,3,4]\n Output: 18\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1562, - "title": "Find Latest Group of Size M", - "question": "class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n \"\"\"\n Given an array arr that represents a permutation of numbers from 1 to n.\n You 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.\n You 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.\n Return 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:\n Input: arr = [3,5,1,2,4], m = 1\n Output: 4\n Explanation: \n Step 1: \"00100\", groups: [\"1\"]\n Step 2: \"00101\", groups: [\"1\", \"1\"]\n Step 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\n Step 4: \"11101\", groups: [\"111\", \"1\"]\n Step 5: \"11111\", groups: [\"11111\"]\n The latest step at which there exists a group of size 1 is step 4.\n Example 2:\n Input: arr = [3,1,5,4,2], m = 2\n Output: -1\n Explanation: \n Step 1: \"00100\", groups: [\"1\"]\n Step 2: \"10100\", groups: [\"1\", \"1\"]\n Step 3: \"10101\", groups: [\"1\", \"1\", \"1\"]\n Step 4: \"10111\", groups: [\"1\", \"111\"]\n Step 5: \"11111\", groups: [\"11111\"]\n No group of size 2 exists during any step.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1563, - "title": "Stone Game V", - "question": "class Solution:\n def stoneGameV(self, stoneValue: List[int]) -> int:\n \"\"\"\n There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.\n In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.\n The game ends when there is only one stone remaining. Alice's is initially zero.\n Return the maximum score that Alice can obtain.\n Example 1:\n Input: stoneValue = [6,2,3,4,5,5]\n Output: 18\n Explanation: In the first round, Alice divides the row to [6,2,3], [4,5,5]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.\n In the second round Alice divides the row to [6], [2,3]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).\n The last round Alice has only one choice to divide the row which is [2], [3]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.\n Example 2:\n Input: stoneValue = [7,7,7,7,7,7,7]\n Output: 28\n Example 3:\n Input: stoneValue = [4]\n Output: 0\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1566, - "title": "Detect Pattern of Length M Repeated K or More Times", - "question": "class Solution:\n def containsPattern(self, arr: List[int], m: int, k: int) -> bool:\n \"\"\"\n Given an array of positive integers arr, find a pattern of length m that is repeated k or more times.\n A 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.\n Return true if there exists a pattern of length m that is repeated k or more times, otherwise return false.\n Example 1:\n Input: arr = [1,2,4,4,4,4], m = 1, k = 3\n Output: true\n Explanation: The pattern (4) of length 1 is repeated 4 consecutive times. Notice that pattern can be repeated k or more times but not less.\n Example 2:\n Input: arr = [1,2,1,2,1,1,1,3], m = 2, k = 2\n Output: true\n Explanation: The pattern (1,2) of length 2 is repeated 2 consecutive times. Another valid pattern (2,1) is also repeated 2 times.\n Example 3:\n Input: arr = [1,2,1,2,1,3], m = 2, k = 3\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1567, - "title": "Maximum Length of Subarray With Positive Product", - "question": "class Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n \"\"\"\n Given an array of integers nums, find the maximum length of a subarray where the product of all its elements is positive.\n A subarray of an array is a consecutive sequence of zero or more values taken out of that array.\n Return the maximum length of a subarray with positive product.\n Example 1:\n Input: nums = [1,-2,-3,4]\n Output: 4\n Explanation: The array nums already has a positive product of 24.\n Example 2:\n Input: nums = [0,1,-2,-3,-4]\n Output: 3\n Explanation: The longest subarray with positive product is [1,-2,-3] which has a product of 6.\n Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive.\n Example 3:\n Input: nums = [-1,-2,-3,0,1]\n Output: 2\n Explanation: The longest subarray with positive product is [-1,-2] or [-2,-3].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1568, - "title": "Minimum Number of Days to Disconnect Island", - "question": "class Solution:\n def minDays(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n The grid is said to be connected if we have exactly one island, otherwise is said disconnected.\n In one day, we are allowed to change any single land cell (1) into a water cell (0).\n Return the minimum number of days to disconnect the grid.\n Example 1:\n Input: grid = [[0,1,1,0],[0,1,1,0],[0,0,0,0]]\n Output: 2\n Explanation: We need at least 2 days to get a disconnected grid.\n Change land grid[1][1] and grid[0][2] to water and get 2 disconnected island.\n Example 2:\n Input: grid = [[1,1]]\n Output: 2\n Explanation: Grid of full water is also disconnected ([[1,1]] -> [[0,0]]), 0 islands.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1569, - "title": "Number of Ways to Reorder Array to Get Same BST", - "question": "class Solution:\n def numOfWays(self, nums: List[int]) -> int:\n \"\"\"\n Given an array nums that represents a permutation of integers from 1 to n. We are going to construct a binary search tree (BST) by inserting the elements of nums in order into an initially empty BST. Find the number of different ways to reorder nums so that the constructed BST is identical to that formed from the original array nums.\n For example, given nums = [2,1,3], we will have 2 as the root, 1 as a left child, and 3 as a right child. The array [2,3,1] also yields the same BST but [3,2,1] yields a different BST.\n Return the number of ways to reorder nums such that the BST formed is identical to the original BST formed from nums.\n Since the answer may be very large, return it modulo 109 + 7.\n Example 1:\n Input: nums = [2,1,3]\n Output: 1\n Explanation: We can reorder nums to be [2,3,1] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.\n Example 2:\n Input: nums = [3,4,5,1,2]\n Output: 5\n Explanation: The following 5 arrays will yield the same BST: \n [3,1,2,4,5]\n [3,1,4,2,5]\n [3,1,4,5,2]\n [3,4,1,2,5]\n [3,4,1,5,2]\n Example 3:\n Input: nums = [1,2,3]\n Output: 0\n Explanation: There are no other orderings of nums that will yield the same BST.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1588, - "title": "Sum of All Odd Length Subarrays", - "question": "class Solution:\n def sumOddLengthSubarrays(self, arr: List[int]) -> int:\n \"\"\"\n Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr.\n A subarray is a contiguous subsequence of the array.\n Example 1:\n Input: arr = [1,4,2,5,3]\n Output: 58\n Explanation: 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\n If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58\n Example 2:\n Input: arr = [1,2]\n Output: 3\n Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.\n Example 3:\n Input: arr = [10,11,12]\n Output: 66\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1590, - "title": "Make Sum Divisible by P", - "question": "class Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n \"\"\"\n 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.\n Return the length of the smallest subarray that you need to remove, or -1 if it's impossible.\n A subarray is defined as a contiguous block of elements in the array.\n Example 1:\n Input: nums = [3,1,4,2], p = 6\n Output: 1\n Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6.\n Example 2:\n Input: nums = [6,3,5,2], p = 9\n Output: 2\n Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9.\n Example 3:\n Input: nums = [1,2,3], p = 3\n Output: 0\n Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1589, - "title": "Maximum Sum Obtained of Any Permutation", - "question": "class Solution:\n def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the maximum total sum of all requests among all permutations of nums.\n Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\n Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]\n Output: 19\n Explanation: One permutation of nums is [2,1,3,4,5] with the following result: \n requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8\n requests[1] -> nums[0] + nums[1] = 2 + 1 = 3\n Total sum: 8 + 3 = 11.\n A permutation with a higher total sum is [3,5,4,2,1] with the following result:\n requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11\n requests[1] -> nums[0] + nums[1] = 3 + 5 = 8\n Total sum: 11 + 8 = 19, which is the best that you can do.\n Example 2:\n Input: nums = [1,2,3,4,5,6], requests = [[0,1]]\n Output: 11\n Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].\n Example 3:\n Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]\n Output: 47\n Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1591, - "title": "Strange Printer II", - "question": "class Solution:\n def isPrintable(self, targetGrid: List[List[int]]) -> bool:\n \"\"\"\n There is a strange printer with the following two special requirements:\n On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle.\n Once the printer has used a color for the above operation, the same color cannot be used again.\n You are given a m x n matrix targetGrid, where targetGrid[row][col] is the color in the position (row, col) of the grid.\n Return true if it is possible to print the matrix targetGrid, otherwise, return false.\n Example 1:\n Input: targetGrid = [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]]\n Output: true\n Example 2:\n Input: targetGrid = [[1,1,1,1],[1,1,3,3],[1,1,3,4],[5,5,1,4]]\n Output: true\n Example 3:\n Input: targetGrid = [[1,2,1],[2,1,2],[1,2,1]]\n Output: false\n Explanation: It is impossible to form targetGrid because it is not allowed to print the same color in different turns.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1576, - "title": "Replace All ?\"s to Avoid Consecutive Repeating Characters", - "question": "class Solution:\n def modifyString(self, s: str) -> str:\n \"\"\"\n 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.\n It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.\n Return 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:\n Input: s = \"?zs\"\n Output: \"azs\"\n Explanation: There are 25 solutions for this problem. From \"azs\" to \"yzs\", all are valid. Only \"z\" is an invalid modification as the string will consist of consecutive repeating characters in \"zzs\".\n Example 2:\n Input: s = \"ubv?w\"\n Output: \"ubvaw\"\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1577, - "title": "Number of Ways Where Square of Number Is Equal to Product of Two Numbers", - "question": "class Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n Given two arrays of integers nums1 and nums2, return the number of triplets formed (type 1 and type 2) under the following rules:\n Type 1: Triplet (i, j, k) if nums1[i]2 == nums2[j] * nums2[k] where 0 <= i < nums1.length and 0 <= j < k < nums2.length.\n Type 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:\n Input: nums1 = [7,4], nums2 = [5,2,8,9]\n Output: 1\n Explanation: Type 1: (1, 1, 2), nums1[1]2 = nums2[1] * nums2[2]. (42 = 2 * 8). \n Example 2:\n Input: nums1 = [1,1], nums2 = [1,1,1]\n Output: 9\n Explanation: All Triplets are valid, because 12 = 1 * 1.\n Type 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].\n Type 2: (0,0,1), (1,0,1), (2,0,1). nums2[i]2 = nums1[j] * nums1[k].\n Example 3:\n Input: nums1 = [7,7,8,3], nums2 = [1,2,9,7]\n Output: 2\n Explanation: There are 2 valid triplets.\n Type 1: (3,0,2). nums1[3]2 = nums2[0] * nums2[2].\n Type 2: (3,0,1). nums2[3]2 = nums1[0] * nums1[1].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1578, - "title": "Minimum Time to Make Rope Colorful", - "question": "class Solution:\n def minCost(self, colors: str, neededTime: List[int]) -> int:\n \"\"\"\n 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.\n Alice 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.\n Return the minimum time Bob needs to make the rope colorful.\n Example 1:\n Input: colors = \"abaac\", neededTime = [1,2,3,4,5]\n Output: 3\n Explanation: In the above image, 'a' is blue, 'b' is red, and 'c' is green.\n Bob can remove the blue balloon at index 2. This takes 3 seconds.\n There are no longer two consecutive balloons of the same color. Total time = 3.\n Example 2:\n Input: colors = \"abc\", neededTime = [1,2,3]\n Output: 0\n Explanation: The rope is already colorful. Bob does not need to remove any balloons from the rope.\n Example 3:\n Input: colors = \"aabaa\", neededTime = [1,2,3,4,1]\n Output: 2\n Explanation: Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.\n There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1579, - "title": "Remove Max Number of Edges to Keep Graph Fully Traversable", - "question": "class Solution:\n def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int:\n \"\"\"\n Alice and Bob have an undirected graph of n nodes and three types of edges:\n Type 1: Can be traversed by Alice only.\n Type 2: Can be traversed by Bob only.\n Type 3: Can be traversed by both Alice and Bob.\n Given an array edges where edges[i] = [typei, ui, vi] represents a bidirectional edge of type typei between nodes ui and vi, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes.\n Return the maximum number of edges you can remove, or return -1 if Alice and Bob cannot fully traverse the graph.\n Example 1:\n Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,3],[1,2,4],[1,1,2],[2,3,4]]\n Output: 2\n Explanation: If we remove the 2 edges [1,1,2] and [1,1,3]. The graph will still be fully traversable by Alice and Bob. Removing any additional edge will not make it so. So the maximum number of edges we can remove is 2.\n Example 2:\n Input: n = 4, edges = [[3,1,2],[3,2,3],[1,1,4],[2,1,4]]\n Output: 0\n Explanation: Notice that removing any edge will not make the graph fully traversable by Alice and Bob.\n Example 3:\n Input: n = 4, edges = [[3,2,3],[1,1,2],[2,3,4]]\n Output: -1\n Explanation: In the current graph, Alice cannot reach node 4 from the other nodes. Likewise, Bob cannot reach 1. Therefore it's impossible to make the graph fully traversable.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1582, - "title": "Special Positions in a Binary Matrix", - "question": "class Solution:\n def numSpecial(self, mat: List[List[int]]) -> int:\n \"\"\"\n Given an m x n binary matrix mat, return the number of special positions in mat.\n A 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:\n Input: mat = [[1,0,0],[0,0,1],[1,0,0]]\n Output: 1\n Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.\n Example 2:\n Input: mat = [[1,0,0],[0,1,0],[0,0,1]]\n Output: 3\n Explanation: (0, 0), (1, 1) and (2, 2) are special positions.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1583, - "title": "Count Unhappy Friends", - "question": "class Solution:\n def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:\n \"\"\"\n You are given a list of preferences for n friends, where n is always even.\n For 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.\n All 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.\n However, 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:\n x prefers u over y, and\n u prefers x over v.\n Return the number of unhappy friends.\n Example 1:\n Input: n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]\n Output: 2\n Explanation:\n Friend 1 is unhappy because:\n - 1 is paired with 0 but prefers 3 over 0, and\n - 3 prefers 1 over 2.\n Friend 3 is unhappy because:\n - 3 is paired with 2 but prefers 1 over 2, and\n - 1 prefers 3 over 0.\n Friends 0 and 2 are happy.\n Example 2:\n Input: n = 2, preferences = [[1], [0]], pairs = [[1, 0]]\n Output: 0\n Explanation: Both friends 0 and 1 are happy.\n Example 3:\n Input: n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1584, - "title": "Min Cost to Connect All Points", - "question": "class Solution:\n def minCostConnectPoints(self, points: List[List[int]]) -> int:\n \"\"\"\n You are given an array points representing integer coordinates of some points on a 2D-plane, where points[i] = [xi, yi].\n The 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.\n Return 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:\n Input: points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\n Output: 20\n Explanation: \n We can connect the points as shown above to get the minimum cost of 20.\n Notice that there is a unique path between every pair of points.\n Example 2:\n Input: points = [[3,12],[-2,5],[-4,1]]\n Output: 18\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1585, - "title": "Check If String Is Transformable With Substring Sort Operations", - "question": "class Solution:\n def isTransformable(self, s: str, t: str) -> bool:\n \"\"\"\n Given two strings s and t, transform string s into string t using the following operation any number of times:\n Choose a non-empty substring in s and sort it in place so the characters are in ascending order.\n For example, applying the operation on the underlined substring in \"14234\" results in \"12344\".\n Return true if it is possible to transform s into t. Otherwise, return false.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: s = \"84532\", t = \"34852\"\n Output: true\n Explanation: You can transform s into t using the following sort operations:\n \"84532\" (from index 2 to 3) -> \"84352\"\n \"84352\" (from index 0 to 2) -> \"34852\"\n Example 2:\n Input: s = \"34521\", t = \"23415\"\n Output: true\n Explanation: You can transform s into t using the following sort operations:\n \"34521\" -> \"23451\"\n \"23451\" -> \"23415\"\n Example 3:\n Input: s = \"12345\", t = \"12435\"\n Output: false\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1603, - "title": "Design Parking System", - "question": "class ParkingSystem:\n def __init__(self, big: int, medium: int, small: int):\n def addCar(self, carType: int) -> bool:\n \"\"\"\n Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.\n Implement the ParkingSystem class:\n ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor.\n bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.\n Example 1:\n Input\n [\"ParkingSystem\", \"addCar\", \"addCar\", \"addCar\", \"addCar\"]\n [[1, 1, 0], [1], [2], [3], [1]]\n Output\n [null, true, true, false, false]\n Explanation\n ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);\n parkingSystem.addCar(1); // return true because there is 1 available slot for a big car\n parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car\n parkingSystem.addCar(3); // return false because there is no available slot for a small car\n parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1604, - "title": "Alert Using Same Key-Card Three or More Times in a One Hour Period", - "question": "class Solution:\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n \"\"\"\n 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.\n You 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.\n Access times are given in the 24-hour time format \"HH:MM\", such as \"23:51\" and \"09:49\".\n Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically.\n Notice 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:\n Input: keyName = [\"daniel\",\"daniel\",\"daniel\",\"luis\",\"luis\",\"luis\",\"luis\"], keyTime = [\"10:00\",\"10:40\",\"11:00\",\"09:00\",\"11:00\",\"13:00\",\"15:00\"]\n Output: [\"daniel\"]\n Explanation: \"daniel\" used the keycard 3 times in a one-hour period (\"10:00\",\"10:40\", \"11:00\").\n Example 2:\n Input: keyName = [\"alice\",\"alice\",\"alice\",\"bob\",\"bob\",\"bob\",\"bob\"], keyTime = [\"12:01\",\"12:00\",\"18:00\",\"21:00\",\"21:20\",\"21:30\",\"23:00\"]\n Output: [\"bob\"]\n Explanation: \"bob\" used the keycard 3 times in a one-hour period (\"21:00\",\"21:20\", \"21:30\").\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1606, - "title": "Find Servers That Handled Most Number of Requests", - "question": "class Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n \"\"\"\n You have k servers numbered from 0 to k-1 that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but cannot handle more than one request at a time. The requests are assigned to servers according to a specific algorithm:\n The ith (0-indexed) request arrives.\n If all servers are busy, the request is dropped (not handled at all).\n If the (i % k)th server is available, assign the request to that server.\n Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the ith server is busy, try to assign the request to the (i+1)th server, then the (i+2)th server, and so on.\n You are given a strictly increasing array arrival of positive integers, where arrival[i] represents the arrival time of the ith request, and another array load, where load[i] represents the load of the ith request (the time it takes to complete). Your goal is to find the busiest server(s). A server is considered busiest if it handled the most number of requests successfully among all the servers.\n Return a list containing the IDs (0-indexed) of the busiest server(s). You may return the IDs in any order.\n Example 1:\n Input: k = 3, arrival = [1,2,3,4,5], load = [5,2,3,3,3] \n Output: [1] \n Explanation: \n All of the servers start out available.\n The first 3 requests are handled by the first 3 servers in order.\n Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1.\n Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped.\n Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server.\n Example 2:\n Input: k = 3, arrival = [1,2,3,4], load = [1,2,1,2]\n Output: [0]\n Explanation: \n The first 3 requests are handled by first 3 servers.\n Request 3 comes in. It is handled by server 0 since the server is available.\n Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server.\n Example 3:\n Input: k = 3, arrival = [1,2,3], load = [10,12,11]\n Output: [0,1,2]\n Explanation: Each server handles a single request, so they are all considered the busiest.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1605, - "title": "Find Valid Matrix Given Row and Column Sums", - "question": "class Solution:\n def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n \"\"\"\n 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.\n Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.\n Return 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:\n Input: rowSum = [3,8], colSum = [4,7]\n Output: [[3,0],\n [1,7]]\n Explanation: \n 0th row: 3 + 0 = 3 == rowSum[0]\n 1st row: 1 + 7 = 8 == rowSum[1]\n 0th column: 3 + 1 = 4 == colSum[0]\n 1st column: 0 + 7 = 7 == colSum[1]\n The row and column sums match, and all matrix elements are non-negative.\n Another possible matrix is: [[1,2],\n [3,5]]\n Example 2:\n Input: rowSum = [5,7,10], colSum = [8,6,8]\n Output: [[0,5,0],\n [6,1,0],\n [2,0,8]]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1592, - "title": "Rearrange Spaces Between Words", - "question": "class Solution:\n def reorderSpaces(self, text: str) -> str:\n \"\"\"\n 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.\n Rearrange 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.\n Return the string after rearranging the spaces.\n Example 1:\n Input: text = \" this is a sentence \"\n Output: \"this is a sentence\"\n Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.\n Example 2:\n Input: text = \" practice makes perfect\"\n Output: \"practice makes perfect \"\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1593, - "title": "Split a String Into the Max Number of Unique Substrings", - "question": "class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n \"\"\"\n Given a string s, return the maximum number of unique substrings that the given string can be split into.\n You 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.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: s = \"ababccc\"\n Output: 5\n Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.\n Example 2:\n Input: s = \"aba\"\n Output: 2\n Explanation: One way to split maximally is ['a', 'ba'].\n Example 3:\n Input: s = \"aa\"\n Output: 1\n Explanation: It is impossible to split the string any further.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1594, - "title": "Maximum Non Negative Product in a Matrix", - "question": "class Solution:\n def maxProductPath(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Among 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.\n Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.\n Notice that the modulo is performed after getting the maximum product.\n Example 1:\n Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]\n Output: -1\n Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.\n Example 2:\n Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]\n Output: 8\n Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).\n Example 3:\n Input: grid = [[1,3],[0,-4]]\n Output: 0\n Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1595, - "title": "Minimum Cost to Connect Two Groups of Points", - "question": "class Solution:\n def connectTwoGroups(self, cost: List[List[int]]) -> int:\n \"\"\"\n You are given two groups of points where the first group has size1 points, the second group has size2 points, and size1 >= size2.\n The cost of the connection between any two points are given in an size1 x size2 matrix where cost[i][j] is the cost of connecting point i of the first group and point j of the second group. The groups are connected if each point in both groups is connected to one or more points in the opposite group. In other words, each point in the first group must be connected to at least one point in the second group, and each point in the second group must be connected to at least one point in the first group.\n Return the minimum cost it takes to connect the two groups.\n Example 1:\n Input: cost = [[15, 96], [36, 2]]\n Output: 17\n Explanation: The optimal way of connecting the groups is:\n 1--A\n 2--B\n This results in a total cost of 17.\n Example 2:\n Input: cost = [[1, 3, 5], [4, 1, 1], [1, 5, 3]]\n Output: 4\n Explanation: The optimal way of connecting the groups is:\n 1--A\n 2--B\n 2--C\n 3--A\n This results in a total cost of 4.\n Note that there are multiple points connected to point 2 in the first group and point A in the second group. This does not matter as there is no limit to the number of points that can be connected. We only care about the minimum total cost.\n Example 3:\n Input: cost = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]]\n Output: 10\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1598, - "title": "Crawler Log Folder", - "question": "class Solution:\n def minOperations(self, logs: List[str]) -> int:\n \"\"\"\n The Leetcode file system keeps a log each time some user performs a change folder operation.\n The 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).\n You are given a list of strings logs where logs[i] is the operation performed by the user at the ith step.\n The file system starts in the main folder, then the operations in logs are performed.\n Return the minimum number of operations needed to go back to the main folder after the change folder operations.\n Example 1:\n Input: logs = [\"d1/\",\"d2/\",\"../\",\"d21/\",\"./\"]\n Output: 2\n Explanation: Use this change folder operation \"../\" 2 times and go back to the main folder.\n Example 2:\n Input: logs = [\"d1/\",\"d2/\",\"./\",\"d3/\",\"../\",\"d31/\"]\n Output: 3\n Example 3:\n Input: logs = [\"d1/\",\"../\",\"../\",\"../\"]\n Output: 0\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1599, - "title": "Maximum Profit of Operating a Centennial Wheel", - "question": "class Solution:\n def minOperationsMaxProfit(self, customers: List[int], boardingCost: int, runningCost: int) -> int:\n \"\"\"\n 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.\n You 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.\n You 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.\n Return 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:\n Input: customers = [8,3], boardingCost = 5, runningCost = 6\n Output: 3\n Explanation: The numbers written on the gondolas are the number of people currently there.\n 1. 8 customers arrive, 4 board and 4 wait for the next gondola, the wheel rotates. Current profit is 4 * $5 - 1 * $6 = $14.\n 2. 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.\n 3. The final 3 customers board the gondola, the wheel rotates. Current profit is 11 * $5 - 3 * $6 = $37.\n The highest profit was $37 after rotating the wheel 3 times.\n Example 2:\n Input: customers = [10,9,6], boardingCost = 6, runningCost = 4\n Output: 7\n Explanation:\n 1. 10 customers arrive, 4 board and 6 wait for the next gondola, the wheel rotates. Current profit is 4 * $6 - 1 * $4 = $20.\n 2. 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.\n 3. The final 6 customers arrive, 4 board and 13 wait, the wheel rotates. Current profit is 12 * $6 - 3 * $4 = $60.\n 4. 4 board and 9 wait, the wheel rotates. Current profit is 16 * $6 - 4 * $4 = $80.\n 5. 4 board and 5 wait, the wheel rotates. Current profit is 20 * $6 - 5 * $4 = $100.\n 6. 4 board and 1 waits, the wheel rotates. Current profit is 24 * $6 - 6 * $4 = $120.\n 7. 1 boards, the wheel rotates. Current profit is 25 * $6 - 7 * $4 = $122.\n The highest profit was $122 after rotating the wheel 7 times.\n Example 3:\n Input: customers = [3,4,0,5,1], boardingCost = 1, runningCost = 92\n Output: -1\n Explanation:\n 1. 3 customers arrive, 3 board and 0 wait, the wheel rotates. Current profit is 3 * $1 - 1 * $92 = -$89.\n 2. 4 customers arrive, 4 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 2 * $92 = -$177.\n 3. 0 customers arrive, 0 board and 0 wait, the wheel rotates. Current profit is 7 * $1 - 3 * $92 = -$269.\n 4. 5 customers arrive, 4 board and 1 waits, the wheel rotates. Current profit is 11 * $1 - 4 * $92 = -$357.\n 5. 1 customer arrives, 2 board and 0 wait, the wheel rotates. Current profit is 13 * $1 - 5 * $92 = -$447.\n The profit was never positive, so return -1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1600, - "title": "Throne Inheritance", - "question": "class ThroneInheritance:\n def __init__(self, kingName: str):\n def birth(self, parentName: str, childName: str) -> None:\n def death(self, name: str) -> None:\n def getInheritanceOrder(self) -> List[str]:\n \"\"\"\n A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.\n The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.\n Successor(x, curOrder):\n if x has no children or all of x's children are in curOrder:\n if x is the king return null\n else return Successor(x's parent, curOrder)\n else return x's oldest child who's not in curOrder\n For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.\n In the beginning, curOrder will be [\"king\"].\n Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get [\"king\", \"Alice\"].\n Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get [\"king\", \"Alice\", \"Jack\"].\n Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get [\"king\", \"Alice\", \"Jack\", \"Bob\"].\n Calling Successor(Bob, curOrder) will return null. Thus the order of inheritance will be [\"king\", \"Alice\", \"Jack\", \"Bob\"].\n Using the above function, we can always obtain a unique order of inheritance.\n Implement the ThroneInheritance class:\n ThroneInheritance(string kingName) Initializes an object of the ThroneInheritance class. The name of the king is given as part of the constructor.\n void birth(string parentName, string childName) Indicates that parentName gave birth to childName.\n void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function nor the current inheritance order. You can treat it as just marking the person as dead.\n string[] getInheritanceOrder() Returns a list representing the current order of inheritance excluding dead people.\n Example 1:\n Input\n [\"ThroneInheritance\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"birth\", \"getInheritanceOrder\", \"death\", \"getInheritanceOrder\"]\n [[\"king\"], [\"king\", \"andy\"], [\"king\", \"bob\"], [\"king\", \"catherine\"], [\"andy\", \"matthew\"], [\"bob\", \"alex\"], [\"bob\", \"asha\"], [null], [\"bob\"], [null]]\n Output\n [null, null, null, null, null, null, null, [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"], null, [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]]\n Explanation\n ThroneInheritance t= new ThroneInheritance(\"king\"); // order: king\n t.birth(\"king\", \"andy\"); // order: king > andy\n t.birth(\"king\", \"bob\"); // order: king > andy > bob\n t.birth(\"king\", \"catherine\"); // order: king > andy > bob > catherine\n t.birth(\"andy\", \"matthew\"); // order: king > andy > matthew > bob > catherine\n t.birth(\"bob\", \"alex\"); // order: king > andy > matthew > bob > alex > catherine\n t.birth(\"bob\", \"asha\"); // order: king > andy > matthew > bob > alex > asha > catherine\n t.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"bob\", \"alex\", \"asha\", \"catherine\"]\n t.death(\"bob\"); // order: king > andy > matthew > bob > alex > asha > catherine\n t.getInheritanceOrder(); // return [\"king\", \"andy\", \"matthew\", \"alex\", \"asha\", \"catherine\"]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1601, - "title": "Maximum Number of Achievable Transfer Requests", - "question": "class Solution:\n def maximumRequests(self, n: int, requests: List[List[int]]) -> int:\n \"\"\"\n We have n buildings numbered from 0 to n - 1. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in.\n You are given an array requests where requests[i] = [fromi, toi] represents an employee's request to transfer from building fromi to building toi.\n All buildings are full, so a list of requests is achievable only if for each building, the net change in employee transfers is zero. This means the number of employees leaving is equal to the number of employees moving in. For example if n = 3 and two employees are leaving building 0, one is leaving building 1, and one is leaving building 2, there should be two employees moving to building 0, one employee moving to building 1, and one employee moving to building 2.\n Return the maximum number of achievable requests.\n Example 1:\n Input: n = 5, requests = [[0,1],[1,0],[0,1],[1,2],[2,0],[3,4]]\n Output: 5\n Explantion: Let's see the requests:\n From building 0 we have employees x and y and both want to move to building 1.\n From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.\n From building 2 we have employee z and they want to move to building 0.\n From building 3 we have employee c and they want to move to building 4.\n From building 4 we don't have any requests.\n We can achieve the requests of users x and b by swapping their places.\n We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.\n Example 2:\n Input: n = 3, requests = [[0,0],[1,2],[2,1]]\n Output: 3\n Explantion: Let's see the requests:\n From building 0 we have employee x and they want to stay in the same building 0.\n From building 1 we have employee y and they want to move to building 2.\n From building 2 we have employee z and they want to move to building 1.\n We can achieve all the requests. \n Example 3:\n Input: n = 4, requests = [[0,3],[3,1],[1,2],[2,0]]\n Output: 4\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1621, - "title": "Number of Sets of K Non-Overlapping Line Segments", - "question": "class Solution:\n def numberOfSets(self, n: int, k: int) -> int:\n \"\"\"\n 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.\n Return 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:\n Input: n = 4, k = 2\n Output: 5\n Explanation: The two line segments are shown in red and blue.\n The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.\n Example 2:\n Input: n = 3, k = 1\n Output: 3\n Explanation: The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.\n Example 3:\n Input: n = 30, k = 7\n Output: 796297179\n Explanation: The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1620, - "title": "Coordinate With Maximum Network Quality", - "question": "class Solution:\n def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:\n \"\"\"\n 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.\n You 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.\n The 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.\n Return 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.\n Note:\n A coordinate (x1, y1) is lexicographically smaller than (x2, y2) if either:\n x1 < x2, or\n x1 == x2 and y1 < y2.\n \u230aval\u230b is the greatest integer less than or equal to val (the floor function).\n Example 1:\n Input: towers = [[1,2,5],[2,1,7],[3,1,9]], radius = 2\n Output: [2,1]\n Explanation: 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\n No other coordinate has a higher network quality.\n Example 2:\n Input: towers = [[23,11,21]], radius = 9\n Output: [23,11]\n Explanation: Since there is only one tower, the network quality is highest right at the tower's location.\n Example 3:\n Input: towers = [[1,2,13],[2,1,7],[0,1,9]], radius = 2\n Output: [1,2]\n Explanation: Coordinate (1, 2) has the highest network quality.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1728, - "title": "Cat and Mouse II", - "question": "class Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n \"\"\"\n A game is played by a cat and a mouse named Cat and Mouse.\n The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food.\n Players are represented by the characters 'C'(Cat),'M'(Mouse).\n Floors are represented by the character '.' and can be walked on.\n Walls are represented by the character '#' and cannot be walked on.\n Food is represented by the character 'F' and can be walked on.\n There is only one of each character 'C', 'M', and 'F' in grid.\n Mouse and Cat play according to the following rules:\n Mouse moves first, then they take turns to move.\n During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid.\n catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.\n Staying in the same position is allowed.\n Mouse can jump over Cat.\n The game can end in 4 ways:\n If Cat occupies the same position as Mouse, Cat wins.\n If Cat reaches the food first, Cat wins.\n If Mouse reaches the food first, Mouse wins.\n If Mouse cannot get to the food within 1000 turns, Cat wins.\n Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.\n Example 1:\n Input: grid = [\"####F\",\"#C...\",\"M....\"], catJump = 1, mouseJump = 2\n Output: true\n Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.\n Example 2:\n Input: grid = [\"M.C...F\"], catJump = 1, mouseJump = 4\n Output: true\n Example 3:\n Input: grid = [\"M.C...F\"], catJump = 1, mouseJump = 3\n Output: false\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1622, - "title": "Fancy Sequence", - "question": "class Fancy:\n def __init__(self):\n def append(self, val: int) -> None:\n def addAll(self, inc: int) -> None:\n def multAll(self, m: int) -> None:\n def getIndex(self, idx: int) -> int:\n \"\"\"\n Write an API that generates fancy sequences using the append, addAll, and multAll operations.\n Implement the Fancy class:\n Fancy() Initializes the object with an empty sequence.\n void append(val) Appends an integer val to the end of the sequence.\n void addAll(inc) Increments all existing values in the sequence by an integer inc.\n void multAll(m) Multiplies all existing values in the sequence by an integer m.\n int getIndex(idx) Gets the current value at index idx (0-indexed) of the sequence modulo 109 + 7. If the index is greater or equal than the length of the sequence, return -1.\n Example 1:\n Input\n [\"Fancy\", \"append\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"addAll\", \"append\", \"multAll\", \"getIndex\", \"getIndex\", \"getIndex\"]\n [[], [2], [3], [7], [2], [0], [3], [10], [2], [0], [1], [2]]\n Output\n [null, null, null, null, null, 10, null, null, null, 26, 34, 20]\n Explanation\n Fancy fancy = new Fancy();\n fancy.append(2); // fancy sequence: [2]\n fancy.addAll(3); // fancy sequence: [2+3] -> [5]\n fancy.append(7); // fancy sequence: [5, 7]\n fancy.multAll(2); // fancy sequence: [5*2, 7*2] -> [10, 14]\n fancy.getIndex(0); // return 10\n fancy.addAll(3); // fancy sequence: [10+3, 14+3] -> [13, 17]\n fancy.append(10); // fancy sequence: [13, 17, 10]\n fancy.multAll(2); // fancy sequence: [13*2, 17*2, 10*2] -> [26, 34, 20]\n fancy.getIndex(0); // return 26\n fancy.getIndex(1); // return 34\n fancy.getIndex(2); // return 20\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1608, - "title": "Special Array With X Elements Greater Than or Equal X", - "question": "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Notice that x does not have to be an element in nums.\n Return 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:\n Input: nums = [3,5]\n Output: 2\n Explanation: There are 2 values (3 and 5) that are greater than or equal to 2.\n Example 2:\n Input: nums = [0,0]\n Output: -1\n Explanation: No numbers fit the criteria for x.\n If x = 0, there should be 0 numbers >= x, but there are 2.\n If x = 1, there should be 1 number >= x, but there are 0.\n If x = 2, there should be 2 numbers >= x, but there are 0.\n x cannot be greater since there are only 2 numbers in nums.\n Example 3:\n Input: nums = [0,4,3,0,4]\n Output: 3\n Explanation: There are 3 values that are greater than or equal to 3.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1609, - "title": "Even Odd Tree", - "question": "class Solution:\n def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:\n \"\"\"\n A binary tree is named Even-Odd if it meets the following conditions:\n The 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.\n For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).\n For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).\n Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.\n Example 1:\n Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]\n Output: true\n Explanation: The node values on each level are:\n Level 0: [1]\n Level 1: [10,4]\n Level 2: [3,7,9]\n Level 3: [12,8,6,2]\n Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.\n Example 2:\n Input: root = [5,4,2,3,3,7]\n Output: false\n Explanation: The node values on each level are:\n Level 0: [5]\n Level 1: [4,2]\n Level 2: [3,3,7]\n Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.\n Example 3:\n Input: root = [5,9,1,3,5,7]\n Output: false\n Explanation: Node values in the level 1 should be even integers.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1611, - "title": "Minimum One Bit Operations to Make Integers Zero", - "question": "class Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n \"\"\"\n Given an integer n, you must transform it into 0 using the following operations any number of times:\n Change the rightmost (0th) bit in the binary representation of n.\n Change the ith bit in the binary representation of n if the (i-1)th bit is set to 1 and the (i-2)th through 0th bits are set to 0.\n Return the minimum number of operations to transform n into 0.\n Example 1:\n Input: n = 3\n Output: 2\n Explanation: The binary representation of 3 is \"11\".\n \"11\" -> \"01\" with the 2nd operation since the 0th bit is 1.\n \"01\" -> \"00\" with the 1st operation.\n Example 2:\n Input: n = 6\n Output: 4\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1610, - "title": "Maximum Number of Visible Points", - "question": "class Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n \"\"\"\n You are given an array points, an integer angle, and your location, where location = [posx, posy] and points[i] = [xi, yi] both denote integral coordinates on the X-Y plane.\n Initially, you are facing directly east from your position. You cannot move from your position, but you can rotate. In other words, posx and posy cannot be changed. Your field of view in degrees is represented by angle, determining how wide you can see from any given view direction. Let d be the amount in degrees that you rotate counterclockwise. Then, your field of view is the inclusive range of angles [d - angle/2, d + angle/2].\n Your browser does not support the video tag or this video format.\n You can see some set of points if, for each point, the angle formed by the point, your position, and the immediate east direction from your position is in your field of view.\n There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.\n Return the maximum number of points you can see.\n Example 1:\n Input: points = [[2,1],[2,2],[3,3]], angle = 90, location = [1,1]\n Output: 3\n Explanation: The shaded region represents your field of view. All points can be made visible in your field of view, including [3,3] even though [2,2] is in front and in the same line of sight.\n Example 2:\n Input: points = [[2,1],[2,2],[3,4],[1,1]], angle = 90, location = [1,1]\n Output: 4\n Explanation: All points can be made visible in your field of view, including the one at your location.\n Example 3:\n Input: points = [[1,0],[2,1]], angle = 13, location = [1,1]\n Output: 1\n Explanation: You can only see one of the two points, as shown above.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1614, - "title": "Maximum Nesting Depth of the Parentheses", - "question": "class Solution:\n def maxDepth(self, s: str) -> int:\n \"\"\"\n A string is a valid parentheses string (denoted VPS) if it meets one of the following:\n It is an empty string \"\", or a single character not equal to \"(\" or \")\",\n It can be written as AB (A concatenated with B), where A and B are VPS's, or\n It can be written as (A), where A is a VPS.\n We can similarly define the nesting depth depth(S) of any VPS S as follows:\n depth(\"\") = 0\n depth(C) = 0, where C is a string with a single character not equal to \"(\" or \")\".\n depth(A + B) = max(depth(A), depth(B)), where A and B are VPS's.\n depth(\"(\" + A + \")\") = 1 + depth(A), where A is a VPS.\n For example, \"\", \"()()\", and \"()(()())\" are VPS's (with nesting depths 0, 1, and 2), and \")(\" and \"(()\" are not VPS's.\n Given a VPS represented as string s, return the nesting depth of s.\n Example 1:\n Input: s = \"(1+(2*3)+((8)/4))+1\"\n Output: 3\n Explanation: Digit 8 is inside of 3 nested parentheses in the string.\n Example 2:\n Input: s = \"(1)+((2))+(((3)))\"\n Output: 3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1615, - "title": "Maximal Network Rank", - "question": "class Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n \"\"\"\n 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.\n The 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.\n The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.\n Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.\n Example 1:\n Input: n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]\n Output: 4\n Explanation: The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.\n Example 2:\n Input: n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]\n Output: 5\n Explanation: There are 5 roads that are connected to cities 1 or 2.\n Example 3:\n Input: n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]\n Output: 5\n Explanation: The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1616, - "title": "Split Two Strings to Make Palindrome", - "question": "class Solution:\n def checkPalindromeFormation(self, a: str, b: str) -> bool:\n \"\"\"\n 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.\n When 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.\n Return true if it is possible to form a palindrome string, otherwise return false.\n Notice that x + y denotes the concatenation of strings x and y.\n Example 1:\n Input: a = \"x\", b = \"y\"\n Output: true\n Explaination: If either a or b are palindromes the answer is true since you can split in the following way:\n aprefix = \"\", asuffix = \"x\"\n bprefix = \"\", bsuffix = \"y\"\n Then, aprefix + bsuffix = \"\" + \"y\" = \"y\", which is a palindrome.\n Example 2:\n Input: a = \"xbdef\", b = \"xecab\"\n Output: false\n Example 3:\n Input: a = \"ulacfd\", b = \"jizalu\"\n Output: true\n Explaination: Split them at index 3:\n aprefix = \"ula\", asuffix = \"cfd\"\n bprefix = \"jiz\", bsuffix = \"alu\"\n Then, aprefix + bsuffix = \"ula\" + \"alu\" = \"ulaalu\", which is a palindrome.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1617, - "title": "Count Subtrees With Max Distance Between Cities", - "question": "class Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\r\n A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other.\r\n For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d.\r\n Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d.\r\n Notice that the distance between the two cities is the number of edges in the path between them.\r\n Example 1:\r\n Input: n = 4, edges = [[1,2],[2,3],[2,4]]\r\n Output: [3,4,0]\r\n Explanation:\r\n The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1.\r\n The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2.\r\n No subtree has two nodes where the max distance between them is 3.\r\n Example 2:\r\n Input: n = 2, edges = [[1,2]]\r\n Output: [1]\r\n Example 3:\r\n Input: n = 3, edges = [[1,2],[2,3]]\r\n Output: [2,1]\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1636, - "title": "Sort Array by Increasing Frequency", - "question": "class Solution:\n def frequencySort(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n Return the sorted array.\n Example 1:\n Input: nums = [1,1,2,2,2,3]\n Output: [3,1,1,2,2,2]\n Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.\n Example 2:\n Input: nums = [2,3,1,3,2]\n Output: [1,3,3,2,2]\n Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.\n Example 3:\n Input: nums = [-1,1,-6,4,5,-6,1,4,1]\n Output: [5,-1,4,4,-6,-6,1,1,1]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1637, - "title": "Widest Vertical Area Between Two Points Containing No Points", - "question": "class Solution:\n def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:\n \"\"\"\n 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.\n A 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.\n Note that points on the edge of a vertical area are not considered included in the area.\n Example 1:\n \u200b\n Input: points = [[8,7],[9,9],[7,4],[9,7]]\n Output: 1\n Explanation: Both the red and the blue area are optimal.\n Example 2:\n Input: points = [[3,1],[9,0],[1,0],[1,4],[5,3],[8,8]]\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1638, - "title": "Count Substrings That Differ by One Character", - "question": "class Solution:\n def countSubstrings(self, s: str, t: str) -> int:\n \"\"\"\n 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.\n For example, the underlined substrings in \"computer\" and \"computation\" only differ by the 'e'/'a', so this is a valid way.\n Return the number of substrings that satisfy the condition above.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: s = \"aba\", t = \"baba\"\n Output: 6\n Explanation: 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\")\n The underlined portions are the substrings that are chosen from s and t.\n \u200b\u200bExample 2:\n Input: s = \"ab\", t = \"bb\"\n Output: 3\n Explanation: The following are the pairs of substrings from s and t that differ by 1 character:\n (\"ab\", \"bb\")\n (\"ab\", \"bb\")\n (\"ab\", \"bb\")\n \u200b\u200b\u200b\u200bThe underlined portions are the substrings that are chosen from s and t.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1639, - "title": "Number of Ways to Form a Target String Given a Dictionary", - "question": "class Solution:\n def numWays(self, words: List[str], target: str) -> int:\n \"\"\"\n You are given a list of strings of the same length words and a string target.\n Your task is to form target using the given words under the following rules:\n target should be formed from left to right.\n To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].\n Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string.\n Repeat the process until you form the string target.\n Notice that you can use multiple characters from the same string in words provided the conditions above are met.\n Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.\n Example 1:\n Input: words = [\"acca\",\"bbbb\",\"caca\"], target = \"aba\"\n Output: 6\n Explanation: There are 6 ways to form target.\n \"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"caca\")\n \"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n \"aba\" -> index 0 (\"acca\"), index 1 (\"bbbb\"), index 3 (\"acca\")\n \"aba\" -> index 0 (\"acca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n \"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"acca\")\n \"aba\" -> index 1 (\"caca\"), index 2 (\"bbbb\"), index 3 (\"caca\")\n Example 2:\n Input: words = [\"abba\",\"baab\"], target = \"bab\"\n Output: 4\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1624, - "title": "Largest Substring Between Two Equal Characters", - "question": "class Solution:\n def maxLengthBetweenEqualCharacters(self, s: str) -> int:\n \"\"\"\n 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.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: s = \"aa\"\n Output: 0\n Explanation: The optimal substring here is an empty substring between the two 'a's.\n Example 2:\n Input: s = \"abca\"\n Output: 2\n Explanation: The optimal substring here is \"bc\".\n Example 3:\n Input: s = \"cbzxy\"\n Output: -1\n Explanation: There are no characters that appear twice in s.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1625, - "title": "Lexicographically Smallest String After Applying Operations", - "question": "class Solution:\n def findLexSmallestString(self, s: str, a: int, b: int) -> str:\n \"\"\"\n You are given a string s of even length consisting of digits from 0 to 9, and two integers a and b.\n You can apply either of the following two operations any number of times and in any order on s:\n Add 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\".\n Rotate s to the right by b positions. For example, if s = \"3456\" and b = 1, s becomes \"6345\".\n Return the lexicographically smallest string you can obtain by applying the above operations any number of times on s.\n A 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:\n Input: s = \"5525\", a = 9, b = 2\n Output: \"2050\"\n Explanation: We can apply the following operations:\n Start: \"5525\"\n Rotate: \"2555\"\n Add: \"2454\"\n Add: \"2353\"\n Rotate: \"5323\"\n Add: \"5222\"\n Add: \"5121\"\n Rotate: \"2151\"\n \u200b\u200b\u200b\u200b\u200b\u200b\u200bAdd: \"2050\"\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\n There is no way to obtain a string that is lexicographically smaller then \"2050\".\n Example 2:\n Input: s = \"74\", a = 5, b = 1\n Output: \"24\"\n Explanation: We can apply the following operations:\n Start: \"74\"\n Rotate: \"47\"\n \u200b\u200b\u200b\u200b\u200b\u200b\u200bAdd: \"42\"\n \u200b\u200b\u200b\u200b\u200b\u200b\u200bRotate: \"24\"\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\n There is no way to obtain a string that is lexicographically smaller then \"24\".\n Example 3:\n Input: s = \"0011\", a = 4, b = 2\n Output: \"0011\"\n Explanation: There are no sequence of operations that will give us a lexicographically smaller string than \"0011\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1626, - "title": "Best Team With No Conflicts", - "question": "class Solution:\n def bestTeamScore(self, scores: List[int], ages: List[int]) -> int:\n \"\"\"\n 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.\n However, 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.\n Given 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:\n Input: scores = [1,3,5,10,15], ages = [1,2,3,4,5]\n Output: 34\n Explanation: You can choose all the players.\n Example 2:\n Input: scores = [4,5,6,5], ages = [2,1,2,1]\n Output: 16\n Explanation: It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age.\n Example 3:\n Input: scores = [1,2,3,5], ages = [8,9,10,1]\n Output: 6\n Explanation: It is best to choose the first 3 players. \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1629, - "title": "Slowest Key", - "question": "class Solution:\n def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:\n \"\"\"\n A newly designed keypad was tested, where a tester pressed a sequence of n keys, one at a time.\n You 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.\n The 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].\n Note 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.\n Return 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:\n Input: releaseTimes = [9,29,49,50], keysPressed = \"cbcd\"\n Output: \"c\"\n Explanation: The keypresses were as follows:\n Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).\n Keypress 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).\n Keypress 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).\n Keypress 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).\n The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.\n 'c' is lexicographically larger than 'b', so the answer is 'c'.\n Example 2:\n Input: releaseTimes = [12,23,36,46,62], keysPressed = \"spuda\"\n Output: \"a\"\n Explanation: The keypresses were as follows:\n Keypress for 's' had a duration of 12.\n Keypress for 'p' had a duration of 23 - 12 = 11.\n Keypress for 'u' had a duration of 36 - 23 = 13.\n Keypress for 'd' had a duration of 46 - 36 = 10.\n Keypress for 'a' had a duration of 62 - 46 = 16.\n The longest of these was the keypress for 'a' with duration 16.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1630, - "title": "Arithmetic Subarrays", - "question": "class Solution:\n def checkArithmeticSubarrays(self, nums: List[int], l: List[int], r: List[int]) -> List[bool]:\n \"\"\"\n 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.\n For example, these are arithmetic sequences:\n 1, 3, 5, 7, 9\n 7, 7, 7, 7\n 3, -1, -5, -9\n The following sequence is not arithmetic:\n 1, 1, 2, 5, 7\n You 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.\n Return 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:\n Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]\n Output: [true,false,true]\n Explanation:\n In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.\n In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.\n In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.\n Example 2:\n Input: 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]\n Output: [false,true,false,false,true,true]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1631, - "title": "Path With Minimum Effort", - "question": "class Solution:\r\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n \"\"\"\n 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.\r\n A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.\r\n Return the minimum effort required to travel from the top-left cell to the bottom-right cell.\r\n Example 1:\r\n Input: heights = [[1,2,2],[3,8,2],[5,3,5]]\r\n Output: 2\r\n Explanation: The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.\r\n This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.\r\n Example 2:\r\n Input: heights = [[1,2,3],[3,8,4],[5,3,5]]\r\n Output: 1\r\n Explanation: 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].\r\n Example 3:\r\n Input: 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]]\r\n Output: 0\r\n Explanation: This route does not require any effort.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1652, - "title": "Defuse the Bomb", - "question": "class Solution:\n def decrypt(self, code: List[int], k: int) -> List[int]:\n \"\"\"\n 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.\n To decrypt the code, you must replace every number. All the numbers are replaced simultaneously.\n If k > 0, replace the ith number with the sum of the next k numbers.\n If k < 0, replace the ith number with the sum of the previous k numbers.\n If k == 0, replace the ith number with 0.\n As code is circular, the next element of code[n-1] is code[0], and the previous element of code[0] is code[n-1].\n Given the circular array code and an integer key k, return the decrypted code to defuse the bomb!\n Example 1:\n Input: code = [5,7,1,4], k = 3\n Output: [12,10,16,13]\n Explanation: Each number is replaced by the sum of the next 3 numbers. The decrypted code is [7+1+4, 1+4+5, 4+5+7, 5+7+1]. Notice that the numbers wrap around.\n Example 2:\n Input: code = [1,2,3,4], k = 0\n Output: [0,0,0,0]\n Explanation: When k is zero, the numbers are replaced by 0. \n Example 3:\n Input: code = [2,4,9,3], k = -2\n Output: [12,5,6,13]\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1653, - "title": "Minimum Deletions to Make String Balanced", - "question": "class Solution:\n def minimumDeletions(self, s: str) -> int:\n \"\"\"\n You are given a string s consisting only of characters 'a' and 'b'\u200b\u200b\u200b\u200b.\n You 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'.\n Return the minimum number of deletions needed to make s balanced.\n Example 1:\n Input: s = \"aababbab\"\n Output: 2\n Explanation: You can either:\n Delete the characters at 0-indexed positions 2 and 6 (\"aababbab\" -> \"aaabbb\"), or\n Delete the characters at 0-indexed positions 3 and 6 (\"aababbab\" -> \"aabbbb\").\n Example 2:\n Input: s = \"bbaaaaabb\"\n Output: 2\n Explanation: The only solution is to delete the first two characters.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1654, - "title": "Minimum Jumps to Reach Home", - "question": "class Solution:\n def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n \"\"\"\n A certain bug's home is on the x-axis at position x. Help them get there from position 0.\n The bug jumps according to the following rules:\n It can jump exactly a positions forward (to the right).\n It can jump exactly b positions backward (to the left).\n It cannot jump backward twice in a row.\n It cannot jump to any forbidden positions.\n The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers.\n Given 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:\n Input: forbidden = [14,4,18,1,15], a = 3, b = 15, x = 9\n Output: 3\n Explanation: 3 jumps forward (0 -> 3 -> 6 -> 9) will get the bug home.\n Example 2:\n Input: forbidden = [8,3,16,6,12,20], a = 15, b = 13, x = 11\n Output: -1\n Example 3:\n Input: forbidden = [1,6,2,14,5,17,4], a = 16, b = 9, x = 7\n Output: 2\n Explanation: One jump forward (0 -> 16) then one jump backward (16 -> 7) will get the bug home.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1655, - "title": "Distribute Repeating Integers", - "question": "class Solution:\n def canDistribute(self, nums: List[int], quantity: List[int]) -> bool:\n \"\"\"\n You are given an array of n integers, nums, where there are at most 50 unique values in the array. You are also given an array of m customer order quantities, quantity, where quantity[i] is the amount of integers the ith customer ordered. Determine if it is possible to distribute nums such that:\n The ith customer gets exactly quantity[i] integers,\n The integers the ith customer gets are all equal, and\n Every customer is satisfied.\n Return true if it is possible to distribute nums according to the above conditions.\n Example 1:\n Input: nums = [1,2,3,4], quantity = [2]\n Output: false\n Explanation: The 0th customer cannot be given two different integers.\n Example 2:\n Input: nums = [1,2,3,3], quantity = [2]\n Output: true\n Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used.\n Example 3:\n Input: nums = [1,1,2,2], quantity = [2,2]\n Output: true\n Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1640, - "title": "Check Array Formation Through Concatenation", - "question": "class Solution:\n def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:\n \"\"\"\n 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].\n Return true if it is possible to form the array arr from pieces. Otherwise, return false.\n Example 1:\n Input: arr = [15,88], pieces = [[88],[15]]\n Output: true\n Explanation: Concatenate [15] then [88]\n Example 2:\n Input: arr = [49,18,16], pieces = [[16,18,49]]\n Output: false\n Explanation: Even though the numbers match, we cannot reorder pieces[0].\n Example 3:\n Input: arr = [91,4,64,78], pieces = [[78],[4,64],[91]]\n Output: true\n Explanation: Concatenate [91] then [4,64] then [78]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1641, - "title": "Count Sorted Vowel Strings", - "question": "class Solution:\n def countVowelStrings(self, n: int) -> int:\n \"\"\"\n 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.\n A 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:\n Input: n = 1\n Output: 5\n Explanation: The 5 sorted strings that consist of vowels only are [\"a\",\"e\",\"i\",\"o\",\"u\"].\n Example 2:\n Input: n = 2\n Output: 15\n Explanation: 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\"].\n Note that \"ea\" is not a valid string since 'e' comes after 'a' in the alphabet.\n Example 3:\n Input: n = 33\n Output: 66045\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1642, - "title": "Furthest Building You Can Reach", - "question": "class Solution:\n def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:\n \"\"\"\n You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.\n You start your journey from building 0 and move to the next building by possibly using bricks or ladders.\n While moving from building i to building i+1 (0-indexed),\n If the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks.\n If 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.\n Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.\n Example 1:\n Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1\n Output: 4\n Explanation: 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.\n It is impossible to go beyond building 4 because you do not have any more bricks or ladders.\n Example 2:\n Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2\n Output: 7\n Example 3:\n Input: heights = [14,3,19,3], bricks = 17, ladders = 0\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1668, - "title": "Maximum Repeating Substring", - "question": "class Solution:\n def maxRepeating(self, sequence: str, word: str) -> int:\n \"\"\"\n 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.\n Given strings sequence and word, return the maximum k-repeating value of word in sequence.\n Example 1:\n Input: sequence = \"ababc\", word = \"ab\"\n Output: 2\n Explanation: \"abab\" is a substring in \"ababc\".\n Example 2:\n Input: sequence = \"ababc\", word = \"ba\"\n Output: 1\n Explanation: \"ba\" is a substring in \"ababc\". \"baba\" is not a substring in \"ababc\".\n Example 3:\n Input: sequence = \"ababc\", word = \"ac\"\n Output: 0\n Explanation: \"ac\" is not a substring in \"ababc\". \n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1669, - "title": "Merge In Between Linked Lists", - "question": "class Solution:\n def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n \"\"\"\n You are given two linked lists: list1 and list2 of sizes n and m respectively.\n Remove list1's nodes from the ath node to the bth node, and put list2 in their place.\n The blue edges and nodes in the following figure indicate the result:\n Build the result list and return its head.\n Example 1:\n Input: list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]\n Output: [0,1,2,1000000,1000001,1000002,5]\n Explanation: We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.\n Example 2:\n Input: list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]\n Output: [0,1,1000000,1000001,1000002,1000003,1000004,6]\n Explanation: The blue edges and nodes in the above figure indicate the result.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1671, - "title": "Minimum Number of Removals to Make Mountain Array", - "question": "class Solution:\n def minimumMountainRemovals(self, nums: List[int]) -> int:\n \"\"\"\n You may recall that an array arr is a mountain array if and only if:\n arr.length >= 3\n There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:\n arr[0] < arr[1] < ... < arr[i - 1] < arr[i]\n arr[i] > arr[i + 1] > ... > arr[arr.length - 1]\n Given an integer array nums\u200b\u200b\u200b, return the minimum number of elements to remove to make nums\u200b\u200b\u200b a mountain array.\n Example 1:\n Input: nums = [1,3,1]\n Output: 0\n Explanation: The array itself is a mountain array so we do not need to remove any elements.\n Example 2:\n Input: nums = [2,1,1,5,6,2,3,1]\n Output: 3\n Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1670, - "title": "Design Front Middle Back Queue", - "question": "class FrontMiddleBackQueue:\n def __init__(self):\n def pushFront(self, val: int) -> None:\n def pushMiddle(self, val: int) -> None:\n def pushBack(self, val: int) -> None:\n def popFront(self) -> int:\n def popMiddle(self) -> int:\n def popBack(self) -> int:\n \"\"\"\n Design a queue that supports push and pop operations in the front, middle, and back.\n Implement the FrontMiddleBack class:\n FrontMiddleBack() Initializes the queue.\n void pushFront(int val) Adds val to the front of the queue.\n void pushMiddle(int val) Adds val to the middle of the queue.\n void pushBack(int val) Adds val to the back of the queue.\n int popFront() Removes the front element of the queue and returns it. If the queue is empty, return -1.\n int popMiddle() Removes the middle element of the queue and returns it. If the queue is empty, return -1.\n int popBack() Removes the back element of the queue and returns it. If the queue is empty, return -1.\n Notice that when there are two middle position choices, the operation is performed on the frontmost middle position choice. For example:\n Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5].\n Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6].\n Example 1:\n Input:\n [\"FrontMiddleBackQueue\", \"pushFront\", \"pushBack\", \"pushMiddle\", \"pushMiddle\", \"popFront\", \"popMiddle\", \"popMiddle\", \"popBack\", \"popFront\"]\n [[], [1], [2], [3], [4], [], [], [], [], []]\n Output:\n [null, null, null, null, null, 1, 3, 4, 2, -1]\n Explanation:\n FrontMiddleBackQueue q = new FrontMiddleBackQueue();\n q.pushFront(1); // [1]\n q.pushBack(2); // [1, 2]\n q.pushMiddle(3); // [1, 3, 2]\n q.pushMiddle(4); // [1, 4, 3, 2]\n q.popFront(); // return 1 -> [4, 3, 2]\n q.popMiddle(); // return 3 -> [4, 2]\n q.popMiddle(); // return 4 -> [2]\n q.popBack(); // return 2 -> []\n q.popFront(); // return -1 -> [] (The queue is empty)\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1646, - "title": "Get Maximum in Generated Array", - "question": "class Solution:\n def getMaximumGenerated(self, n: int) -> int:\n \"\"\"\n You are given an integer n. A 0-indexed integer array nums of length n + 1 is generated in the following way:\n nums[0] = 0\n nums[1] = 1\n nums[2 * i] = nums[i] when 2 <= 2 * i <= n\n nums[2 * i + 1] = nums[i] + nums[i + 1] when 2 <= 2 * i + 1 <= n\n Return the maximum integer in the array nums\u200b\u200b\u200b.\n Example 1:\n Input: n = 7\n Output: 3\n Explanation: 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\n Hence, nums = [0,1,1,2,1,3,2,3], and the maximum is max(0,1,1,2,1,3,2,3) = 3.\n Example 2:\n Input: n = 2\n Output: 1\n Explanation: According to the given rules, nums = [0,1,1]. The maximum is max(0,1,1) = 1.\n Example 3:\n Input: n = 3\n Output: 2\n Explanation: According to the given rules, nums = [0,1,1,2]. The maximum is max(0,1,1,2) = 2.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1647, - "title": "Minimum Deletions to Make Character Frequencies Unique", - "question": "class Solution:\n def minDeletions(self, s: str) -> int:\n \"\"\"\n A string s is called good if there are no two different characters in s that have the same frequency.\n Given a string s, return the minimum number of characters you need to delete to make s good.\n The 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:\n Input: s = \"aab\"\n Output: 0\n Explanation: s is already good.\n Example 2:\n Input: s = \"aaabbbcc\"\n Output: 2\n Explanation: You can delete two 'b's resulting in the good string \"aaabcc\".\n Another way it to delete one 'b' and one 'c' resulting in the good string \"aaabbc\".\n Example 3:\n Input: s = \"ceabaacb\"\n Output: 2\n Explanation: You can delete both 'c's resulting in the good string \"eabaab\".\n Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1648, - "title": "Sell Diminishing-Valued Colored Balls", - "question": "class Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n \"\"\"\n You have an inventory of different colored balls, and there is a customer that wants orders balls of any color.\n The 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).\n You 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.\n Return 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:\n Input: inventory = [2,5], orders = 4\n Output: 14\n Explanation: Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).\n The maximum total value is 2 + 5 + 4 + 3 = 14.\n Example 2:\n Input: inventory = [3,5], orders = 6\n Output: 19\n Explanation: Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).\n The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1649, - "title": "Create Sorted Array through Instructions", - "question": "class Solution:\n def createSortedArray(self, instructions: List[int]) -> int:\n \"\"\"\n Given an integer array instructions, you are asked to create a sorted array from the elements in instructions. You start with an empty container nums. For each element from left to right in instructions, insert it into nums. The cost of each insertion is the minimum of the following:\r\n The number of elements currently in nums that are strictly less than instructions[i].\r\n The number of elements currently in nums that are strictly greater than instructions[i].\r\n For example, if inserting element 3 into nums = [1,2,3,5], the cost of insertion is min(2, 1) (elements 1 and 2 are less than 3, element 5 is greater than 3) and nums will become [1,2,3,3,5].\r\n Return the total cost to insert all elements from instructions into nums. Since the answer may be large, return it modulo 109 + 7\r\n Example 1:\r\n Input: instructions = [1,5,6,2]\r\n Output: 1\r\n Explanation: Begin with nums = [].\r\n Insert 1 with cost min(0, 0) = 0, now nums = [1].\r\n Insert 5 with cost min(1, 0) = 0, now nums = [1,5].\r\n Insert 6 with cost min(2, 0) = 0, now nums = [1,5,6].\r\n Insert 2 with cost min(1, 2) = 1, now nums = [1,2,5,6].\r\n The total cost is 0 + 0 + 0 + 1 = 1.\r\n Example 2:\r\n Input: instructions = [1,2,3,6,5,4]\r\n Output: 3\r\n Explanation: Begin with nums = [].\r\n Insert 1 with cost min(0, 0) = 0, now nums = [1].\r\n Insert 2 with cost min(1, 0) = 0, now nums = [1,2].\r\n Insert 3 with cost min(2, 0) = 0, now nums = [1,2,3].\r\n Insert 6 with cost min(3, 0) = 0, now nums = [1,2,3,6].\r\n Insert 5 with cost min(3, 1) = 1, now nums = [1,2,3,5,6].\r\n Insert 4 with cost min(3, 2) = 2, now nums = [1,2,3,4,5,6].\r\n The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.\r\n Example 3:\r\n Input: instructions = [1,3,3,3,2,4,2,1,2]\r\n Output: 4\r\n Explanation: Begin with nums = [].\r\n Insert 1 with cost min(0, 0) = 0, now nums = [1].\r\n Insert 3 with cost min(1, 0) = 0, now nums = [1,3].\r\n Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3].\r\n Insert 3 with cost min(1, 0) = 0, now nums = [1,3,3,3].\r\n Insert 2 with cost min(1, 3) = 1, now nums = [1,2,3,3,3].\r\n Insert 4 with cost min(5, 0) = 0, now nums = [1,2,3,3,3,4].\r\n \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(1, 4) = 1, now nums = [1,2,2,3,3,3,4].\r\n \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 1 with cost min(0, 6) = 0, now nums = [1,1,2,2,3,3,3,4].\r\n \u200b\u200b\u200b\u200b\u200b\u200b\u200bInsert 2 with cost min(2, 4) = 2, now nums = [1,1,2,2,2,3,3,3,4].\r\n The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1656, - "title": "Design an Ordered Stream", - "question": "class OrderedStream:\n def __init__(self, n: int):\n def insert(self, idKey: int, value: str) -> List[str]:\n \"\"\"\n There is a stream of n (idKey, value) pairs arriving in an arbitrary order, where idKey is an integer between 1 and n and value is a string. No two pairs have the same id.\n Design a stream that returns the values in increasing order of their IDs by returning a chunk (list) of values after each insertion. The concatenation of all the chunks should result in a list of the sorted values.\n Implement the OrderedStream class:\n OrderedStream(int n) Constructs the stream to take n values.\n String[] insert(int idKey, String value) Inserts the pair (idKey, value) into the stream, then returns the largest possible chunk of currently inserted values that appear next in the order.\n Example:\n Input\n [\"OrderedStream\", \"insert\", \"insert\", \"insert\", \"insert\", \"insert\"]\n [[5], [3, \"ccccc\"], [1, \"aaaaa\"], [2, \"bbbbb\"], [5, \"eeeee\"], [4, \"ddddd\"]]\n Output\n [null, [], [\"aaaaa\"], [\"bbbbb\", \"ccccc\"], [], [\"ddddd\", \"eeeee\"]]\n Explanation\n // Note that the values ordered by ID is [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"].\n OrderedStream os = new OrderedStream(5);\n os.insert(3, \"ccccc\"); // Inserts (3, \"ccccc\"), returns [].\n os.insert(1, \"aaaaa\"); // Inserts (1, \"aaaaa\"), returns [\"aaaaa\"].\n os.insert(2, \"bbbbb\"); // Inserts (2, \"bbbbb\"), returns [\"bbbbb\", \"ccccc\"].\n os.insert(5, \"eeeee\"); // Inserts (5, \"eeeee\"), returns [].\n os.insert(4, \"ddddd\"); // Inserts (4, \"ddddd\"), returns [\"ddddd\", \"eeeee\"].\n // Concatentating all the chunks returned:\n // [] + [\"aaaaa\"] + [\"bbbbb\", \"ccccc\"] + [] + [\"ddddd\", \"eeeee\"] = [\"aaaaa\", \"bbbbb\", \"ccccc\", \"ddddd\", \"eeeee\"]\n // The resulting order is the same as the order above.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1658, - "title": "Minimum Operations to Reduce X to Zero", - "question": "class Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n \"\"\"\n 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.\n Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.\n Example 1:\n Input: nums = [1,1,4,2,3], x = 5\n Output: 2\n Explanation: The optimal solution is to remove the last two elements to reduce x to zero.\n Example 2:\n Input: nums = [5,6,7,8,9], x = 4\n Output: -1\n Example 3:\n Input: nums = [3,2,20,1,1,3], x = 10\n Output: 5\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1657, - "title": "Determine if Two Strings Are Close", - "question": "class Solution:\n def closeStrings(self, word1: str, word2: str) -> bool:\n \"\"\"\n Two strings are considered close if you can attain one from the other using the following operations:\n Operation 1: Swap any two existing characters.\n For example, abcde -> aecdb\n Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.\n For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's)\n You can use the operations on either string as many times as necessary.\n Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.\n Example 1:\n Input: word1 = \"abc\", word2 = \"bca\"\n Output: true\n Explanation: You can attain word2 from word1 in 2 operations.\n Apply Operation 1: \"abc\" -> \"acb\"\n Apply Operation 1: \"acb\" -> \"bca\"\n Example 2:\n Input: word1 = \"a\", word2 = \"aa\"\n Output: false\n Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.\n Example 3:\n Input: word1 = \"cabbba\", word2 = \"abbccc\"\n Output: true\n Explanation: You can attain word2 from word1 in 3 operations.\n Apply Operation 1: \"cabbba\" -> \"caabbb\"\n Apply Operation 2: \"caabbb\" -> \"baaccc\"\n Apply Operation 2: \"baaccc\" -> \"abbccc\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1659, - "title": "Maximize Grid Happiness", - "question": "class Solution:\n def getMaxGridHappiness(self, m: int, n: int, introvertsCount: int, extrovertsCount: int) -> int:\n \"\"\"\n You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and there are two types of people: introverts and extroverts. There are introvertsCount introverts and extrovertsCount extroverts.\n You should decide how many people you want to live in the grid and assign each of them one grid cell. Note that you do not have to have all the people living in the grid.\n The happiness of each person is calculated as follows:\n Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).\n Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).\n Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.\n The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.\n Example 1:\n Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2\n Output: 240\n Explanation: Assume the grid is 1-indexed with coordinates (row, column).\n We 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\n The grid happiness is 120 + 60 + 60 = 240.\n The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.\n Example 2:\n Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1\n Output: 260\n Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).\n - Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n - Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80\n - Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90\n The grid happiness is 90 + 80 + 90 = 260.\n Example 3:\n Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0\n Output: 240\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1662, - "title": "Check If Two String Arrays are Equivalent", - "question": "class Solution:\n def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:\n \"\"\"\n Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise.\n A string is represented by an array if the array elements concatenated in order forms the string.\n Example 1:\n Input: word1 = [\"ab\", \"c\"], word2 = [\"a\", \"bc\"]\n Output: true\n Explanation:\n word1 represents string \"ab\" + \"c\" -> \"abc\"\n word2 represents string \"a\" + \"bc\" -> \"abc\"\n The strings are the same, so return true.\n Example 2:\n Input: word1 = [\"a\", \"cb\"], word2 = [\"ab\", \"c\"]\n Output: false\n Example 3:\n Input: word1 = [\"abc\", \"d\", \"defg\"], word2 = [\"abcddefg\"]\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1663, - "title": "Smallest String With A Given Numeric Value", - "question": "class Solution:\n def getSmallestString(self, n: int, k: int) -> str:\n \"\"\"\n 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.\n The 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.\n You are given two integers n and k. Return the lexicographically smallest string with length equal to n and numeric value equal to k.\n Note 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:\n Input: n = 3, k = 27\n Output: \"aay\"\n Explanation: The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.\n Example 2:\n Input: n = 5, k = 73\n Output: \"aaszz\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1664, - "title": "Ways to Make a Fair Array", - "question": "class Solution:\n def waysToMakeFair(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n For example, if nums = [6,1,7,4,1]:\n Choosing to remove index 1 results in nums = [6,7,4,1].\n Choosing to remove index 2 results in nums = [6,1,4,1].\n Choosing to remove index 4 results in nums = [6,1,7,4].\n An array is fair if the sum of the odd-indexed values equals the sum of the even-indexed values.\n Return the number of indices that you could choose such that after the removal, nums is fair. \n Example 1:\n Input: nums = [2,1,6,4]\n Output: 1\n Explanation:\n Remove index 0: [1,6,4] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.\n Remove index 1: [2,6,4] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair.\n Remove index 2: [2,1,4] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.\n Remove index 3: [2,1,6] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.\n There is 1 index that you can remove to make nums fair.\n Example 2:\n Input: nums = [1,1,1]\n Output: 3\n Explanation: You can remove any index and the remaining array is fair.\n Example 3:\n Input: nums = [1,2,3]\n Output: 0\n Explanation: You cannot make a fair array after removing any index.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1665, - "title": "Minimum Initial Energy to Finish Tasks", - "question": "class Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n \"\"\"\n You are given an array tasks where tasks[i] = [actuali, minimumi]:\n actuali is the actual amount of energy you spend to finish the ith task.\n minimumi is the minimum amount of energy you require to begin the ith task.\n For example, if the task is [10, 12] and your current energy is 11, you cannot start this task. However, if your current energy is 13, you can complete this task, and your energy will be 3 after finishing it.\n You can finish the tasks in any order you like.\n Return the minimum initial amount of energy you will need to finish all the tasks.\n Example 1:\n Input: tasks = [[1,2],[2,4],[4,8]]\n Output: 8\n Explanation:\n Starting with 8 energy, we finish the tasks in the following order:\n - 3rd task. Now energy = 8 - 4 = 4.\n - 2nd task. Now energy = 4 - 2 = 2.\n - 1st task. Now energy = 2 - 1 = 1.\n Notice that even though we have leftover energy, starting with 7 energy does not work because we cannot do the 3rd task.\n Example 2:\n Input: tasks = [[1,3],[2,4],[10,11],[10,12],[8,9]]\n Output: 32\n Explanation:\n Starting with 32 energy, we finish the tasks in the following order:\n - 1st task. Now energy = 32 - 1 = 31.\n - 2nd task. Now energy = 31 - 2 = 29.\n - 3rd task. Now energy = 29 - 10 = 19.\n - 4th task. Now energy = 19 - 10 = 9.\n - 5th task. Now energy = 9 - 8 = 1.\n Example 3:\n Input: tasks = [[1,7],[2,8],[3,9],[4,10],[5,11],[6,12]]\n Output: 27\n Explanation:\n Starting with 27 energy, we finish the tasks in the following order:\n - 5th task. Now energy = 27 - 5 = 22.\n - 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1684, - "title": "Count the Number of Consistent Strings", - "question": "class Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n \"\"\"\n 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.\n Return the number of consistent strings in the array words.\n Example 1:\n Input: allowed = \"ab\", words = [\"ad\",\"bd\",\"aaab\",\"baa\",\"badab\"]\n Output: 2\n Explanation: Strings \"aaab\" and \"baa\" are consistent since they only contain characters 'a' and 'b'.\n Example 2:\n Input: allowed = \"abc\", words = [\"a\",\"b\",\"c\",\"ab\",\"ac\",\"bc\",\"abc\"]\n Output: 7\n Explanation: All strings are consistent.\n Example 3:\n Input: allowed = \"cad\", words = [\"cc\",\"acd\",\"b\",\"ba\",\"bac\",\"bad\",\"ac\",\"d\"]\n Output: 4\n Explanation: Strings \"cc\", \"acd\", \"ac\", and \"d\" are consistent.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1685, - "title": "Sum of Absolute Differences in a Sorted Array", - "question": "class Solution:\n def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:\n \"\"\"\n You are given an integer array nums sorted in non-decreasing order.\n Build 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.\n In 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:\n Input: nums = [2,3,5]\n Output: [4,3,5]\n Explanation: Assuming the arrays are 0-indexed, then\n result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,\n result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,\n result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.\n Example 2:\n Input: nums = [1,4,6,8,10]\n Output: [24,15,13,15,21]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1686, - "title": "Stone Game VI", - "question": "class Solution:\n def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int:\n \"\"\"\n Alice and Bob take turns playing a game, with Alice starting first.\n There 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.\n You 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.\n The 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.\n Determine the result of the game, and:\n If Alice wins, return 1.\n If Bob wins, return -1.\n If the game results in a draw, return 0.\n Example 1:\n Input: aliceValues = [1,3], bobValues = [2,1]\n Output: 1\n Explanation:\n If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.\n Bob can only choose stone 0, and will only receive 2 points.\n Alice wins.\n Example 2:\n Input: aliceValues = [1,2], bobValues = [3,1]\n Output: 0\n Explanation:\n If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.\n Draw.\n Example 3:\n Input: aliceValues = [2,4,3], bobValues = [1,6,7]\n Output: -1\n Explanation:\n Regardless of how Alice plays, Bob will be able to have more points than Alice.\n For 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.\n Bob wins.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1687, - "title": "Delivering Boxes from Storage to Ports", - "question": "class Solution:\n def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int:\n \"\"\"\n You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry.\n You are given an array boxes, where boxes[i] = [ports\u200b\u200bi\u200b, weighti], and three integers portsCount, maxBoxes, and maxWeight.\n ports\u200b\u200bi is the port where you need to deliver the ith box and weightsi is the weight of the ith box.\n portsCount is the number of ports.\n maxBoxes and maxWeight are the respective box and weight limits of the ship.\n The boxes need to be delivered in the order they are given. The ship will follow these steps:\n The ship will take some number of boxes from the boxes queue, not violating the maxBoxes and maxWeight constraints.\n For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered.\n The ship then makes a return trip to storage to take more boxes from the queue.\n The ship must end at storage after all the boxes have been delivered.\n Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.\n Example 1:\n Input: boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3\n Output: 4\n Explanation: The optimal strategy is as follows: \n - The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.\n So the total number of trips is 4.\n Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).\n Example 2:\n Input: boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6\n Output: 6\n Explanation: The optimal strategy is as follows: \n - The ship takes the first box, goes to port 1, then returns to storage. 2 trips.\n - 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.\n So the total number of trips is 2 + 2 + 2 = 6.\n Example 3:\n Input: boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7\n Output: 6\n Explanation: The optimal strategy is as follows:\n - The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.\n - 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.\n So the total number of trips is 2 + 2 + 2 = 6.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1672, - "title": "Richest Customer Wealth", - "question": "class Solution:\n def maximumWealth(self, accounts: List[List[int]]) -> int:\n \"\"\"\n You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b customer has in the j\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b bank. Return the wealth that the richest customer has.\n A 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:\n Input: accounts = [[1,2,3],[3,2,1]]\n Output: 6\n Explanation:\n 1st customer has wealth = 1 + 2 + 3 = 6\n 2nd customer has wealth = 3 + 2 + 1 = 6\n Both customers are considered the richest with a wealth of 6 each, so return 6.\n Example 2:\n Input: accounts = [[1,5],[7,3],[3,5]]\n Output: 10\n Explanation: \n 1st customer has wealth = 6\n 2nd customer has wealth = 10 \n 3rd customer has wealth = 8\n The 2nd customer is the richest with a wealth of 10.\n Example 3:\n Input: accounts = [[2,8,7],[7,1,3],[1,9,5]]\n Output: 17\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1673, - "title": "Find the Most Competitive Subsequence", - "question": "class Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n \"\"\"\n Given an integer array nums and a positive integer k, return the most competitive subsequence of nums of size k.\n An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array.\n We 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:\n Input: nums = [3,5,2,6], k = 2\n Output: [2,6]\n Explanation: Among the set of every possible subsequence: {[3,5], [3,2], [3,6], [5,2], [5,6], [2,6]}, [2,6] is the most competitive.\n Example 2:\n Input: nums = [2,4,3,3,5,4,9,6], k = 4\n Output: [2,3,3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1674, - "title": "Minimum Moves to Make Array Complementary", - "question": "class Solution:\n def minMoves(self, nums: List[int], limit: int) -> int:\n \"\"\"\n 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.\n The 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.\n Return the minimum number of moves required to make nums complementary.\n Example 1:\n Input: nums = [1,2,4,3], limit = 4\n Output: 1\n Explanation: In 1 move, you can change nums to [1,2,2,3] (underlined elements are changed).\n nums[0] + nums[3] = 1 + 3 = 4.\n nums[1] + nums[2] = 2 + 2 = 4.\n nums[2] + nums[1] = 2 + 2 = 4.\n nums[3] + nums[0] = 3 + 1 = 4.\n Therefore, nums[i] + nums[n-1-i] = 4 for every i, so nums is complementary.\n Example 2:\n Input: nums = [1,2,2,1], limit = 2\n Output: 2\n Explanation: In 2 moves, you can change nums to [2,2,2,2]. You cannot change any number to 3 since 3 > limit.\n Example 3:\n Input: nums = [1,2,1,2], limit = 2\n Output: 0\n Explanation: nums is already complementary.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1675, - "title": "Minimize Deviation in Array", - "question": "class Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n \"\"\"\n You are given an array nums of n positive integers.\n You can perform two types of operations on any element of the array any number of times:\n If the element is even, divide it by 2.\n For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].\n If the element is odd, multiply it by 2.\n For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].\n The deviation of the array is the maximum difference between any two elements in the array.\n Return the minimum deviation the array can have after performing some number of operations.\n Example 1:\n Input: nums = [1,2,3,4]\n Output: 1\n Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.\n Example 2:\n Input: nums = [4,1,5,20,3]\n Output: 3\n Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.\n Example 3:\n Input: nums = [2,10,8]\n Output: 3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1678, - "title": "Goal Parser Interpretation", - "question": "class Solution:\n def interpret(self, command: str) -> str:\n \"\"\"\n 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.\n Given the string command, return the Goal Parser's interpretation of command.\n Example 1:\n Input: command = \"G()(al)\"\n Output: \"Goal\"\n Explanation: The Goal Parser interprets the command as follows:\n G -> G\n () -> o\n (al) -> al\n The final concatenated result is \"Goal\".\n Example 2:\n Input: command = \"G()()()()(al)\"\n Output: \"Gooooal\"\n Example 3:\n Input: command = \"(al)G(al)()()G\"\n Output: \"alGalooG\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1679, - "title": "Max Number of K-Sum Pairs", - "question": "class Solution:\n def maxOperations(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an integer array nums and an integer k.\n In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.\n Return the maximum number of operations you can perform on the array.\n Example 1:\n Input: nums = [1,2,3,4], k = 5\n Output: 2\n Explanation: 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 = []\n There are no more pairs that sum up to 5, hence a total of 2 operations.\n Example 2:\n Input: nums = [3,1,3,4,3], k = 6\n Output: 1\n Explanation: Starting with nums = [3,1,3,4,3]:\n - Remove the first two 3's, then nums = [1,4,3]\n There are no more pairs that sum up to 6, hence a total of 1 operation.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1681, - "title": "Minimum Incompatibility", - "question": "class Solution:\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an integer array nums\u200b\u200b\u200b and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.\n A subset's incompatibility is the difference between the maximum and minimum elements in that array.\n Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.\n A subset is a group integers that appear in the array with no particular order.\n Example 1:\n Input: nums = [1,2,1,4], k = 2\n Output: 4\n Explanation: The optimal distribution of subsets is [1,2] and [1,4].\n The incompatibility is (2-1) + (4-1) = 4.\n Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.\n Example 2:\n Input: nums = [6,3,8,1,3,1,2,2], k = 4\n Output: 6\n Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].\n The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.\n Example 3:\n Input: nums = [5,3,3,6,3,3], k = 3\n Output: -1\n Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1680, - "title": "Concatenation of Consecutive Binary Numbers", - "question": "class Solution:\n def concatenatedBinary(self, n: int) -> int:\n \"\"\"\n 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:\n Input: n = 1\n Output: 1\n Explanation: \"1\" in binary corresponds to the decimal value 1. \n Example 2:\n Input: n = 3\n Output: 27\n Explanation: In binary, 1, 2, and 3 corresponds to \"1\", \"10\", and \"11\".\n After concatenating them, we have \"11011\", which corresponds to the decimal value 27.\n Example 3:\n Input: n = 12\n Output: 505379714\n Explanation: The concatenation results in \"1101110010111011110001001101010111100\".\n The decimal value of that is 118505380540.\n After modulo 109 + 7, the result is 505379714.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1700, - "title": "Number of Students Unable to Eat Lunch", - "question": "class Solution:\n def countStudents(self, students: List[int], sandwiches: List[int]) -> int:\n \"\"\"\n 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.\n The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a stack. At each step:\n If 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.\n Otherwise, they will leave it and go to the queue's end.\n This continues until none of the queue students want to take the top sandwich and are thus unable to eat.\n You are given two integer arrays students and sandwiches where sandwiches[i] is the type of the i\u200b\u200b\u200b\u200b\u200b\u200bth sandwich in the stack (i = 0 is the top of the stack) and students[j] is the preference of the j\u200b\u200b\u200b\u200b\u200b\u200bth 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:\n Input: students = [1,1,0,0], sandwiches = [0,1,0,1]\n Output: 0 \n Explanation:\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 = [].\n Hence all students are able to eat.\n Example 2:\n Input: students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]\n Output: 3\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1701, - "title": "Average Waiting Time", - "question": "class Solution:\n def averageWaitingTime(self, customers: List[List[int]]) -> float:\n \"\"\"\n There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrivali, timei]:\n arrivali is the arrival time of the ith customer. The arrival times are sorted in non-decreasing order.\n timei is the time needed to prepare the order of the ith customer.\n When 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.\n Return the average waiting time of all customers. Solutions within 10-5 from the actual answer are considered accepted.\n Example 1:\n Input: customers = [[1,2],[2,5],[4,3]]\n Output: 5.00000\n Explanation:\n 1) 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.\n 2) 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.\n 3) 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.\n So the average waiting time = (2 + 6 + 7) / 3 = 5.\n Example 2:\n Input: customers = [[5,2],[5,4],[10,3],[20,1]]\n Output: 3.25000\n Explanation:\n 1) 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.\n 2) 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.\n 3) 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.\n 4) 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.\n So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1702, - "title": "Maximum Binary String After Change", - "question": "class Solution:\n def maximumBinaryString(self, binary: str) -> str:\n \"\"\"\n 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:\n Operation 1: If the number contains the substring \"00\", you can replace it with \"10\".\n For example, \"00010\" -> \"10010\"\n Operation 2: If the number contains the substring \"10\", you can replace it with \"01\".\n For example, \"00010\" -> \"00001\"\n Return 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:\n Input: binary = \"000110\"\n Output: \"111011\"\n Explanation: A valid transformation sequence can be:\n \"000110\" -> \"000101\" \n \"000101\" -> \"100101\" \n \"100101\" -> \"110101\" \n \"110101\" -> \"110011\" \n \"110011\" -> \"111011\"\n Example 2:\n Input: binary = \"01\"\n Output: \"01\"\n Explanation: \"01\" cannot be transformed any further.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1703, - "title": "Minimum Adjacent Swaps for K Consecutive Ones", - "question": "class Solution:\n def minMoves(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an integer array, nums, and an integer k. nums comprises of only 0's and 1's. In one move, you can choose two adjacent indices and swap their values.\n Return the minimum number of moves required so that nums has k consecutive 1's.\n Example 1:\n Input: nums = [1,0,0,1,0,1], k = 2\n Output: 1\n Explanation: In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.\n Example 2:\n Input: nums = [1,0,0,0,0,0,1,1], k = 3\n Output: 5\n Explanation: In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].\n Example 3:\n Input: nums = [1,1,0,1], k = 2\n Output: 0\n Explanation: nums already has 2 consecutive 1's.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1688, - "title": "Count of Matches in Tournament", - "question": "class Solution:\n def numberOfMatches(self, n: int) -> int:\n \"\"\"\n You are given an integer n, the number of teams in a tournament that has strange rules:\n If 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.\n If 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.\n Return the number of matches played in the tournament until a winner is decided.\n Example 1:\n Input: n = 7\n Output: 6\n Explanation: 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.\n Total number of matches = 3 + 2 + 1 = 6.\n Example 2:\n Input: n = 14\n Output: 13\n Explanation: 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.\n Total number of matches = 7 + 3 + 2 + 1 = 13.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1689, - "title": "Partitioning Into Minimum Number Of Deci-Binary Numbers", - "question": "class Solution:\n def minPartitions(self, n: str) -> int:\n \"\"\"\n 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.\n Given 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:\n Input: n = \"32\"\n Output: 3\n Explanation: 10 + 11 + 11 = 32\n Example 2:\n Input: n = \"82734\"\n Output: 8\n Example 3:\n Input: n = \"27346209830709182346\"\n Output: 9\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1690, - "title": "Stone Game VII", - "question": "class Solution:\n def stoneGameVII(self, stones: List[int]) -> int:\n \"\"\"\n Alice and Bob take turns playing a game, with Alice starting first.\n There 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.\n Bob 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.\n Given 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:\n Input: stones = [5,3,1,4,2]\n Output: 6\n Explanation: \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 = [].\n The score difference is 18 - 12 = 6.\n Example 2:\n Input: stones = [7,90,5,1,100,10,10,2]\n Output: 122\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1694, - "title": "Reformat Phone Number", - "question": "class Solution:\n def reformatNumber(self, number: str) -> str:\n \"\"\"\n You are given a phone number as a string number. number consists of digits, spaces ' ', and/or dashes '-'.\n You 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:\n 2 digits: A single block of length 2.\n 3 digits: A single block of length 3.\n 4 digits: Two blocks of length 2 each.\n The 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.\n Return the phone number after formatting.\n Example 1:\n Input: number = \"1-23-45 6\"\n Output: \"123-456\"\n Explanation: The digits are \"123456\".\n Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\n Step 2: There are 3 digits remaining, so put them in a single block of length 3. The 2nd block is \"456\".\n Joining the blocks gives \"123-456\".\n Example 2:\n Input: number = \"123 4-567\"\n Output: \"123-45-67\"\n Explanation: The digits are \"1234567\".\n Step 1: There are more than 4 digits, so group the next 3 digits. The 1st block is \"123\".\n Step 2: There are 4 digits left, so split them into two blocks of length 2. The blocks are \"45\" and \"67\".\n Joining the blocks gives \"123-45-67\".\n Example 3:\n Input: number = \"123 4-5678\"\n Output: \"123-456-78\"\n Explanation: The digits are \"12345678\".\n Step 1: The 1st block is \"123\".\n Step 2: The 2nd block is \"456\".\n Step 3: There are 2 digits left, so put them in a single block of length 2. The 3rd block is \"78\".\n Joining the blocks gives \"123-456-78\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1695, - "title": "Maximum Erasure Value", - "question": "class Solution:\n def maximumUniqueSubarray(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Return the maximum score you can get by erasing exactly one subarray.\n An 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:\n Input: nums = [4,2,4,5,6]\n Output: 17\n Explanation: The optimal subarray here is [2,4,5,6].\n Example 2:\n Input: nums = [5,2,1,2,5,2,1,2,5]\n Output: 8\n Explanation: The optimal subarray here is [5,2,1] or [1,2,5].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1696, - "title": "Jump Game VI", - "question": "class Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given a 0-indexed integer array nums and an integer k.\n You 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.\n You 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.\n Return the maximum score you can get.\n Example 1:\n Input: nums = [1,-1,-2,4,-7,3], k = 2\n Output: 7\n Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.\n Example 2:\n Input: nums = [10,-5,-2,4,0,3], k = 3\n Output: 17\n Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.\n Example 3:\n Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1697, - "title": "Checking Existence of Edge Length Limited Paths", - "question": "class Solution:\n def distanceLimitedPathsExist(self, n: int, edgeList: List[List[int]], queries: List[List[int]]) -> List[bool]:\n \"\"\"\n An undirected graph of n nodes is defined by edgeList, where edgeList[i] = [ui, vi, disi] denotes an edge between nodes ui and vi with distance disi. Note that there may be multiple edges between two nodes.\n Given an array queries, where queries[j] = [pj, qj, limitj], your task is to determine for each queries[j] whether there is a path between pj and qj such that each edge on the path has a distance strictly less than limitj .\n Return a boolean array answer, where answer.length == queries.length and the jth value of answer is true if there is a path for queries[j] is true, and false otherwise.\n Example 1:\n Input: n = 3, edgeList = [[0,1,2],[1,2,4],[2,0,8],[1,0,16]], queries = [[0,1,2],[0,2,5]]\n Output: [false,true]\n Explanation: The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.\n For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.\n For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.\n Example 2:\n Input: n = 5, edgeList = [[0,1,10],[1,2,5],[2,3,9],[3,4,13]], queries = [[0,4,14],[1,4,13]]\n Output: [true,false]\n Exaplanation: The above figure shows the given graph.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1716, - "title": "Calculate Money in Leetcode Bank", - "question": "class Solution:\n def totalMoney(self, n: int) -> int:\n \"\"\"\n Hercy wants to save money for his first car. He puts money in the Leetcode bank every day.\n He 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. \n Given n, return the total amount of money he will have in the Leetcode bank at the end of the nth day.\n Example 1:\n Input: n = 4\n Output: 10\n Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.\n Example 2:\n Input: n = 10\n Output: 37\n Explanation: After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.\n Example 3:\n Input: n = 20\n Output: 96\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1717, - "title": "Maximum Score From Removing Substrings", - "question": "class Solution:\n def maximumGain(self, s: str, x: int, y: int) -> int:\n \"\"\"\n You are given a string s and two integers x and y. You can perform two types of operations any number of times.\n Remove substring \"ab\" and gain x points.\n For example, when removing \"ab\" from \"cabxbae\" it becomes \"cxbae\".\n Remove substring \"ba\" and gain y points.\n For example, when removing \"ba\" from \"cabxbae\" it becomes \"cabxe\".\n Return the maximum points you can gain after applying the above operations on s.\n Example 1:\n Input: s = \"cdbcbbaaabab\", x = 4, y = 5\n Output: 19\n Explanation:\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.\n Total score = 5 + 4 + 5 + 5 = 19.\n Example 2:\n Input: s = \"aabbaaxybbaabb\", x = 5, y = 4\n Output: 20\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1718, - "title": "Construct the Lexicographically Largest Valid Sequence", - "question": "class Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n \"\"\"\n Given an integer n, find a sequence that satisfies all of the following:\n The integer 1 occurs once in the sequence.\n Each integer between 2 and n occurs twice in the sequence.\n For every integer i between 2 and n, the distance between the two occurrences of i is exactly i.\n The distance between two numbers on the sequence, a[i] and a[j], is the absolute difference of their indices, |j - i|.\n Return the lexicographically largest sequence. It is guaranteed that under the given constraints, there is always a solution. \n A 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:\n Input: n = 3\n Output: [3,1,2,3,2]\n Explanation: [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.\n Example 2:\n Input: n = 5\n Output: [5,3,1,4,3,5,2,4,2]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1719, - "title": "Number Of Ways To Reconstruct A Tree", - "question": "class Solution:\n def checkWays(self, pairs: List[List[int]]) -> int:\n \"\"\"\n You are given an array pairs, where pairs[i] = [xi, yi], and:\n There are no duplicates.\n xi < yi\n Let ways be the number of rooted trees that satisfy the following conditions:\n The tree consists of nodes whose values appeared in pairs.\n A pair [xi, yi] exists in pairs if and only if xi is an ancestor of yi or yi is an ancestor of xi.\n Note: the tree does not have to be a binary tree.\n Two ways are considered to be different if there is at least one node that has different parents in both ways.\n Return:\n 0 if ways == 0\n 1 if ways == 1\n 2 if ways > 1\n A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root.\n An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.\n Example 1:\n Input: pairs = [[1,2],[2,3]]\n Output: 1\n Explanation: There is exactly one valid rooted tree, which is shown in the above figure.\n Example 2:\n Input: pairs = [[1,2],[2,3],[1,3]]\n Output: 2\n Explanation: There are multiple valid rooted trees. Three of them are shown in the above figures.\n Example 3:\n Input: pairs = [[1,2],[2,3],[2,4],[1,5]]\n Output: 0\n Explanation: There are no valid rooted trees.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1704, - "title": "Determine if String Halves Are Alike", - "question": "class Solution:\n def halvesAreAlike(self, s: str) -> bool:\n \"\"\"\n 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.\n Two 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.\n Return true if a and b are alike. Otherwise, return false.\n Example 1:\n Input: s = \"book\"\n Output: true\n Explanation: a = \"bo\" and b = \"ok\". a has 1 vowel and b has 1 vowel. Therefore, they are alike.\n Example 2:\n Input: s = \"textbook\"\n Output: false\n Explanation: a = \"text\" and b = \"book\". a has 1 vowel whereas b has 2. Therefore, they are not alike.\n Notice that the vowel o is counted twice.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1705, - "title": "Maximum Number of Eaten Apples", - "question": "class Solution:\n def eatenApples(self, apples: List[int], days: List[int]) -> int:\n \"\"\"\n 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.\n You 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.\n Given two integer arrays days and apples of length n, return the maximum number of apples you can eat.\n Example 1:\n Input: apples = [1,2,3,5,2], days = [3,2,1,4,2]\n Output: 7\n Explanation: You can eat 7 apples:\n - On the first day, you eat an apple that grew on the first day.\n - On the second day, you eat an apple that grew on the second day.\n - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.\n - On the fourth to the seventh days, you eat apples that grew on the fourth day.\n Example 2:\n Input: apples = [3,0,0,0,0,2], days = [3,0,0,0,0,2]\n Output: 5\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1723, - "title": "Find Minimum Time to Finish All Jobs", - "question": "class Solution:\n def minimumTimeRequired(self, jobs: List[int], k: int) -> int:\n \"\"\"\n You are given an integer array jobs, where jobs[i] is the amount of time it takes to complete the ith job.\n There are k workers that you can assign jobs to. Each job should be assigned to exactly one worker. The working time of a worker is the sum of the time it takes to complete all jobs assigned to them. Your goal is to devise an optimal assignment such that the maximum working time of any worker is minimized.\n Return the minimum possible maximum working time of any assignment. \n Example 1:\n Input: jobs = [3,2,3], k = 3\n Output: 3\n Explanation: By assigning each person one job, the maximum time is 3.\n Example 2:\n Input: jobs = [1,2,4,7,8], k = 2\n Output: 11\n Explanation: Assign the jobs the following way:\n Worker 1: 1, 2, 8 (working time = 1 + 2 + 8 = 11)\n Worker 2: 4, 7 (working time = 4 + 7 = 11)\n The maximum working time is 11.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1707, - "title": "Maximum XOR With an Element From Array", - "question": "class Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].\n The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.\n Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.\n Example 1:\n Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]\n Output: [3,3,7]\n Explanation:\n 1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.\n 2) 1 XOR 2 = 3.\n 3) 5 XOR 2 = 7.\n Example 2:\n Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]\n Output: [15,-1,5]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1710, - "title": "Maximum Units on a Truck", - "question": "class Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n \"\"\"\n You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]:\n numberOfBoxesi is the number of boxes of type i.\n numberOfUnitsPerBoxi is the number of units in each box of the type i.\n You 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.\n Return the maximum total number of units that can be put on the truck.\n Example 1:\n Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4\n Output: 8\n Explanation: 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.\n You can take all the boxes of the first and second types, and one box of the third type.\n The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.\n Example 2:\n Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10\n Output: 91\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1711, - "title": "Count Good Meals", - "question": "class Solution:\n def countPairs(self, deliciousness: List[int]) -> int:\n \"\"\"\n A good meal is a meal that contains exactly two different food items with a sum of deliciousness equal to a power of two.\n You can pick any two different foods to make a good meal.\n Given an array of integers deliciousness where deliciousness[i] is the deliciousness of the i\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b item of food, return the number of different good meals you can make from this list modulo 109 + 7.\n Note that items with different indices are considered different even if they have the same deliciousness value.\n Example 1:\n Input: deliciousness = [1,3,5,7,9]\n Output: 4\n Explanation: The good meals are (1,3), (1,7), (3,5) and, (7,9).\n Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.\n Example 2:\n Input: deliciousness = [1,1,1,3,3,3,7]\n Output: 15\n Explanation: The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1712, - "title": "Ways to Split Array Into Three Subarrays", - "question": "class Solution:\n def waysToSplit(self, nums: List[int]) -> int:\n \"\"\"\n A split of an integer array is good if:\n The array is split into three non-empty contiguous subarrays - named left, mid, right respectively from left to right.\n The 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.\n Given 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:\n Input: nums = [1,1,1]\n Output: 1\n Explanation: The only good way to split nums is [1] [1] [1].\n Example 2:\n Input: nums = [1,2,2,2,5,0]\n Output: 3\n Explanation: There are three good ways of splitting nums:\n [1] [2] [2,2,5,0]\n [1] [2,2] [2,5,0]\n [1,2] [2,2] [5,0]\n Example 3:\n Input: nums = [3,2,1]\n Output: 0\n Explanation: There is no good way to split nums.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1713, - "title": "Minimum Operations to Make a Subsequence", - "question": "class Solution:\n def minOperations(self, target: List[int], arr: List[int]) -> int:\n \"\"\"\n You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.\n In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.\n Return the minimum number of operations needed to make target a subsequence of arr.\n A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\n Example 1:\n Input: target = [5,1,3], arr = [9,4,2,3,4]\n Output: 2\n Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], then target will be a subsequence of arr.\n Example 2:\n Input: target = [6,4,8,1,3,2], arr = [4,7,6,2,3,8,6,1]\n Output: 3\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1732, - "title": "Find the Highest Altitude", - "question": "class Solution:\n def largestAltitude(self, gain: List[int]) -> int:\n \"\"\"\n 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.\n You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i\u200b\u200b\u200b\u200b\u200b\u200b and i + 1 for all (0 <= i < n). Return the highest altitude of a point.\n Example 1:\n Input: gain = [-5,1,5,0,-7]\n Output: 1\n Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.\n Example 2:\n Input: gain = [-4,-3,-2,-1,4,3,2]\n Output: 0\n Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1733, - "title": "Minimum Number of People to Teach", - "question": "class Solution:\n def minimumTeachings(self, n: int, languages: List[List[int]], friendships: List[List[int]]) -> int:\n \"\"\"\n 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.\n You are given an integer n, an array languages, and an array friendships where:\n There are n languages numbered 1 through n,\n languages[i] is the set of languages the i\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b user knows, and\n friendships[i] = [u\u200b\u200b\u200b\u200b\u200b\u200bi\u200b\u200b\u200b, v\u200b\u200b\u200b\u200b\u200b\u200bi] denotes a friendship between the users u\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200bi\u200b\u200b\u200b\u200b\u200b and vi.\n You can choose one language and teach it to some users so that all friends can communicate with each other. Return the minimum number of users you need to teach.\n Note 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:\n Input: n = 2, languages = [[1],[2],[1,2]], friendships = [[1,2],[1,3],[2,3]]\n Output: 1\n Explanation: You can either teach user 1 the second language or user 2 the first language.\n Example 2:\n Input: n = 3, languages = [[2],[1,3],[1,2],[3]], friendships = [[1,4],[1,2],[3,4],[2,3]]\n Output: 2\n Explanation: Teach the third language to users 1 and 3, yielding two users to teach.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1734, - "title": "Decode XORed Permutation", - "question": "class Solution:\n def decode(self, encoded: List[int]) -> List[int]:\n \"\"\"\n There is an integer array perm that is a permutation of the first n positive integers, where n is always odd.\n It 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].\n Given the encoded array, return the original array perm. It is guaranteed that the answer exists and is unique.\n Example 1:\n Input: encoded = [3,1]\n Output: [1,2,3]\n Explanation: If perm = [1,2,3], then encoded = [1 XOR 2,2 XOR 3] = [3,1]\n Example 2:\n Input: encoded = [6,5,4,6]\n Output: [2,4,1,5,3]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1735, - "title": "Count Ways to Make Array With Product", - "question": "class Solution:\n def waysToFillArray(self, queries: List[List[int]]) -> List[int]:\n \"\"\"\n You are given a 2D integer array, queries. For each queries[i], where queries[i] = [ni, ki], find the number of different ways you can place positive integers into an array of size ni such that the product of the integers is ki. As the number of ways may be too large, the answer to the ith query is the number of ways modulo 109 + 7.\n Return an integer array answer where answer.length == queries.length, and answer[i] is the answer to the ith query.\n Example 1:\n Input: queries = [[2,6],[5,1],[73,660]]\n Output: [4,1,50734910]\n Explanation: Each query is independent.\n [2,6]: There are 4 ways to fill an array of size 2 that multiply to 6: [1,6], [2,3], [3,2], [6,1].\n [5,1]: There is 1 way to fill an array of size 5 that multiply to 1: [1,1,1,1,1].\n [73,660]: There are 1050734917 ways to fill an array of size 73 that multiply to 660. 1050734917 modulo 109 + 7 = 50734910.\n Example 2:\n Input: queries = [[1,1],[2,2],[3,3],[4,4],[5,5]]\n Output: [1,2,3,10,5]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1720, - "title": "Decode XORed Array", - "question": "class Solution:\n def decode(self, encoded: List[int], first: int) -> List[int]:\n \"\"\"\n There is a hidden integer array arr that consists of n non-negative integers.\n It 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].\n You are given the encoded array. You are also given an integer first, that is the first element of arr, i.e. arr[0].\n Return the original array arr. It can be proved that the answer exists and is unique.\n Example 1:\n Input: encoded = [1,2,3], first = 1\n Output: [1,0,2,1]\n Explanation: If arr = [1,0,2,1], then first = 1 and encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]\n Example 2:\n Input: encoded = [6,2,7,3], first = 4\n Output: [4,2,0,7,4]\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1722, - "title": "Minimize Hamming Distance After Swap Operations", - "question": "class Solution:\n def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int:\n \"\"\"\n 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.\n The 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).\n Return the minimum Hamming distance of source and target after performing any amount of swap operations on array source.\n Example 1:\n Input: source = [1,2,3,4], target = [2,1,4,5], allowedSwaps = [[0,1],[2,3]]\n Output: 1\n Explanation: 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]\n The Hamming distance of source and target is 1 as they differ in 1 position: index 3.\n Example 2:\n Input: source = [1,2,3,4], target = [1,3,2,4], allowedSwaps = []\n Output: 2\n Explanation: There are no allowed swaps.\n The Hamming distance of source and target is 2 as they differ in 2 positions: index 1 and index 2.\n Example 3:\n Input: source = [5,1,2,4,3], target = [1,5,4,2,3], allowedSwaps = [[0,4],[4,2],[1,3],[1,4]]\n Output: 0\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1725, - "title": "Number Of Rectangles That Can Form The Largest Square", - "question": "class Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n \"\"\"\n You are given an array rectangles where rectangles[i] = [li, wi] represents the ith rectangle of length li and width wi.\r\n You 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.\r\n Let maxLen be the side length of the largest square you can obtain from any of the given rectangles.\r\n Return the number of rectangles that can make a square with a side length of maxLen.\r\n Example 1:\r\n Input: rectangles = [[5,8],[3,9],[5,12],[16,5]]\r\n Output: 3\r\n Explanation: The largest squares you can get from each rectangle are of lengths [5,3,5,5].\r\n The largest possible square is of length 5, and you can get it out of 3 rectangles.\r\n Example 2:\r\n Input: rectangles = [[2,3],[3,7],[4,3],[3,7]]\r\n Output: 3\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1742, - "title": "Maximum Number of Balls in a Box", - "question": "class Solution:\n def countBalls(self, lowLimit: int, highLimit: int) -> int:\n \"\"\"\n 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.\n Your 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.\n Given two integers lowLimit and highLimit, return the number of balls in the box with the most balls.\n Example 1:\n Input: lowLimit = 1, highLimit = 10\n Output: 2\n Explanation:\n Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\n Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ...\n Box 1 has the most number of balls with 2 balls.\n Example 2:\n Input: lowLimit = 5, highLimit = 15\n Output: 2\n Explanation:\n Box Number: 1 2 3 4 5 6 7 8 9 10 11 ...\n Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ...\n Boxes 5 and 6 have the most number of balls with 2 balls in each.\n Example 3:\n Input: lowLimit = 19, highLimit = 28\n Output: 2\n Explanation:\n Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ...\n Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ...\n Box 10 has the most number of balls with 2 balls.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1727, - "title": "Largest Submatrix With Rearrangements", - "question": "class Solution:\n def largestSubmatrix(self, matrix: List[List[int]]) -> int:\n \"\"\"\n 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.\n Return the area of the largest submatrix within matrix where every element of the submatrix is 1 after reordering the columns optimally.\n Example 1:\n Input: matrix = [[0,0,1],[1,1,1],[1,0,1]]\n Output: 4\n Explanation: You can rearrange the columns as shown above.\n The largest submatrix of 1s, in bold, has an area of 4.\n Example 2:\n Input: matrix = [[1,0,1,0,1]]\n Output: 3\n Explanation: You can rearrange the columns as shown above.\n The largest submatrix of 1s, in bold, has an area of 3.\n Example 3:\n Input: matrix = [[1,1,0],[1,0,1]]\n Output: 2\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1748, - "title": "Sum of Unique Elements", - "question": "class Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.\n Return the sum of all the unique elements of nums.\n Example 1:\n Input: nums = [1,2,3,2]\n Output: 4\n Explanation: The unique elements are [1,3], and the sum is 4.\n Example 2:\n Input: nums = [1,1,1,1,1]\n Output: 0\n Explanation: There are no unique elements, and the sum is 0.\n Example 3:\n Input: nums = [1,2,3,4,5]\n Output: 15\n Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1749, - "title": "Maximum Absolute Sum of Any Subarray", - "question": "class Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n \"\"\"\n 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).\n Return the maximum absolute sum of any (possibly empty) subarray of nums.\n Note that abs(x) is defined as follows:\n If x is a negative integer, then abs(x) = -x.\n If x is a non-negative integer, then abs(x) = x.\n Example 1:\n Input: nums = [1,-3,2,3,-4]\n Output: 5\n Explanation: The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.\n Example 2:\n Input: nums = [2,-5,1,-4,3,-2]\n Output: 8\n Explanation: The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1750, - "title": "Minimum Length of String After Deleting Similar Ends", - "question": "class Solution:\n def minimumLength(self, s: str) -> int:\n \"\"\"\n 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:\n Pick a non-empty prefix from the string s where all the characters in the prefix are equal.\n Pick a non-empty suffix from the string s where all the characters in this suffix are equal.\n The prefix and the suffix should not intersect at any index.\n The characters from the prefix and suffix must be the same.\n Delete both the prefix and the suffix.\n Return the minimum length of s after performing the above operation any number of times (possibly zero times).\n Example 1:\n Input: s = \"ca\"\n Output: 2\n Explanation: You can't remove any characters, so the string stays as is.\n Example 2:\n Input: s = \"cabaabac\"\n Output: 0\n Explanation: An optimal sequence of operations is:\n - Take prefix = \"c\" and suffix = \"c\" and remove them, s = \"abaaba\".\n - Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"baab\".\n - Take prefix = \"b\" and suffix = \"b\" and remove them, s = \"aa\".\n - Take prefix = \"a\" and suffix = \"a\" and remove them, s = \"\".\n Example 3:\n Input: s = \"aabccabba\"\n Output: 3\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1751, - "title": "Maximum Number of Events That Can Be Attended II", - "question": "class Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n \"\"\"\n You are given an array of events where events[i] = [startDayi, endDayi, valuei]. The ith event starts at startDayi and ends at endDayi, and if you attend this event, you will receive a value of valuei. You are also given an integer k which represents the maximum number of events you can attend.\n You can only attend one event at a time. If you choose to attend an event, you must attend the entire event. Note that the end day is inclusive: that is, you cannot attend two events where one of them starts and the other ends on the same day.\n Return the maximum sum of values that you can receive by attending events.\n Example 1:\n Input: events = [[1,2,4],[3,4,3],[2,3,1]], k = 2\n Output: 7\n Explanation: Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.\n Example 2:\n Input: events = [[1,2,4],[3,4,3],[2,3,10]], k = 2\n Output: 10\n Explanation: Choose event 2 for a total value of 10.\n Notice that you cannot attend any other event as they overlap, and that you do not have to attend k events.\n Example 3:\n Input: events = [[1,1,1],[2,2,2],[3,3,3],[4,4,4]], k = 3\n Output: 9\n Explanation: Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1736, - "title": "Latest Time by Replacing Hidden Digits", - "question": "class Solution:\n def maximumTime(self, time: str) -> str:\n \"\"\"\n You are given a string time in the form of hh:mm, where some of the digits in the string are hidden (represented by ?).\n The valid times are those inclusively between 00:00 and 23:59.\n Return the latest valid time you can get from time by replacing the hidden digits.\n Example 1:\n Input: time = \"2?:?0\"\n Output: \"23:50\"\n Explanation: The latest hour beginning with the digit '2' is 23 and the latest minute ending with the digit '0' is 50.\n Example 2:\n Input: time = \"0?:3?\"\n Output: \"09:39\"\n Example 3:\n Input: time = \"1?:22\"\n Output: \"19:22\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1737, - "title": "Change Minimum Characters to Satisfy One of Three Conditions", - "question": "class Solution:\n def minCharacters(self, a: str, b: str) -> int:\n \"\"\"\n 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.\n Your goal is to satisfy one of the following three conditions:\n Every letter in a is strictly less than every letter in b in the alphabet.\n Every letter in b is strictly less than every letter in a in the alphabet.\n Both a and b consist of only one distinct letter.\n Return the minimum number of operations needed to achieve your goal.\n Example 1:\n Input: a = \"aba\", b = \"caa\"\n Output: 2\n Explanation: Consider the best way to make each condition true:\n 1) Change b to \"ccc\" in 2 operations, then every letter in a is less than every letter in b.\n 2) Change a to \"bbb\" and b to \"aaa\" in 3 operations, then every letter in b is less than every letter in a.\n 3) Change a to \"aaa\" and b to \"aaa\" in 2 operations, then a and b consist of one distinct letter.\n The best way was done in 2 operations (either condition 1 or condition 3).\n Example 2:\n Input: a = \"dabadd\", b = \"cda\"\n Output: 3\n Explanation: The best way is to make condition 1 true by changing b to \"eee\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1738, - "title": "Find Kth Largest XOR Coordinate Value", - "question": "class Solution:\n def kthLargestValue(self, matrix: List[List[int]], k: int) -> int:\n \"\"\"\n You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k.\n The 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).\n Find the kth largest value (1-indexed) of all the coordinates of matrix.\n Example 1:\n Input: matrix = [[5,2],[1,6]], k = 1\n Output: 7\n Explanation: The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value.\n Example 2:\n Input: matrix = [[5,2],[1,6]], k = 2\n Output: 5\n Explanation: The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value.\n Example 3:\n Input: matrix = [[5,2],[1,6]], k = 3\n Output: 4\n Explanation: The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1739, - "title": "Building Boxes", - "question": "class Solution:\n def minimumBoxes(self, n: int) -> int:\n \"\"\"\n You have a cubic storeroom where the width, length, and height of the room are all equal to n units. You are asked to place n boxes in this room where each box is a cube of unit side length. There are however some rules to placing the boxes:\n You can place the boxes anywhere on the floor.\n If box x is placed on top of the box y, then each side of the four vertical sides of the box y must either be adjacent to another box or to a wall.\n Given an integer n, return the minimum possible number of boxes touching the floor.\n Example 1:\n Input: n = 3\n Output: 3\n Explanation: The figure above is for the placement of the three boxes.\n These boxes are placed in the corner of the room, where the corner is on the left side.\n Example 2:\n Input: n = 4\n Output: 3\n Explanation: The figure above is for the placement of the four boxes.\n These boxes are placed in the corner of the room, where the corner is on the left side.\n Example 3:\n Input: n = 10\n Output: 6\n Explanation: The figure above is for the placement of the ten boxes.\n These boxes are placed in the corner of the room, where the corner is on the back side.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1743, - "title": "Restore the Array From Adjacent Pairs", - "question": "class Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n You 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.\n It 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.\n Return the original array nums. If there are multiple solutions, return any of them.\n Example 1:\n Input: adjacentPairs = [[2,1],[3,4],[3,2]]\n Output: [1,2,3,4]\n Explanation: This array has all its adjacent pairs in adjacentPairs.\n Notice that adjacentPairs[i] may not be in left-to-right order.\n Example 2:\n Input: adjacentPairs = [[4,-2],[1,4],[-3,1]]\n Output: [-2,4,1,-3]\n Explanation: There can be negative numbers.\n Another solution is [-3,1,4,-2], which would also be accepted.\n Example 3:\n Input: adjacentPairs = [[100000,-100000]]\n Output: [100000,-100000]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1745, - "title": "Palindrome Partitioning IV", - "question": "class Solution:\n def checkPartitioning(self, s: str) -> bool:\n \"\"\"\n Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.\u200b\u200b\u200b\u200b\u200b\n A string is said to be palindrome if it the same string when reversed.\n Example 1:\n Input: s = \"abcbdd\"\n Output: true\n Explanation: \"abcbdd\" = \"a\" + \"bcb\" + \"dd\", and all three substrings are palindromes.\n Example 2:\n Input: s = \"bcbddxy\"\n Output: false\n Explanation: s cannot be split into 3 palindromes.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1744, - "title": "Can You Eat Your Favorite Candy on Your Favorite Day?", - "question": "class Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n \"\"\"\n 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].\n You play a game with the following rules:\n You start eating candies on day 0.\n You cannot eat any candy of type i unless you have eaten all candies of type i - 1.\n You must eat at least one candy per day until you have eaten all the candies.\n Construct 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.\n Return the constructed array answer.\n Example 1:\n Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]]\n Output: [true,false,true]\n Explanation:\n 1- 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.\n 2- 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.\n 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13.\n Example 2:\n Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]]\n Output: [false,true,true,false,false]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1763, - "title": "Longest Nice Substring", - "question": "class Solution:\n def longestNiceSubstring(self, s: str) -> str:\n \"\"\"\n 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.\n Given 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:\n Input: s = \"YazaAay\"\n Output: \"aAa\"\n Explanation: \"aAa\" is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.\n \"aAa\" is the longest nice substring.\n Example 2:\n Input: s = \"Bb\"\n Output: \"Bb\"\n Explanation: \"Bb\" is a nice string because both 'B' and 'b' appear. The whole string is a substring.\n Example 3:\n Input: s = \"c\"\n Output: \"\"\n Explanation: There are no nice substrings.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1764, - "title": "Form Array by Concatenating Subarrays of Another Array", - "question": "class Solution:\n def canChoose(self, groups: List[List[int]], nums: List[int]) -> bool:\n \"\"\"\n You are given a 2D integer array groups of length n. You are also given an integer array nums.\n You 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).\n Return true if you can do this task, and false otherwise.\n Note 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:\n Input: groups = [[1,-1,-1],[3,-2,0]], nums = [1,-1,0,1,-1,-1,3,-2,0]\n Output: true\n Explanation: 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].\n These subarrays are disjoint as they share no common nums[k] element.\n Example 2:\n Input: groups = [[10,-2],[1,2,3,4]], nums = [1,2,3,4,10,-2]\n Output: false\n Explanation: Note that choosing the subarrays [1,2,3,4,10,-2] and [1,2,3,4,10,-2] is incorrect because they are not in the same order as in groups.\n [10,-2] must come before [1,2,3,4].\n Example 3:\n Input: groups = [[1,2,3],[3,4]], nums = [7,7,1,2,3,4,7,7]\n Output: false\n Explanation: 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.\n They share a common elements nums[4] (0-indexed).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1766, - "title": "Tree of Coprimes", - "question": "class Solution:\n def getCoprimes(self, nums: List[int], edges: List[List[int]]) -> List[int]:\n \"\"\"\n There is a tree (i.e., a connected, undirected graph that has no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. Each node has a value associated with it, and the root of the tree is node 0.\n To represent this tree, you are given an integer array nums and a 2D array edges. Each nums[i] represents the ith node's value, and each edges[j] = [uj, vj] represents an edge between nodes uj and vj in the tree.\n Two values x and y are coprime if gcd(x, y) == 1 where gcd(x, y) is the greatest common divisor of x and y.\n An ancestor of a node i is any other node on the shortest path from node i to the root. A node is not considered an ancestor of itself.\n Return an array ans of size n, where ans[i] is the closest ancestor to node i such that nums[i] and nums[ans[i]] are coprime, or -1 if there is no such ancestor.\n Example 1:\n Input: nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]\n Output: [-1,0,0,1]\n Explanation: In the above figure, each node's value is in parentheses.\n - Node 0 has no coprime ancestors.\n - Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).\n - Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's\n value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.\n - Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its\n closest valid ancestor.\n Example 2:\n Input: nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]\n Output: [-1,0,-1,0,0,0,-1]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1765, - "title": "Map of Highest Peak", - "question": "class Solution:\n def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]:\n \"\"\"\n You are given an integer matrix isWater of size m x n that represents a map of land and water cells.\n If isWater[i][j] == 0, cell (i, j) is a land cell.\n If isWater[i][j] == 1, cell (i, j) is a water cell.\n You must assign each cell a height in a way that follows these rules:\n The height of each cell must be non-negative.\n If the cell is a water cell, its height must be 0.\n Any two adjacent cells must have an absolute height difference of at most 1. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n Find an assignment of heights such that the maximum height in the matrix is maximized.\n Return 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:\n Input: isWater = [[0,1],[0,0]]\n Output: [[1,0],[2,1]]\n Explanation: The image shows the assigned heights of each cell.\n The blue cell is the water cell, and the green cells are the land cells.\n Example 2:\n Input: isWater = [[0,0,1],[1,0,0],[0,0,0]]\n Output: [[1,1,0],[0,1,1],[1,2,2]]\n Explanation: A height of 2 is the maximum possible height of any assignment.\n Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1752, - "title": "Check if Array Is Sorted and Rotated", - "question": "class Solution:\n def check(self, nums: List[int]) -> bool:\n \"\"\"\n 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.\n There may be duplicates in the original array.\n Note: 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:\n Input: nums = [3,4,5,1,2]\n Output: true\n Explanation: [1,2,3,4,5] is the original sorted array.\n You can rotate the array by x = 3 positions to begin on the the element of value 3: [3,4,5,1,2].\n Example 2:\n Input: nums = [2,1,3,4]\n Output: false\n Explanation: There is no sorted array once rotated that can make nums.\n Example 3:\n Input: nums = [1,2,3]\n Output: true\n Explanation: [1,2,3] is the original sorted array.\n You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1753, - "title": "Maximum Score From Removing Stones", - "question": "class Solution:\n def maximumScore(self, a: int, b: int, c: int) -> int:\n \"\"\"\n You are playing a solitaire game with three piles of stones of sizes a\u200b\u200b\u200b\u200b\u200b\u200b, b,\u200b\u200b\u200b\u200b\u200b\u200b and c\u200b\u200b\u200b\u200b\u200b\u200b 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).\n Given three integers a\u200b\u200b\u200b\u200b\u200b, b,\u200b\u200b\u200b\u200b\u200b and c\u200b\u200b\u200b\u200b\u200b, return the maximum score you can get.\n Example 1:\n Input: a = 2, b = 4, c = 6\n Output: 6\n Explanation: 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)\n There are fewer than two non-empty piles, so the game ends. Total: 6 points.\n Example 2:\n Input: a = 4, b = 4, c = 6\n Output: 7\n Explanation: 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)\n There are fewer than two non-empty piles, so the game ends. Total: 7 points.\n Example 3:\n Input: a = 1, b = 8, c = 8\n Output: 8\n Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.\n After that, there are fewer than two non-empty piles, so the game ends.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1754, - "title": "Largest Merge Of Two Strings", - "question": "class Solution:\n def largestMerge(self, word1: str, word2: str) -> str:\n \"\"\"\n 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:\n If word1 is non-empty, append the first character in word1 to merge and delete it from word1.\n For example, if word1 = \"abc\" and merge = \"dv\", then after choosing this operation, word1 = \"bc\" and merge = \"dva\".\n If word2 is non-empty, append the first character in word2 to merge and delete it from word2.\n For example, if word2 = \"abc\" and merge = \"\", then after choosing this operation, word2 = \"bc\" and merge = \"a\".\n Return the lexicographically largest merge you can construct.\n A 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:\n Input: word1 = \"cabaa\", word2 = \"bcaaa\"\n Output: \"cbcabaaaaa\"\n Explanation: One way to get the lexicographically largest merge is:\n - Take from word1: merge = \"c\", word1 = \"abaa\", word2 = \"bcaaa\"\n - Take from word2: merge = \"cb\", word1 = \"abaa\", word2 = \"caaa\"\n - Take from word2: merge = \"cbc\", word1 = \"abaa\", word2 = \"aaa\"\n - Take from word1: merge = \"cbca\", word1 = \"baa\", word2 = \"aaa\"\n - Take from word1: merge = \"cbcab\", word1 = \"aa\", word2 = \"aaa\"\n - Append the remaining 5 a's from word1 and word2 at the end of merge.\n Example 2:\n Input: word1 = \"abcabc\", word2 = \"abdcaba\"\n Output: \"abdcabcabcaba\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1755, - "title": "Closest Subsequence Sum", - "question": "class Solution:\n def minAbsDifference(self, nums: List[int], goal: int) -> int:\n \"\"\"\n You are given an integer array nums and an integer goal.\n You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).\n Return the minimum possible value of abs(sum - goal).\n Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.\n Example 1:\n Input: nums = [5,-7,3,5], goal = 6\n Output: 0\n Explanation: Choose the whole array as a subsequence, with a sum of 6.\n This is equal to the goal, so the absolute difference is 0.\n Example 2:\n Input: nums = [7,-9,15,-2], goal = -5\n Output: 1\n Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.\n The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.\n Example 3:\n Input: nums = [1,2,3], goal = -7\n Output: 7\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1758, - "title": "Minimum Changes To Make Alternating Binary String", - "question": "class Solution:\n def minOperations(self, s: str) -> int:\n \"\"\"\n 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.\n The string is called alternating if no two adjacent characters are equal. For example, the string \"010\" is alternating, while the string \"0100\" is not.\n Return the minimum number of operations needed to make s alternating.\n Example 1:\n Input: s = \"0100\"\n Output: 1\n Explanation: If you change the last character to '1', s will be \"0101\", which is alternating.\n Example 2:\n Input: s = \"10\"\n Output: 0\n Explanation: s is already alternating.\n Example 3:\n Input: s = \"1111\"\n Output: 2\n Explanation: You need two operations to reach \"0101\" or \"1010\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1759, - "title": "Count Number of Homogenous Substrings", - "question": "class Solution:\n def countHomogenous(self, s: str) -> int:\n \"\"\"\n Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.\r\n A string is homogenous if all the characters of the string are the same.\r\n A substring is a contiguous sequence of characters within a string.\r\n Example 1:\r\n Input: s = \"abbcccaa\"\r\n Output: 13\r\n Explanation: The homogenous substrings are listed as below:\r\n \"a\" appears 3 times.\r\n \"aa\" appears 1 time.\r\n \"b\" appears 2 times.\r\n \"bb\" appears 1 time.\r\n \"c\" appears 3 times.\r\n \"cc\" appears 2 times.\r\n \"ccc\" appears 1 time.\r\n 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.\r\n Example 2:\r\n Input: s = \"xy\"\r\n Output: 2\r\n Explanation: The homogenous substrings are \"x\" and \"y\".\r\n Example 3:\r\n Input: s = \"zzzzz\"\r\n Output: 15\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1760, - "title": "Minimum Limit of Balls in a Bag", - "question": "class Solution:\n def minimumSize(self, nums: List[int], maxOperations: int) -> int:\n \"\"\"\n You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.\n You can perform the following operation at most maxOperations times:\n Take any bag of balls and divide it into two new bags with a positive number of balls.\n For 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.\n Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.\n Return the minimum possible penalty after performing the operations.\n Example 1:\n Input: nums = [9], maxOperations = 2\n Output: 3\n Explanation: \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].\n The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.\n Example 2:\n Input: nums = [2,4,8,2], maxOperations = 4\n Output: 2\n Explanation:\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].\n The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1761, - "title": "Minimum Degree of a Connected Trio in a Graph", - "question": "class Solution:\n def minTrioDegree(self, n: int, edges: List[List[int]]) -> int:\n \"\"\"\n You are given an undirected graph. You are given an integer n which is the number of nodes in the graph and an array edges, where each edges[i] = [ui, vi] indicates that there is an undirected edge between ui and vi.\n A connected trio is a set of three nodes where there is an edge between every pair of them.\n The degree of a connected trio is the number of edges where one endpoint is in the trio, and the other is not.\n Return the minimum degree of a connected trio in the graph, or -1 if the graph has no connected trios.\n Example 1:\n Input: n = 6, edges = [[1,2],[1,3],[3,2],[4,1],[5,2],[3,6]]\n Output: 3\n Explanation: There is exactly one trio, which is [1,2,3]. The edges that form its degree are bolded in the figure above.\n Example 2:\n Input: n = 7, edges = [[1,3],[4,1],[4,3],[2,5],[5,6],[6,7],[7,5],[2,6]]\n Output: 0\n Explanation: There are exactly three trios:\n 1) [1,4,3] with degree 0.\n 2) [2,5,6] with degree 2.\n 3) [5,6,7] with degree 2.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1779, - "title": "Find Nearest Point That Has the Same X or Y Coordinate", - "question": "class Solution:\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n \"\"\"\n You are given two integers, x and y, which represent your current location on a Cartesian grid: (x, y). You are also given an array points where each points[i] = [ai, bi] represents that a point exists at (ai, bi). A point is valid if it shares the same x-coordinate or the same y-coordinate as your location.\n Return the index (0-indexed) of the valid point with the smallest Manhattan distance from your current location. If there are multiple, return the valid point with the smallest index. If there are no valid points, return -1.\n The Manhattan distance between two points (x1, y1) and (x2, y2) is abs(x1 - x2) + abs(y1 - y2).\n Example 1:\n Input: x = 3, y = 4, points = [[1,2],[3,1],[2,4],[2,3],[4,4]]\n Output: 2\n Explanation: Of all the points, only [3,1], [2,4] and [4,4] are valid. Of the valid points, [2,4] and [4,4] have the smallest Manhattan distance from your current location, with a distance of 1. [2,4] has the smallest index, so return 2.\n Example 2:\n Input: x = 3, y = 4, points = [[3,4]]\n Output: 0\n Explanation: The answer is allowed to be on the same location as your current location.\n Example 3:\n Input: x = 3, y = 4, points = [[2,3]]\n Output: -1\n Explanation: There are no valid points.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1780, - "title": "Check if Number is a Sum of Powers of Three", - "question": "class Solution:\n def checkPowersOfThree(self, n: int) -> bool:\n \"\"\"\n Given an integer n, return true if it is possible to represent n as the sum of distinct powers of three. Otherwise, return false.\n An integer y is a power of three if there exists an integer x such that y == 3x.\n Example 1:\n Input: n = 12\n Output: true\n Explanation: 12 = 31 + 32\n Example 2:\n Input: n = 91\n Output: true\n Explanation: 91 = 30 + 32 + 34\n Example 3:\n Input: n = 21\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1781, - "title": "Sum of Beauty of All Substrings", - "question": "class Solution:\n def beautySum(self, s: str) -> int:\n \"\"\"\n The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.\n For example, the beauty of \"abaacc\" is 3 - 1 = 2.\n Given a string s, return the sum of beauty of all of its substrings.\n Example 1:\n Input: s = \"aabcb\"\n Output: 5\n Explanation: The substrings with non-zero beauty are [\"aab\",\"aabc\",\"aabcb\",\"abcb\",\"bcb\"], each with beauty equal to 1.\n Example 2:\n Input: s = \"aabcbaa\"\n Output: 17\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1782, - "title": "Count Pairs Of Nodes", - "question": "class Solution:\n def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]:\n \"\"\"\n 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.\n Let incident(a, b) be defined as the number of edges that are connected to either node a or b.\n The answer to the jth query is the number of pairs of nodes (a, b) that satisfy both of the following conditions:\n a < b\n incident(a, b) > queries[j]\n Return an array answers such that answers.length == queries.length and answers[j] is the answer of the jth query.\n Note that there can be multiple edges between the same two nodes.\n Example 1:\n Input: n = 4, edges = [[1,2],[2,4],[1,3],[2,3],[2,1]], queries = [2,3]\n Output: [6,5]\n Explanation: The calculations for incident(a, b) are shown in the table above.\n The answers for each of the queries are as follows:\n - answers[0] = 6. All the pairs have an incident(a, b) value greater than 2.\n - answers[1] = 5. All the pairs except (3, 4) have an incident(a, b) value greater than 3.\n Example 2:\n Input: n = 5, edges = [[1,5],[1,5],[3,4],[2,5],[1,3],[5,1],[2,3],[2,5]], queries = [1,2,3,4,5]\n Output: [10,10,9,8,6]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1768, - "title": "Merge Strings Alternately", - "question": "class Solution:\n def mergeAlternately(self, word1: str, word2: str) -> str:\n \"\"\"\n 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.\r\n Return the merged string.\r\n Example 1:\r\n Input: word1 = \"abc\", word2 = \"pqr\"\r\n Output: \"apbqcr\"\r\n Explanation: The merged string will be merged as so:\r\n word1: a b c\r\n word2: p q r\r\n merged: a p b q c r\r\n Example 2:\r\n Input: word1 = \"ab\", word2 = \"pqrs\"\r\n Output: \"apbqrs\"\r\n Explanation: Notice that as word2 is longer, \"rs\" is appended to the end.\r\n word1: a b \r\n word2: p q r s\r\n merged: a p b q r s\r\n Example 3:\r\n Input: word1 = \"abcd\", word2 = \"pq\"\r\n Output: \"apbqcd\"\r\n Explanation: Notice that as word1 is longer, \"cd\" is appended to the end.\r\n word1: a b c d\r\n word2: p q \r\n merged: a p b q c d\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1769, - "title": "Minimum Number of Operations to Move All Balls to Each Box", - "question": "class Solution:\n def minOperations(self, boxes: str) -> List[int]:\n \"\"\"\n 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.\n In 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.\n Return 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.\n Each answer[i] is calculated considering the initial state of the boxes.\n Example 1:\n Input: boxes = \"110\"\n Output: [1,1,3]\n Explanation: The answer for each box is as follows:\n 1) First box: you will have to move one ball from the second box to the first box in one operation.\n 2) Second box: you will have to move one ball from the first box to the second box in one operation.\n 3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.\n Example 2:\n Input: boxes = \"001011\"\n Output: [11,8,5,4,3,4]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1770, - "title": "Maximum Score from Performing Multiplication Operations", - "question": "class Solution:\n def maximumScore(self, nums: List[int], multipliers: List[int]) -> int:\n \"\"\"\n You are given two 0-indexed integer arrays nums and multipliers of size n and m respectively, where n >= m.\n You begin with a score of 0. You want to perform exactly m operations. On the ith operation (0-indexed) you will:\n Choose one integer x from either the start or the end of the array nums.\n Add multipliers[i] * x to your score.\n Note that multipliers[0] corresponds to the first operation, multipliers[1] to the second operation, and so on.\n Remove x from nums.\n Return the maximum score after performing m operations.\n Example 1:\n Input: nums = [1,2,3], multipliers = [3,2,1]\n Output: 14\n Explanation: 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.\n The total score is 9 + 4 + 1 = 14.\n Example 2:\n Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]\n Output: 102\n Explanation: 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. \n The total score is 50 + 15 - 9 + 4 + 42 = 102.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1771, - "title": "Maximize Palindrome Length From Subsequences", - "question": "class Solution:\n def longestPalindrome(self, word1: str, word2: str) -> int:\n \"\"\"\n You are given two strings, word1 and word2. You want to construct a string in the following manner:\n Choose some non-empty subsequence subsequence1 from word1.\n Choose some non-empty subsequence subsequence2 from word2.\n Concatenate the subsequences: subsequence1 + subsequence2, to make the string.\n Return the length of the longest palindrome that can be constructed in the described manner. If no palindromes can be constructed, return 0.\n A subsequence of a string s is a string that can be made by deleting some (possibly none) characters from s without changing the order of the remaining characters.\n A palindrome is a string that reads the same forward as well as backward.\n Example 1:\n Input: word1 = \"cacb\", word2 = \"cbba\"\n Output: 5\n Explanation: Choose \"ab\" from word1 and \"cba\" from word2 to make \"abcba\", which is a palindrome.\n Example 2:\n Input: word1 = \"ab\", word2 = \"ab\"\n Output: 3\n Explanation: Choose \"ab\" from word1 and \"a\" from word2 to make \"aba\", which is a palindrome.\n Example 3:\n Input: word1 = \"aa\", word2 = \"bb\"\n Output: 0\n Explanation: You cannot construct a palindrome from the described method, so return 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1773, - "title": "Count Items Matching a Rule", - "question": "class Solution:\n def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int:\n \"\"\"\n 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.\n The ith item is said to match the rule if one of the following is true:\n ruleKey == \"type\" and ruleValue == typei.\n ruleKey == \"color\" and ruleValue == colori.\n ruleKey == \"name\" and ruleValue == namei.\n Return the number of items that match the given rule.\n Example 1:\n Input: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"lenovo\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"color\", ruleValue = \"silver\"\n Output: 1\n Explanation: There is only one item matching the given rule, which is [\"computer\",\"silver\",\"lenovo\"].\n Example 2:\n Input: items = [[\"phone\",\"blue\",\"pixel\"],[\"computer\",\"silver\",\"phone\"],[\"phone\",\"gold\",\"iphone\"]], ruleKey = \"type\", ruleValue = \"phone\"\n Output: 2\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1774, - "title": "Closest Dessert Cost", - "question": "class Solution:\n def closestCost(self, baseCosts: List[int], toppingCosts: List[int], target: int) -> int:\n \"\"\"\n 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:\n There must be exactly one ice cream base.\n You can add one or more types of topping or have no toppings at all.\n There are at most two of each type of topping.\n You are given three inputs:\n baseCosts, an integer array of length n, where each baseCosts[i] represents the price of the ith ice cream base flavor.\n toppingCosts, an integer array of length m, where each toppingCosts[i] is the price of one of the ith topping.\n target, an integer representing your target price for dessert.\n You want to make a dessert with a total cost as close to target as possible.\n Return the closest possible cost of the dessert to target. If there are multiple, return the lower one.\n Example 1:\n Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10\n Output: 10\n Explanation: 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\n Total: 7 + 3 + 0 = 10.\n Example 2:\n Input: baseCosts = [2,3], toppingCosts = [4,5,100], target = 18\n Output: 17\n Explanation: 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\n Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.\n Example 3:\n Input: baseCosts = [3,10], toppingCosts = [2,5], target = 9\n Output: 8\n Explanation: It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1775, - "title": "Equal Sum Arrays With Minimum Number of Operations", - "question": "class Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n 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.\n In one operation, you can change any integer's value in any of the arrays to any value between 1 and 6, inclusive.\n Return the minimum number of operations required to make the sum of values in nums1 equal to the sum of values in nums2. Return -1\u200b\u200b\u200b\u200b\u200b if it is not possible to make the sum of the two arrays equal.\n Example 1:\n Input: nums1 = [1,2,3,4,5,6], nums2 = [1,1,2,2,2,2]\n Output: 3\n Explanation: You can make the sums of nums1 and nums2 equal with 3 operations. All indices are 0-indexed.\n - Change nums2[0] to 6. nums1 = [1,2,3,4,5,6], nums2 = [6,1,2,2,2,2].\n - Change nums1[5] to 1. nums1 = [1,2,3,4,5,1], nums2 = [6,1,2,2,2,2].\n - Change nums1[2] to 2. nums1 = [1,2,2,4,5,1], nums2 = [6,1,2,2,2,2].\n Example 2:\n Input: nums1 = [1,1,1,1,1,1,1], nums2 = [6]\n Output: -1\n Explanation: There is no way to decrease the sum of nums1 or to increase the sum of nums2 to make them equal.\n Example 3:\n Input: nums1 = [6,6], nums2 = [1]\n Output: 3\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1776, - "title": "Car Fleet II", - "question": "class Solution:\n def getCollisionTimes(self, cars: List[List[int]]) -> List[float]:\n \"\"\"\n There are n cars traveling at different speeds in the same direction along a one-lane road. You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:\n positioni is the distance between the ith car and the beginning of the road in meters. It is guaranteed that positioni < positioni+1.\n speedi is the initial speed of the ith car in meters per second.\n For simplicity, cars can be considered as points moving along the number line. Two cars collide when they occupy the same position. Once a car collides with another car, they unite and form a single car fleet. The cars in the formed fleet will have the same position and the same speed, which is the initial speed of the slowest car in the fleet.\n Return an array answer, where answer[i] is the time, in seconds, at which the ith car collides with the next car, or -1 if the car does not collide with the next car. Answers within 10-5 of the actual answers are accepted.\n Example 1:\n Input: cars = [[1,2],[2,1],[4,3],[7,2]]\n Output: [1.00000,-1.00000,3.00000,-1.00000]\n Explanation: After exactly one second, the first car will collide with the second car, and form a car fleet with speed 1 m/s. After exactly 3 seconds, the third car will collide with the fourth car, and form a car fleet with speed 2 m/s.\n Example 2:\n Input: cars = [[3,4],[5,4],[6,3],[9,1]]\n Output: [2.00000,1.00000,1.50000,-1.00000]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1796, - "title": "Second Largest Digit in a String", - "question": "class Solution:\n def secondHighest(self, s: str) -> int:\n \"\"\"\n Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.\n An alphanumeric string is a string consisting of lowercase English letters and digits.\n Example 1:\n Input: s = \"dfa12321afd\"\n Output: 2\n Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.\n Example 2:\n Input: s = \"abc1111\"\n Output: -1\n Explanation: The digits that appear in s are [1]. There is no second largest digit. \n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1797, - "title": "Design Authentication Manager", - "question": "class AuthenticationManager:\n def __init__(self, timeToLive: int):\n def generate(self, tokenId: str, currentTime: int) -> None:\n def renew(self, tokenId: str, currentTime: int) -> None:\n def countUnexpiredTokens(self, currentTime: int) -> int:\n \"\"\"\n There is an authentication system that works with authentication tokens. For each session, the user will receive a new authentication token that will expire timeToLive seconds after the currentTime. If the token is renewed, the expiry time will be extended to expire timeToLive seconds after the (potentially different) currentTime.\n Implement the AuthenticationManager class:\n AuthenticationManager(int timeToLive) constructs the AuthenticationManager and sets the timeToLive.\n generate(string tokenId, int currentTime) generates a new token with the given tokenId at the given currentTime in seconds.\n renew(string tokenId, int currentTime) renews the unexpired token with the given tokenId at the given currentTime in seconds. If there are no unexpired tokens with the given tokenId, the request is ignored, and nothing happens.\n countUnexpiredTokens(int currentTime) returns the number of unexpired tokens at the given currentTime.\n Note that if a token expires at time t, and another action happens on time t (renew or countUnexpiredTokens), the expiration takes place before the other actions.\n Example 1:\n Input\n [\"AuthenticationManager\", \"renew\", \"generate\", \"countUnexpiredTokens\", \"generate\", \"renew\", \"renew\", \"countUnexpiredTokens\"]\n [[5], [\"aaa\", 1], [\"aaa\", 2], [6], [\"bbb\", 7], [\"aaa\", 8], [\"bbb\", 10], [15]]\n Output\n [null, null, null, 1, null, null, null, 0]\n Explanation\n AuthenticationManager authenticationManager = new AuthenticationManager(5); // Constructs the AuthenticationManager with timeToLive = 5 seconds.\n authenticationManager.renew(\"aaa\", 1); // No token exists with tokenId \"aaa\" at time 1, so nothing happens.\n authenticationManager.generate(\"aaa\", 2); // Generates a new token with tokenId \"aaa\" at time 2.\n authenticationManager.countUnexpiredTokens(6); // The token with tokenId \"aaa\" is the only unexpired one at time 6, so return 1.\n authenticationManager.generate(\"bbb\", 7); // Generates a new token with tokenId \"bbb\" at time 7.\n authenticationManager.renew(\"aaa\", 8); // The token with tokenId \"aaa\" expired at time 7, and 8 >= 7, so at time 8 the renew request is ignored, and nothing happens.\n authenticationManager.renew(\"bbb\", 10); // The token with tokenId \"bbb\" is unexpired at time 10, so the renew request is fulfilled and now the token will expire at time 15.\n authenticationManager.countUnexpiredTokens(15); // The token with tokenId \"bbb\" expires at time 15, and the token with tokenId \"aaa\" expired at time 7, so currently no token is unexpired, so return 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1799, - "title": "Maximize Score After N Operations", - "question": "class Solution:\n def maxScore(self, nums: List[int]) -> int:\n \"\"\"\n You are given nums, an array of positive integers of size 2 * n. You must perform n operations on this array.\n In the ith operation (1-indexed), you will:\n Choose two elements, x and y.\n Receive a score of i * gcd(x, y).\n Remove x and y from nums.\n Return the maximum score you can receive after performing n operations.\n The function gcd(x, y) is the greatest common divisor of x and y.\n Example 1:\n Input: nums = [1,2]\n Output: 1\n Explanation: The optimal choice of operations is:\n (1 * gcd(1, 2)) = 1\n Example 2:\n Input: nums = [3,4,6,8]\n Output: 11\n Explanation: The optimal choice of operations is:\n (1 * gcd(3, 6)) + (2 * gcd(4, 8)) = 3 + 8 = 11\n Example 3:\n Input: nums = [1,2,3,4,5,6]\n Output: 14\n Explanation: The optimal choice of operations is:\n (1 * gcd(1, 5)) + (2 * gcd(2, 4)) + (3 * gcd(3, 6)) = 1 + 4 + 9 = 14\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1803, - "title": "Count Pairs With XOR in a Range", - "question": "class Solution:\n def countPairs(self, nums: List[int], low: int, high: int) -> int:\n \"\"\"\n Given a (0-indexed) integer array nums and two integers low and high, return the number of nice pairs.\r\n A nice pair is a pair (i, j) where 0 <= i < j < nums.length and low <= (nums[i] XOR nums[j]) <= high.\r\n Example 1:\r\n Input: nums = [1,4,2,7], low = 2, high = 6\r\n Output: 6\r\n Explanation: All nice pairs (i, j) are as follows:\r\n - (0, 1): nums[0] XOR nums[1] = 5 \r\n - (0, 2): nums[0] XOR nums[2] = 3\r\n - (0, 3): nums[0] XOR nums[3] = 6\r\n - (1, 2): nums[1] XOR nums[2] = 6\r\n - (1, 3): nums[1] XOR nums[3] = 3\r\n - (2, 3): nums[2] XOR nums[3] = 5\r\n Example 2:\r\n Input: nums = [9,8,4,2,1], low = 5, high = 14\r\n Output: 8\r\n Explanation: All nice pairs (i, j) are as follows:\r\n \u200b\u200b\u200b\u200b\u200b - (0, 2): nums[0] XOR nums[2] = 13\r\n - (0, 3): nums[0] XOR nums[3] = 11\r\n - (0, 4): nums[0] XOR nums[4] = 8\r\n - (1, 2): nums[1] XOR nums[2] = 12\r\n - (1, 3): nums[1] XOR nums[3] = 10\r\n - (1, 4): nums[1] XOR nums[4] = 9\r\n - (2, 3): nums[2] XOR nums[3] = 6\r\n - (2, 4): nums[2] XOR nums[4] = 5\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1784, - "title": "Check if Binary String Has at Most One Segment of Ones", - "question": "class Solution:\n def checkOnesSegment(self, s: str) -> bool:\n \"\"\"\n Given a binary string s \u200b\u200b\u200b\u200b\u200bwithout leading zeros, return true\u200b\u200b\u200b if s contains at most one contiguous segment of ones. Otherwise, return false.\n Example 1:\n Input: s = \"1001\"\n Output: false\n Explanation: The ones do not form a contiguous segment.\n Example 2:\n Input: s = \"110\"\n Output: true\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1785, - "title": "Minimum Elements to Add to Form a Given Sum", - "question": "class Solution:\n def minElements(self, nums: List[int], limit: int, goal: int) -> int:\n \"\"\"\n 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.\n Return 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.\n Note that abs(x) equals x if x >= 0, and -x otherwise.\n Example 1:\n Input: nums = [1,-1,1], limit = 3, goal = -4\n Output: 2\n Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4.\n Example 2:\n Input: nums = [1,-10,9,1], limit = 100, goal = 0\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1786, - "title": "Number of Restricted Paths From First to Last Node", - "question": "class Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n \"\"\"\n 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.\n A 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.\n The 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.\n Return 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:\n Input: n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]\n Output: 3\n Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:\n 1) 1 --> 2 --> 5\n 2) 1 --> 2 --> 3 --> 5\n 3) 1 --> 3 --> 5\n Example 2:\n Input: 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]]\n Output: 1\n Explanation: Each circle contains the node number in black and its distanceToLastNode value in blue. The only restricted path is 1 --> 3 --> 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1787, - "title": "Make the XOR of All Segments Equal to Zero", - "question": "class Solution:\n def minChanges(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an array nums\u200b\u200b\u200b and an integer k\u200b\u200b\u200b\u200b\u200b. The XOR of a segment [left, right] where left <= right is the XOR of all the elements with indices between left and right, inclusive: nums[left] XOR nums[left+1] XOR ... XOR nums[right].\n Return the minimum number of elements to change in the array such that the XOR of all segments of size k\u200b\u200b\u200b\u200b\u200b\u200b is equal to zero.\n Example 1:\n Input: nums = [1,2,0,3,0], k = 1\n Output: 3\n Explanation: Modify the array from [1,2,0,3,0] to from [0,0,0,0,0].\n Example 2:\n Input: nums = [3,4,5,2,1,7,3,4,7], k = 3\n Output: 3\n Explanation: Modify the array from [3,4,5,2,1,7,3,4,7] to [3,4,7,3,4,7,3,4,7].\n Example 3:\n Input: nums = [1,2,4,1,2,5,1,2,6], k = 3\n Output: 3\n Explanation: Modify the array from [1,2,4,1,2,5,1,2,6] to [1,2,3,1,2,3,1,2,3].\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1790, - "title": "Check if One String Swap Can Make Strings Equal", - "question": "class Solution:\n def areAlmostEqual(self, s1: str, s2: str) -> bool:\n \"\"\"\n 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.\n Return 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:\n Input: s1 = \"bank\", s2 = \"kanb\"\n Output: true\n Explanation: For example, swap the first character with the last character of s2 to make \"bank\".\n Example 2:\n Input: s1 = \"attack\", s2 = \"defend\"\n Output: false\n Explanation: It is impossible to make them equal with one string swap.\n Example 3:\n Input: s1 = \"kelb\", s2 = \"kelb\"\n Output: true\n Explanation: The two strings are already equal, so no string swap operation is required.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1791, - "title": "Find Center of Star Graph", - "question": "class Solution:\n def findCenter(self, edges: List[List[int]]) -> int:\n \"\"\"\n 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.\n You 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:\n Input: edges = [[1,2],[2,3],[4,2]]\n Output: 2\n Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.\n Example 2:\n Input: edges = [[1,2],[5,1],[1,3],[1,4]]\n Output: 1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1792, - "title": "Maximum Average Pass Ratio", - "question": "class Solution:\n def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:\n \"\"\"\n 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.\n You 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.\n The 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.\n Return 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:\n Input: classes = [[1,2],[3,5],[2,2]], extraStudents = 2\n Output: 0.78333\n Explanation: You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.\n Example 2:\n Input: classes = [[2,4],[3,9],[4,5],[2,10]], extraStudents = 4\n Output: 0.53485\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1793, - "title": "Maximum Score of a Good Subarray", - "question": "class Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n \"\"\"\n You are given an array of integers nums (0-indexed) and an integer k.\n The score of a subarray (i, j) is defined as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A good subarray is a subarray where i <= k <= j.\n Return the maximum possible score of a good subarray.\n Example 1:\n Input: nums = [1,4,3,7,4,5], k = 3\n Output: 15\n Explanation: The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. \n Example 2:\n Input: nums = [5,5,4,5,4,1,1,1], k = 0\n Output: 20\n Explanation: The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1812, - "title": "Determine Color of a Chessboard Square", - "question": "class Solution:\n def squareIsWhite(self, coordinates: str) -> bool:\n \"\"\"\n You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.\n Return true if the square is white, and false if the square is black.\n The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.\n Example 1:\n Input: coordinates = \"a1\"\n Output: false\n Explanation: From the chessboard above, the square with coordinates \"a1\" is black, so return false.\n Example 2:\n Input: coordinates = \"h3\"\n Output: true\n Explanation: From the chessboard above, the square with coordinates \"h3\" is white, so return true.\n Example 3:\n Input: coordinates = \"c7\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1813, - "title": "Sentence Similarity III", - "question": "class Solution:\n def areSentencesSimilar(self, sentence1: str, sentence2: str) -> bool:\n \"\"\"\n 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.\n Two 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.\n Given two sentences sentence1 and sentence2, return true if sentence1 and sentence2 are similar. Otherwise, return false.\n Example 1:\n Input: sentence1 = \"My name is Haley\", sentence2 = \"My Haley\"\n Output: true\n Explanation: sentence2 can be turned to sentence1 by inserting \"name is\" between \"My\" and \"Haley\".\n Example 2:\n Input: sentence1 = \"of\", sentence2 = \"A lot of words\"\n Output: false\n Explanation: No single sentence can be inserted inside one of the sentences to make it equal to the other.\n Example 3:\n Input: sentence1 = \"Eating right now\", sentence2 = \"Eating\"\n Output: true\n Explanation: sentence2 can be turned to sentence1 by inserting \"right now\" at the end of the sentence.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1815, - "title": "Maximum Number of Groups Getting Fresh Donuts", - "question": "class Solution:\n def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int:\n \"\"\"\n There is a donuts shop that bakes donuts in batches of batchSize. They have a rule where they must serve all of the donuts of a batch before serving any donuts of the next batch. You are given an integer batchSize and an integer array groups, where groups[i] denotes that there is a group of groups[i] customers that will visit the shop. Each customer will get exactly one donut.\n When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.\n You can freely rearrange the ordering of the groups. Return the maximum possible number of happy groups after rearranging the groups.\n Example 1:\n Input: batchSize = 3, groups = [1,2,3,4,5,6]\n Output: 4\n Explanation: You can arrange the groups as [6,2,4,5,1,3]. Then the 1st, 2nd, 4th, and 6th groups will be happy.\n Example 2:\n Input: batchSize = 4, groups = [1,3,2,5,2,2,1,6]\n Output: 4\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1814, - "title": "Count Nice Pairs in an Array", - "question": "class Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n \"\"\"\n 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:\n 0 <= i < j < nums.length\n nums[i] + rev(nums[j]) == nums[j] + rev(nums[i])\n Return the number of nice pairs of indices. Since that number can be too large, return it modulo 109 + 7.\n Example 1:\n Input: nums = [42,11,1,97]\n Output: 2\n Explanation: The two pairs are:\n - (0,3) : 42 + rev(97) = 42 + 79 = 121, 97 + rev(42) = 97 + 24 = 121.\n - (1,2) : 11 + rev(1) = 11 + 1 = 12, 1 + rev(11) = 1 + 11 = 12.\n Example 2:\n Input: nums = [13,10,35,24,76]\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1800, - "title": "Maximum Ascending Subarray Sum", - "question": "class Solution:\n def maxAscendingSum(self, nums: List[int]) -> int:\n \"\"\"\n Given an array of positive integers nums, return the maximum possible sum of an ascending subarray in nums.\n A subarray is defined as a contiguous sequence of numbers in an array.\n A 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:\n Input: nums = [10,20,30,5,10,50]\n Output: 65\n Explanation: [5,10,50] is the ascending subarray with the maximum sum of 65.\n Example 2:\n Input: nums = [10,20,30,40,50]\n Output: 150\n Explanation: [10,20,30,40,50] is the ascending subarray with the maximum sum of 150.\n Example 3:\n Input: nums = [12,17,15,13,10,11,12]\n Output: 33\n Explanation: [10,11,12] is the ascending subarray with the maximum sum of 33.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1801, - "title": "Number of Orders in the Backlog", - "question": "class Solution:\n def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:\n \"\"\"\n 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:\r\n 0 if it is a batch of buy orders, or\r\n 1 if it is a batch of sell orders.\r\n Note 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.\r\n There 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:\r\n If 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.\r\n Vice 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.\r\n Return 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.\r\n Example 1:\r\n Input: orders = [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]\r\n Output: 6\r\n Explanation: Here is what happens with the orders:\r\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.\r\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.\r\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.\r\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.\r\n Finally, 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.\r\n Example 2:\r\n Input: orders = [[7,1000000000,1],[15,3,0],[5,999999995,0],[5,1,1]]\r\n Output: 999999984\r\n Explanation: Here is what happens with the orders:\r\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.\r\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.\r\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.\r\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.\r\n Finally, 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).\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1802, - "title": "Maximum Value at a Given Index in a Bounded Array", - "question": "class Solution:\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n \"\"\"\n You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:\n nums.length == n\n nums[i] is a positive integer where 0 <= i < n.\n abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1.\n The sum of all the elements of nums does not exceed maxSum.\n nums[index] is maximized.\n Return nums[index] of the constructed array.\n Note that abs(x) equals x if x >= 0, and -x otherwise.\n Example 1:\n Input: n = 4, index = 2, maxSum = 6\n Output: 2\n Explanation: nums = [1,2,2,1] is one array that satisfies all the conditions.\n There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].\n Example 2:\n Input: n = 6, index = 1, maxSum = 10\n Output: 3\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1798, - "title": "Maximum Number of Consecutive Values You Can Make", - "question": "class Solution:\n def getMaximumConsecutive(self, coins: List[int]) -> int:\n \"\"\"\n 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.\n Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.\n Note that you may have multiple coins of the same value.\n Example 1:\n Input: coins = [1,3]\n Output: 2\n Explanation: You can make the following values:\n - 0: take []\n - 1: take [1]\n You can make 2 consecutive integer values starting from 0.\n Example 2:\n Input: coins = [1,1,1,4]\n Output: 8\n Explanation: 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]\n You can make 8 consecutive integer values starting from 0.\n Example 3:\n Input: nums = [1,4,10,3,1]\n Output: 20\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1805, - "title": "Number of Different Integers in a String", - "question": "class Solution:\n def numDifferentIntegers(self, word: str) -> int:\n \"\"\"\n You are given a string word that consists of digits and lowercase English letters.\n You 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\".\n Return the number of different integers after performing the replacement operations on word.\n Two integers are considered different if their decimal representations without any leading zeros are different.\n Example 1:\n Input: word = \"a123bc34d8ef34\"\n Output: 3\n Explanation: The three different integers are \"123\", \"34\", and \"8\". Notice that \"34\" is only counted once.\n Example 2:\n Input: word = \"leet1234code234\"\n Output: 2\n Example 3:\n Input: word = \"a1b01c001\"\n Output: 1\n Explanation: The three integers \"1\", \"01\", and \"001\" all represent the same integer because\n the leading zeros are ignored when comparing their decimal values.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1807, - "title": "Evaluate the Bracket Pairs of a String", - "question": "class Solution:\n def evaluate(self, s: str, knowledge: List[List[str]]) -> str:\n \"\"\"\n You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.\n For example, in the string \"(name)is(age)yearsold\", there are two bracket pairs that contain the keys \"name\" and \"age\".\n You 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.\n You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:\n Replace keyi and the bracket pair with the key's corresponding valuei.\n If 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).\n Each key will appear at most once in your knowledge. There will not be any nested brackets in s.\n Return the resulting string after evaluating all of the bracket pairs.\n Example 1:\n Input: s = \"(name)is(age)yearsold\", knowledge = [[\"name\",\"bob\"],[\"age\",\"two\"]]\n Output: \"bobistwoyearsold\"\n Explanation:\n The key \"name\" has a value of \"bob\", so replace \"(name)\" with \"bob\".\n The key \"age\" has a value of \"two\", so replace \"(age)\" with \"two\".\n Example 2:\n Input: s = \"hi(name)\", knowledge = [[\"a\",\"b\"]]\n Output: \"hi?\"\n Explanation: As you do not know the value of the key \"name\", replace \"(name)\" with \"?\".\n Example 3:\n Input: s = \"(a)(a)(a)aaa\", knowledge = [[\"a\",\"yes\"]]\n Output: \"yesyesyesaaa\"\n Explanation: The same key can appear multiple times.\n The key \"a\" has a value of \"yes\", so replace all occurrences of \"(a)\" with \"yes\".\n Notice that the \"a\"s not in a bracket pair are not evaluated.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1806, - "title": "Minimum Number of Operations to Reinitialize a Permutation", - "question": "class Solution:\n def reinitializePermutation(self, n: int) -> int:\n \"\"\"\n You are given an even integer n\u200b\u200b\u200b\u200b\u200b\u200b. You initially have a permutation perm of size n\u200b\u200b where perm[i] == i\u200b (0-indexed)\u200b\u200b\u200b\u200b.\n In one operation, you will create a new array arr, and for each i:\n If i % 2 == 0, then arr[i] = perm[i / 2].\n If i % 2 == 1, then arr[i] = perm[n / 2 + (i - 1) / 2].\n You will then assign arr\u200b\u200b\u200b\u200b to perm.\n Return the minimum non-zero number of operations you need to perform on perm to return the permutation to its initial value.\n Example 1:\n Input: n = 2\n Output: 1\n Explanation: perm = [0,1] initially.\n After the 1st operation, perm = [0,1]\n So it takes only 1 operation.\n Example 2:\n Input: n = 4\n Output: 2\n Explanation: perm = [0,1,2,3] initially.\n After the 1st operation, perm = [0,2,1,3]\n After the 2nd operation, perm = [0,1,2,3]\n So it takes only 2 operations.\n Example 3:\n Input: n = 6\n Output: 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1808, - "title": "Maximize Number of Nice Divisors", - "question": "class Solution:\n def maxNiceDivisors(self, primeFactors: int) -> int:\n \"\"\"\n You are given a positive integer primeFactors. You are asked to construct a positive integer n that satisfies the following conditions:\r\n The number of prime factors of n (not necessarily distinct) is at most primeFactors.\r\n The number of nice divisors of n is maximized. Note that a divisor of n is nice if it is divisible by every prime factor of n. For example, if n = 12, then its prime factors are [2,2,3], then 6 and 12 are nice divisors, while 3 and 4 are not.\r\n Return the number of nice divisors of n. Since that number can be too large, return it modulo 109 + 7.\r\n Note that a prime number is a natural number greater than 1 that is not a product of two smaller natural numbers. The prime factors of a number n is a list of prime numbers such that their product equals n.\r\n Example 1:\r\n Input: primeFactors = 5\r\n Output: 6\r\n Explanation: 200 is a valid value of n.\r\n It has 5 prime factors: [2,2,2,5,5], and it has 6 nice divisors: [10,20,40,50,100,200].\r\n There is not other value of n that has at most 5 prime factors and more nice divisors.\r\n Example 2:\r\n Input: primeFactors = 8\r\n Output: 18\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1827, - "title": "Minimum Operations to Make the Array Increasing", - "question": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n \"\"\"\n 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.\r\n For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3].\r\n Return the minimum number of operations needed to make nums strictly increasing.\r\n An 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.\r\n Example 1:\r\n Input: nums = [1,1,1]\r\n Output: 3\r\n Explanation: You can do the following operations:\r\n 1) Increment nums[2], so nums becomes [1,1,2].\r\n 2) Increment nums[1], so nums becomes [1,2,2].\r\n 3) Increment nums[2], so nums becomes [1,2,3].\r\n Example 2:\r\n Input: nums = [1,5,2,4,1]\r\n Output: 14\r\n Example 3:\r\n Input: nums = [8]\r\n Output: 0\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1828, - "title": "Queries on Number of Points Inside a Circle", - "question": "class Solution:\n def countPoints(self, points: List[List[int]], queries: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n You are also given an array queries where queries[j] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.\n For each query queries[j], compute the number of points inside the jth circle. Points on the border of the circle are considered inside.\n Return an array answer, where answer[j] is the answer to the jth query.\n Example 1:\n Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]\n Output: [3,2,2]\n Explanation: The points and circles are shown above.\n queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.\n Example 2:\n Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]\n Output: [2,3,2,4]\n Explanation: The points and circles are shown above.\n queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1829, - "title": "Maximum XOR for Each Query", - "question": "class Solution:\n def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:\n \"\"\"\n 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:\n Find 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.\n Remove the last element from the current array nums.\n Return an array answer, where answer[i] is the answer to the ith query.\n Example 1:\n Input: nums = [0,1,1,3], maximumBit = 2\n Output: [0,3,2,3]\n Explanation: The queries are answered as follows:\n 1st query: nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.\n 2nd query: nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.\n 3rd query: nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.\n 4th query: nums = [0], k = 3 since 0 XOR 3 = 3.\n Example 2:\n Input: nums = [2,3,4,7], maximumBit = 3\n Output: [5,2,6,5]\n Explanation: The queries are answered as follows:\n 1st query: nums = [2,3,4,7], k = 5 since 2 XOR 3 XOR 4 XOR 7 XOR 5 = 7.\n 2nd query: nums = [2,3,4], k = 2 since 2 XOR 3 XOR 4 XOR 2 = 7.\n 3rd query: nums = [2,3], k = 6 since 2 XOR 3 XOR 6 = 7.\n 4th query: nums = [2], k = 5 since 2 XOR 5 = 7.\n Example 3:\n Input: nums = [0,1,2,2,5,7], maximumBit = 3\n Output: [4,3,6,4,6,7]\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1830, - "title": "Minimum Number of Operations to Make String Sorted", - "question": "class Solution:\n def makeStringSorted(self, s: str) -> int:\n \"\"\"\n You are given a string s (0-indexed)\u200b\u200b\u200b\u200b\u200b\u200b. You are asked to perform the following operation on s\u200b\u200b\u200b\u200b\u200b\u200b until you get a sorted string:\n Find the largest index i such that 1 <= i < s.length and s[i] < s[i - 1].\n Find 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.\n Swap the two characters at indices i - 1\u200b\u200b\u200b\u200b and j\u200b\u200b\u200b\u200b\u200b.\n Reverse the suffix starting at index i\u200b\u200b\u200b\u200b\u200b\u200b.\n Return 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:\n Input: s = \"cba\"\n Output: 5\n Explanation: The simulation goes as follows:\n Operation 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\".\n Operation 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\".\n Operation 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\".\n Operation 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\".\n Operation 5: i=2, j=2. Swap s[1] and s[2] to get s=\"abc\", then reverse the suffix starting at 2. Now, s=\"abc\".\n Example 2:\n Input: s = \"aabaa\"\n Output: 2\n Explanation: The simulation goes as follows:\n Operation 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\".\n Operation 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1816, - "title": "Truncate Sentence", - "question": "class Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n \"\"\"\n 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).\n For example, \"Hello World\", \"HELLO\", and \"hello world hello world\" are all sentences.\n You are given a sentence s\u200b\u200b\u200b\u200b\u200b\u200b and an integer k\u200b\u200b\u200b\u200b\u200b\u200b. You want to truncate s\u200b\u200b\u200b\u200b\u200b\u200b such that it contains only the first k\u200b\u200b\u200b\u200b\u200b\u200b words. Return s\u200b\u200b\u200b\u200b\u200b\u200b after truncating it.\n Example 1:\n Input: s = \"Hello how are you Contestant\", k = 4\n Output: \"Hello how are you\"\n Explanation:\n The words in s are [\"Hello\", \"how\" \"are\", \"you\", \"Contestant\"].\n The first 4 words are [\"Hello\", \"how\", \"are\", \"you\"].\n Hence, you should return \"Hello how are you\".\n Example 2:\n Input: s = \"What is the solution to this problem\", k = 4\n Output: \"What is the solution\"\n Explanation:\n The words in s are [\"What\", \"is\" \"the\", \"solution\", \"to\", \"this\", \"problem\"].\n The first 4 words are [\"What\", \"is\", \"the\", \"solution\"].\n Hence, you should return \"What is the solution\".\n Example 3:\n Input: s = \"chopper is not a tanuki\", k = 5\n Output: \"chopper is not a tanuki\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1817, - "title": "Finding the Users Active Minutes", - "question": "class Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n \"\"\"\n 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.\n Multiple users can perform actions simultaneously, and a single user can perform multiple actions in the same minute.\n The 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.\n You 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.\n Return the array answer as described above.\n Example 1:\n Input: logs = [[0,5],[1,2],[0,2],[0,5],[1,3]], k = 5\n Output: [0,2,0,0,0]\n Explanation:\n The 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).\n The user with ID=1 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\n Since both users have a UAM of 2, answer[2] is 2, and the remaining answer[j] values are 0.\n Example 2:\n Input: logs = [[1,1],[2,2],[2,3]], k = 4\n Output: [1,1,0,0]\n Explanation:\n The user with ID=1 performed a single action at minute 1. Hence, they have a UAM of 1.\n The user with ID=2 performed actions at minutes 2 and 3. Hence, they have a UAM of 2.\n There is one user with a UAM of 1 and one with a UAM of 2.\n Hence, answer[1] = 1, answer[2] = 1, and the remaining values are 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1818, - "title": "Minimum Absolute Sum Difference", - "question": "class Solution:\n def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n You are given two positive integer arrays nums1 and nums2, both of length n.\n The 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).\n You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.\n Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.\n |x| is defined as:\n x if x >= 0, or\n -x if x < 0.\n Example 1:\n Input: nums1 = [1,7,5], nums2 = [2,3,5]\n Output: 3\n Explanation: 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].\n Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.\n Example 2:\n Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]\n Output: 0\n Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an \n absolute sum difference of 0.\n Example 3:\n Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]\n Output: 20\n Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].\n This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1819, - "title": "Number of Different Subsequences GCDs", - "question": "class Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n \"\"\"\n You are given an array nums that consists of positive integers.\n The GCD of a sequence of numbers is defined as the greatest integer that divides all the numbers in the sequence evenly.\n For example, the GCD of the sequence [4,6,16] is 2.\n A subsequence of an array is a sequence that can be formed by removing some elements (possibly none) of the array.\n For example, [2,5,10] is a subsequence of [1,2,1,2,4,1,5,10].\n Return the number of different GCDs among all non-empty subsequences of nums.\n Example 1:\n Input: nums = [6,10,3]\n Output: 5\n Explanation: The figure shows all the non-empty subsequences and their GCDs.\n The different GCDs are 6, 10, 3, 2, and 1.\n Example 2:\n Input: nums = [5,15,40,5,6]\n Output: 7\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1822, - "title": "Sign of the Product of an Array", - "question": "class Solution:\n def arraySign(self, nums: List[int]) -> int:\n \"\"\"\n There is a function signFunc(x) that returns:\n 1 if x is positive.\n -1 if x is negative.\n 0 if x is equal to 0.\n You are given an integer array nums. Let product be the product of all values in the array nums.\n Return signFunc(product).\n Example 1:\n Input: nums = [-1,-2,-3,-4,3,2,1]\n Output: 1\n Explanation: The product of all values in the array is 144, and signFunc(144) = 1\n Example 2:\n Input: nums = [1,5,0,2,-3]\n Output: 0\n Explanation: The product of all values in the array is 0, and signFunc(0) = 0\n Example 3:\n Input: nums = [-1,1,-1,1,-1]\n Output: -1\n Explanation: The product of all values in the array is -1, and signFunc(-1) = -1\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1823, - "title": "Find the Winner of the Circular Game", - "question": "class Solution:\n def findTheWinner(self, n: int, k: int) -> int:\n \"\"\"\n 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.\n The rules of the game are as follows:\n Start at the 1st friend.\n Count 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.\n The last friend you counted leaves the circle and loses the game.\n If 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.\n Else, the last friend in the circle wins the game.\n Given the number of friends, n, and an integer k, return the winner of the game.\n Example 1:\n Input: n = 5, k = 2\n Output: 3\n Explanation: Here are the steps of the game:\n 1) Start at friend 1.\n 2) Count 2 friends clockwise, which are friends 1 and 2.\n 3) Friend 2 leaves the circle. Next start is friend 3.\n 4) Count 2 friends clockwise, which are friends 3 and 4.\n 5) Friend 4 leaves the circle. Next start is friend 5.\n 6) Count 2 friends clockwise, which are friends 5 and 1.\n 7) Friend 1 leaves the circle. Next start is friend 3.\n 8) Count 2 friends clockwise, which are friends 3 and 5.\n 9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.\n Example 2:\n Input: n = 6, k = 5\n Output: 1\n Explanation: The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1824, - "title": "Minimum Sideway Jumps", - "question": "class Solution:\n def minSideJumps(self, obstacles: List[int]) -> int:\n \"\"\"\n 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.\n You 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.\n For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.\n The 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.\n For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.\n Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.\n Note: There will be no obstacles on points 0 and n.\n Example 1:\n Input: obstacles = [0,1,2,3,0]\n Output: 2 \n Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).\n Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).\n Example 2:\n Input: obstacles = [0,1,1,3,3,0]\n Output: 0\n Explanation: There are no obstacles on lane 2. No side jumps are required.\n Example 3:\n Input: obstacles = [0,2,1,0,3,0]\n Output: 2\n Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1825, - "title": "Finding MK Average", - "question": "class MKAverage:\n def __init__(self, m: int, k: int):\n def addElement(self, num: int) -> None:\n def calculateMKAverage(self) -> int:\n \"\"\"\n You are given two integers, m and k, and a stream of integers. You are tasked to implement a data structure that calculates the MKAverage for the stream.\n The MKAverage can be calculated using these steps:\n If the number of the elements in the stream is less than m you should consider the MKAverage to be -1. Otherwise, copy the last m elements of the stream to a separate container.\n Remove the smallest k elements and the largest k elements from the container.\n Calculate the average value for the rest of the elements rounded down to the nearest integer.\n Implement the MKAverage class:\n MKAverage(int m, int k) Initializes the MKAverage object with an empty stream and the two integers m and k.\n void addElement(int num) Inserts a new element num into the stream.\n int calculateMKAverage() Calculates and returns the MKAverage for the current stream rounded down to the nearest integer.\n Example 1:\n Input\n [\"MKAverage\", \"addElement\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"calculateMKAverage\", \"addElement\", \"addElement\", \"addElement\", \"calculateMKAverage\"]\n [[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]\n Output\n [null, null, null, -1, null, 3, null, null, null, 5]\n Explanation\n MKAverage obj = new MKAverage(3, 1); \n obj.addElement(3); // current elements are [3]\n obj.addElement(1); // current elements are [3,1]\n obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist.\n obj.addElement(10); // current elements are [3,1,10]\n obj.calculateMKAverage(); // The last 3 elements are [3,1,10].\n // After removing smallest and largest 1 element the container will be [3].\n // The average of [3] equals 3/1 = 3, return 3\n obj.addElement(5); // current elements are [3,1,10,5]\n obj.addElement(5); // current elements are [3,1,10,5,5]\n obj.addElement(5); // current elements are [3,1,10,5,5,5]\n obj.calculateMKAverage(); // The last 3 elements are [5,5,5].\n // After removing smallest and largest 1 element the container will be [5].\n // The average of [5] equals 5/1 = 5, return 5\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1844, - "title": "Replace All Digits with Characters", - "question": "class Solution:\n def replaceDigits(self, s: str) -> str:\n \"\"\"\n You are given a 0-indexed string s that has lowercase English letters in its even indices and digits in its odd indices.\n There is a function shift(c, x), where c is a character and x is a digit, that returns the xth character after c.\n For example, shift('a', 5) = 'f' and shift('x', 0) = 'x'.\n For every odd index i, you want to replace the digit s[i] with shift(s[i-1], s[i]).\n Return s after replacing all digits. It is guaranteed that shift(s[i-1], s[i]) will never exceed 'z'.\n Example 1:\n Input: s = \"a1c1e1\"\n Output: \"abcdef\"\n Explanation: 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'\n Example 2:\n Input: s = \"a1b2c3d4e\"\n Output: \"abbdcfdhe\"\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1845, - "title": "Seat Reservation Manager", - "question": "class SeatManager:\n def __init__(self, n: int):\n def reserve(self) -> int:\n def unreserve(self, seatNumber: int) -> None:\n \"\"\"\n Design a system that manages the reservation state of n seats that are numbered from 1 to n.\n Implement the SeatManager class:\n SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available.\n int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number.\n void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.\n Example 1:\n Input\n [\"SeatManager\", \"reserve\", \"reserve\", \"unreserve\", \"reserve\", \"reserve\", \"reserve\", \"reserve\", \"unreserve\"]\n [[5], [], [], [2], [], [], [], [], [5]]\n Output\n [null, 1, 2, null, 2, 3, 4, 5, null]\n Explanation\n SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.\n seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.\n seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\n seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are [2,3,4,5].\n seatManager.reserve(); // The available seats are [2,3,4,5], so return the lowest of them, which is 2.\n seatManager.reserve(); // The available seats are [3,4,5], so return the lowest of them, which is 3.\n seatManager.reserve(); // The available seats are [4,5], so return the lowest of them, which is 4.\n seatManager.reserve(); // The only available seat is seat 5, so return 5.\n seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are [5].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1846, - "title": "Maximum Element After Decreasing and Rearranging", - "question": "class Solution:\n def maximumElementAfterDecrementingAndRearranging(self, arr: List[int]) -> int:\n \"\"\"\n You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:\n The value of the first element in arr must be 1.\n The 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.\n There are 2 types of operations that you can perform any number of times:\n Decrease the value of any element of arr to a smaller positive integer.\n Rearrange the elements of arr to be in any order.\n Return the maximum possible value of an element in arr after performing the operations to satisfy the conditions.\n Example 1:\n Input: arr = [2,2,1,2,1]\n Output: 2\n Explanation: \n We can satisfy the conditions by rearranging arr so it becomes [1,2,2,2,1].\n The largest element in arr is 2.\n Example 2:\n Input: arr = [100,1,1000]\n Output: 3\n Explanation: \n One possible way to satisfy the conditions is by doing the following:\n 1. Rearrange arr so it becomes [1,100,1000].\n 2. Decrease the value of the second element to 2.\n 3. Decrease the value of the third element to 3.\n Now arr = [1,2,3], which satisfies the conditions.\n The largest element in arr is 3.\n Example 3:\n Input: arr = [1,2,3,4,5]\n Output: 5\n Explanation: The array already satisfies the conditions, and the largest element is 5.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1847, - "title": "Closest Room", - "question": "class Solution:\n def closestRoom(self, rooms: List[List[int]], queries: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n You 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:\n The room has a size of at least minSizej, and\n abs(id - preferredj) is minimized, where abs(x) is the absolute value of x.\n If 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.\n Return an array answer of length k where answer[j] contains the answer to the jth query.\n Example 1:\n Input: rooms = [[2,2],[1,2],[3,2]], queries = [[3,1],[3,3],[5,2]]\n Output: [3,-1,3]\n Explanation: The answers to the queries are as follows:\n Query = [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.\n Query = [3,3]: There are no rooms with a size of at least 3, so the answer is -1.\n Query = [5,2]: Room number 3 is the closest as abs(3 - 5) = 2, and its size of 2 is at least 2. The answer is 3.\n Example 2:\n Input: rooms = [[1,4],[2,3],[3,5],[4,1],[5,2]], queries = [[2,3],[2,4],[2,5]]\n Output: [2,1,3]\n Explanation: The answers to the queries are as follows:\n Query = [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.\n Query = [2,4]: Room numbers 1 and 3 both have sizes of at least 4. The answer is 1 since it is smaller.\n Query = [2,5]: Room number 3 is the only room with a size of at least 5. The answer is 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1832, - "title": "Check if the Sentence Is Pangram", - "question": "class Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n \"\"\"\n A pangram is a sentence where every letter of the English alphabet appears at least once.\n Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.\n Example 1:\n Input: sentence = \"thequickbrownfoxjumpsoverthelazydog\"\n Output: true\n Explanation: sentence contains at least one of every letter of the English alphabet.\n Example 2:\n Input: sentence = \"leetcode\"\n Output: false\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1833, - "title": "Maximum Ice Cream Bars", - "question": "class Solution:\n def maxIceCream(self, costs: List[int], coins: int) -> int:\n \"\"\"\n It is a sweltering summer day, and a boy wants to buy some ice cream bars.\n At 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. \n Note: The boy can buy the ice cream bars in any order.\n Return the maximum number of ice cream bars the boy can buy with coins coins.\n You must solve the problem by counting sort.\n Example 1:\n Input: costs = [1,3,2,4,1], coins = 7\n Output: 4\n Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.\n Example 2:\n Input: costs = [10,6,8,7,7,8], coins = 5\n Output: 0\n Explanation: The boy cannot afford any of the ice cream bars.\n Example 3:\n Input: costs = [1,6,3,1,2,5], coins = 20\n Output: 6\n Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1834, - "title": "Single-Threaded CPU", - "question": "class Solution:\n def getOrder(self, tasks: List[List[int]]) -> List[int]:\n \"\"\"\n You are given n\u200b\u200b\u200b\u200b\u200b\u200b tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b task will be available to process at enqueueTimei and will take processingTimei to finish processing.\n You have a single-threaded CPU that can process at most one task at a time and will act in the following way:\n If the CPU is idle and there are no available tasks to process, the CPU remains idle.\n If 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.\n Once a task is started, the CPU will process the entire task without stopping.\n The CPU can finish a task then start a new one instantly.\n Return the order in which the CPU will process the tasks.\n Example 1:\n Input: tasks = [[1,2],[2,4],[3,2],[4,1]]\n Output: [0,2,3,1]\n Explanation: The events go as follows: \n - At time = 1, task 0 is available to process. Available tasks = {0}.\n - Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.\n - At time = 2, task 1 is available to process. Available tasks = {1}.\n - At time = 3, task 2 is available to process. Available tasks = {1, 2}.\n - Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.\n - At time = 4, task 3 is available to process. Available tasks = {1, 3}.\n - At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.\n - At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.\n - At time = 10, the CPU finishes task 1 and becomes idle.\n Example 2:\n Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]\n Output: [4,3,2,0,1]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1835, - "title": "Find XOR Sum of All Pairs Bitwise AND", - "question": "class Solution:\n def getXORSum(self, arr1: List[int], arr2: List[int]) -> int:\n \"\"\"\n 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.\n For 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.\n You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.\n Consider 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.\n Return the XOR sum of the aforementioned list.\n Example 1:\n Input: arr1 = [1,2,3], arr2 = [6,5]\n Output: 0\n Explanation: 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].\n The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.\n Example 2:\n Input: arr1 = [12], arr2 = [4]\n Output: 4\n Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1837, - "title": "Sum of Digits in Base K", - "question": "class Solution:\n def sumBase(self, n: int, k: int) -> int:\n \"\"\"\n 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.\n After converting, each digit should be interpreted as a base 10 number, and the sum should be returned in base 10.\n Example 1:\n Input: n = 34, k = 6\n Output: 9\n Explanation: 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.\n Example 2:\n Input: n = 10, k = 10\n Output: 1\n Explanation: n is already in base 10. 1 + 0 = 1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1838, - "title": "Frequency of the Most Frequent Element", - "question": "class Solution:\n def maxFrequency(self, nums: List[int], k: int) -> int:\n \"\"\"\n The frequency of an element is the number of times it occurs in an array.\n You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.\n Return the maximum possible frequency of an element after performing at most k operations.\n Example 1:\n Input: nums = [1,2,4], k = 5\n Output: 3\n Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].\n 4 has a frequency of 3.\n Example 2:\n Input: nums = [1,4,8,13], k = 5\n Output: 2\n Explanation: There are multiple optimal solutions:\n - Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.\n - Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.\n - Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.\n Example 3:\n Input: nums = [3,9,6], k = 2\n Output: 1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1839, - "title": "Longest Substring Of All Vowels in Order", - "question": "class Solution:\n def longestBeautifulSubstring(self, word: str) -> int:\n \"\"\"\n A string is considered beautiful if it satisfies the following conditions:\n Each of the 5 English vowels ('a', 'e', 'i', 'o', 'u') must appear at least once in it.\n The letters must be sorted in alphabetical order (i.e. all 'a's before 'e's, all 'e's before 'i's, etc.).\n For example, strings \"aeiou\" and \"aaaaaaeiiiioou\" are considered beautiful, but \"uaeio\", \"aeoiu\", and \"aaaeeeooo\" are not beautiful.\n Given a string word consisting of English vowels, return the length of the longest beautiful substring of word. If no such substring exists, return 0.\n A substring is a contiguous sequence of characters in a string.\n Example 1:\n Input: word = \"aeiaaioaaaaeiiiiouuuooaauuaeiu\"\n Output: 13\n Explanation: The longest beautiful substring in word is \"aaaaeiiiiouuu\" of length 13.\n Example 2:\n Input: word = \"aeeeiiiioooauuuaeiou\"\n Output: 5\n Explanation: The longest beautiful substring in word is \"aeiou\" of length 5.\n Example 3:\n Input: word = \"a\"\n Output: 0\n Explanation: There is no beautiful substring, so return 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1840, - "title": "Maximum Building Height", - "question": "class Solution:\n def maxBuilding(self, n: int, restrictions: List[List[int]]) -> int:\n \"\"\"\n 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.\n However, there are city restrictions on the heights of the new buildings:\n The height of each building must be a non-negative integer.\n The height of the first building must be 0.\n The height difference between any two adjacent buildings cannot exceed 1.\n Additionally, 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.\n It is guaranteed that each building will appear at most once in restrictions, and building 1 will not be in restrictions.\n Return the maximum possible height of the tallest building.\n Example 1:\n Input: n = 5, restrictions = [[2,1],[4,1]]\n Output: 2\n Explanation: The green area in the image indicates the maximum allowed height for each building.\n We can build the buildings with heights [0,1,2,1,2], and the tallest building has a height of 2.\n Example 2:\n Input: n = 6, restrictions = []\n Output: 5\n Explanation: The green area in the image indicates the maximum allowed height for each building.\n We can build the buildings with heights [0,1,2,3,4,5], and the tallest building has a height of 5.\n Example 3:\n Input: n = 10, restrictions = [[5,3],[2,5],[7,4],[10,3]]\n Output: 5\n Explanation: The green area in the image indicates the maximum allowed height for each building.\n We 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1859, - "title": "Sorting the Sentence", - "question": "class Solution:\n def sortSentence(self, s: str) -> str:\n \"\"\"\n 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.\r\n A sentence can be shuffled by appending the 1-indexed word position to each word then rearranging the words in the sentence.\r\n For example, the sentence \"This is a sentence\" can be shuffled as \"sentence4 a3 is2 This1\" or \"is2 sentence4 This1 a3\".\r\n Given a shuffled sentence s containing no more than 9 words, reconstruct and return the original sentence.\r\n Example 1:\r\n Input: s = \"is2 sentence4 This1 a3\"\r\n Output: \"This is a sentence\"\r\n Explanation: Sort the words in s to their original positions \"This1 is2 a3 sentence4\", then remove the numbers.\r\n Example 2:\r\n Input: s = \"Myself2 Me1 I4 and3\"\r\n Output: \"Me Myself and I\"\r\n Explanation: Sort the words in s to their original positions \"Me1 Myself2 and3 I4\", then remove the numbers.\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1860, - "title": "Incremental Memory Leak", - "question": "class Solution:\n def memLeak(self, memory1: int, memory2: int) -> List[int]:\n \"\"\"\n 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.\n At 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.\n Return 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:\n Input: memory1 = 2, memory2 = 2\n Output: [3,1,0]\n Explanation: The memory is allocated as follows:\n - At the 1st second, 1 bit of memory is allocated to stick 1. The first stick now has 1 bit of available memory.\n - At the 2nd second, 2 bits of memory are allocated to stick 2. The second stick now has 0 bits of available memory.\n - At the 3rd second, the program crashes. The sticks have 1 and 0 bits available respectively.\n Example 2:\n Input: memory1 = 8, memory2 = 11\n Output: [6,0,4]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1861, - "title": "Rotating the Box", - "question": "class Solution:\n def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n \"\"\"\n 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:\r\n A stone '#'\r\n A stationary obstacle '*'\r\n Empty '.'\r\n The 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.\r\n It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.\r\n Return an n x m matrix representing the box after the rotation described above.\r\n Example 1:\r\n Input: box = [[\"#\",\".\",\"#\"]]\r\n Output: [[\".\"],\r\n [\"#\"],\r\n [\"#\"]]\r\n Example 2:\r\n Input: box = [[\"#\",\".\",\"*\",\".\"],\r\n [\"#\",\"#\",\"*\",\".\"]]\r\n Output: [[\"#\",\".\"],\r\n [\"#\",\"#\"],\r\n [\"*\",\"*\"],\r\n [\".\",\".\"]]\r\n Example 3:\r\n Input: box = [[\"#\",\"#\",\"*\",\".\",\"*\",\".\"],\r\n [\"#\",\"#\",\"#\",\"*\",\".\",\".\"],\r\n [\"#\",\"#\",\"#\",\".\",\"#\",\".\"]]\r\n Output: [[\".\",\"#\",\"#\"],\r\n [\".\",\"#\",\"#\"],\r\n [\"#\",\"#\",\"*\"],\r\n [\"#\",\"*\",\".\"],\r\n [\"#\",\".\",\"*\"],\r\n [\"#\",\".\",\".\"]]\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1848, - "title": "Minimum Distance to the Target Element", - "question": "class Solution:\n def getMinDistance(self, nums: List[int], target: int, start: int) -> int:\n \"\"\"\n 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.\n Return abs(i - start).\n It is guaranteed that target exists in nums.\n Example 1:\n Input: nums = [1,2,3,4,5], target = 5, start = 3\n Output: 1\n Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.\n Example 2:\n Input: nums = [1], target = 1, start = 0\n Output: 0\n Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.\n Example 3:\n Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0\n Output: 0\n Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1849, - "title": "Splitting a String Into Descending Consecutive Values", - "question": "class Solution:\n def splitString(self, s: str) -> bool:\n \"\"\"\n You are given a string s that consists of only digits.\n Check 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.\n For 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.\n Another 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.\n Return true if it is possible to split s\u200b\u200b\u200b\u200b\u200b\u200b as described above, or false otherwise.\n A substring is a contiguous sequence of characters in a string.\n Example 1:\n Input: s = \"1234\"\n Output: false\n Explanation: There is no valid way to split s.\n Example 2:\n Input: s = \"050043\"\n Output: true\n Explanation: s can be split into [\"05\", \"004\", \"3\"] with numerical values [5,4,3].\n The values are in descending order with adjacent values differing by 1.\n Example 3:\n Input: s = \"9080701\"\n Output: false\n Explanation: There is no valid way to split s.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1851, - "title": "Minimum Interval to Include Each Query", - "question": "class Solution:\n def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:\n \"\"\"\n You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.\n You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.\n Return an array containing the answers to the queries.\n Example 1:\n Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]\n Output: [3,3,1,4]\n Explanation: The queries are processed as follows:\n - Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.\n - Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.\n - Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.\n - Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.\n Example 2:\n Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]\n Output: [2,-1,4,6]\n Explanation: The queries are processed as follows:\n - Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.\n - Query = 19: None of the intervals contain 19. The answer is -1.\n - Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.\n - Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1850, - "title": "Minimum Adjacent Swaps to Reach the Kth Smallest Number", - "question": "class Solution:\n def getMinSwaps(self, num: str, k: int) -> int:\n \"\"\"\n You are given a string num, representing a large integer, and an integer k.\n We 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.\n For example, when num = \"5489355142\":\n The 1st smallest wonderful integer is \"5489355214\".\n The 2nd smallest wonderful integer is \"5489355241\".\n The 3rd smallest wonderful integer is \"5489355412\".\n The 4th smallest wonderful integer is \"5489355421\".\n Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.\n The tests are generated in such a way that kth smallest wonderful integer exists.\n Example 1:\n Input: num = \"5489355142\", k = 4\n Output: 2\n Explanation: The 4th smallest wonderful number is \"5489355421\". To get this number:\n - Swap index 7 with index 8: \"5489355142\" -> \"5489355412\"\n - Swap index 8 with index 9: \"5489355412\" -> \"5489355421\"\n Example 2:\n Input: num = \"11112\", k = 4\n Output: 4\n Explanation: The 4th smallest wonderful number is \"21111\". To get this number:\n - Swap index 3 with index 4: \"11112\" -> \"11121\"\n - Swap index 2 with index 3: \"11121\" -> \"11211\"\n - Swap index 1 with index 2: \"11211\" -> \"12111\"\n - Swap index 0 with index 1: \"12111\" -> \"21111\"\n Example 3:\n Input: num = \"00123\", k = 1\n Output: 1\n Explanation: The 1st smallest wonderful number is \"00132\". To get this number:\n - Swap index 3 with index 4: \"00123\" -> \"00132\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1854, - "title": "Maximum Population Year", - "question": "class Solution:\n def maximumPopulation(self, logs: List[List[int]]) -> int:\n \"\"\"\n You are given a 2D integer array logs where each logs[i] = [birthi, deathi] indicates the birth and death years of the ith person.\n The 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.\n Return the earliest year with the maximum population.\n Example 1:\n Input: logs = [[1993,1999],[2000,2010]]\n Output: 1993\n Explanation: The maximum population is 1, and 1993 is the earliest year with this population.\n Example 2:\n Input: logs = [[1950,1961],[1960,1971],[1970,1981]]\n Output: 1960\n Explanation: \n The maximum population is 2, and it had happened in years 1960 and 1970.\n The earlier year between them is 1960.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1855, - "title": "Maximum Distance Between a Pair of Values", - "question": "class Solution:\n def maxDistance(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n You are given two non-increasing 0-indexed integer arrays nums1\u200b\u200b\u200b\u200b\u200b\u200b and nums2\u200b\u200b\u200b\u200b\u200b\u200b.\n A 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\u200b\u200b\u200b\u200b.\n Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.\n An array arr is non-increasing if arr[i-1] >= arr[i] for every 1 <= i < arr.length.\n Example 1:\n Input: nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]\n Output: 2\n Explanation: The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).\n The maximum distance is 2 with pair (2,4).\n Example 2:\n Input: nums1 = [2,2,2], nums2 = [10,10,1]\n Output: 1\n Explanation: The valid pairs are (0,0), (0,1), and (1,1).\n The maximum distance is 1 with pair (0,1).\n Example 3:\n Input: nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]\n Output: 2\n Explanation: The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).\n The maximum distance is 2 with pair (2,4).\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1856, - "title": "Maximum Subarray Min-Product", - "question": "class Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n \"\"\"\n The min-product of an array is equal to the minimum value in the array multiplied by the array's sum.\n For example, the array [3,2,5] (minimum value is 2) has a min-product of 2 * (3+2+5) = 2 * 10 = 20.\n Given 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.\n Note 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.\n A subarray is a contiguous part of an array.\n Example 1:\n Input: nums = [1,2,3,2]\n Output: 14\n Explanation: The maximum min-product is achieved with the subarray [2,3,2] (minimum value is 2).\n 2 * (2+3+2) = 2 * 7 = 14.\n Example 2:\n Input: nums = [2,3,3,1,2]\n Output: 18\n Explanation: The maximum min-product is achieved with the subarray [3,3] (minimum value is 3).\n 3 * (3+3) = 3 * 6 = 18.\n Example 3:\n Input: nums = [3,1,5,6,4,2]\n Output: 60\n Explanation: The maximum min-product is achieved with the subarray [5,6,4] (minimum value is 4).\n 4 * (5+6+4) = 4 * 15 = 60.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1857, - "title": "Largest Color Value in a Directed Graph", - "question": "class Solution:\r\n def largestPathValue(self, colors: str, edges: List[List[int]]) -> int:\n \"\"\"\n There is a directed graph of n colored nodes and m edges. The nodes are numbered from 0 to n - 1.\r\n You are given a string colors where colors[i] is a lowercase English letter representing the color of the ith node in this graph (0-indexed). You are also given a 2D array edges where edges[j] = [aj, bj] indicates that there is a directed edge from node aj to node bj.\r\n A valid path in the graph is a sequence of nodes x1 -> x2 -> x3 -> ... -> xk such that there is a directed edge from xi to xi+1 for every 1 <= i < k. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path.\r\n Return the largest color value of any valid path in the given graph, or -1 if the graph contains a cycle.\r\n Example 1:\r\n Input: colors = \"abaca\", edges = [[0,1],[0,2],[2,3],[3,4]]\r\n Output: 3\r\n Explanation: The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored \"a\" (red in the above image).\r\n Example 2:\r\n Input: colors = \"a\", edges = [[0,0]]\r\n Output: -1\r\n Explanation: There is a cycle from 0 to 0.\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1876, - "title": "Substrings of Size Three with Distinct Characters", - "question": "class Solution:\n def countGoodSubstrings(self, s: str) -> int:\n \"\"\"\n A string is good if there are no repeated characters.\n Given a string s\u200b\u200b\u200b\u200b\u200b, return the number of good substrings of length three in s\u200b\u200b\u200b\u200b\u200b\u200b.\n Note that if there are multiple occurrences of the same substring, every occurrence should be counted.\n A substring is a contiguous sequence of characters in a string.\n Example 1:\n Input: s = \"xyzzaz\"\n Output: 1\n Explanation: There are 4 substrings of size 3: \"xyz\", \"yzz\", \"zza\", and \"zaz\". \n The only good substring of length 3 is \"xyz\".\n Example 2:\n Input: s = \"aababcabc\"\n Output: 4\n Explanation: There are 7 substrings of size 3: \"aab\", \"aba\", \"bab\", \"abc\", \"bca\", \"cab\", and \"abc\".\n The good substrings are \"abc\", \"bca\", \"cab\", and \"abc\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1877, - "title": "Minimize Maximum Pair Sum in Array", - "question": "class Solution:\n def minPairSum(self, nums: List[int]) -> int:\n \"\"\"\n 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.\r\n For 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.\r\n Given an array nums of even length n, pair up the elements of nums into n / 2 pairs such that:\r\n Each element of nums is in exactly one pair, and\r\n The maximum pair sum is minimized.\r\n Return the minimized maximum pair sum after optimally pairing up the elements.\r\n Example 1:\r\n Input: nums = [3,5,2,3]\r\n Output: 7\r\n Explanation: The elements can be paired up into pairs (3,3) and (5,2).\r\n The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.\r\n Example 2:\r\n Input: nums = [3,5,4,2,4,6]\r\n Output: 8\r\n Explanation: The elements can be paired up into pairs (3,5), (4,4), and (6,2).\r\n The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1879, - "title": "Minimum XOR Sum of Two Arrays", - "question": "class Solution:\n def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:\n \"\"\"\n You are given two integer arrays nums1 and nums2 of length n.\n The 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).\n For 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.\n Rearrange the elements of nums2 such that the resulting XOR sum is minimized.\n Return the XOR sum after the rearrangement.\n Example 1:\n Input: nums1 = [1,2], nums2 = [2,3]\n Output: 2\n Explanation: Rearrange nums2 so that it becomes [3,2].\n The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.\n Example 2:\n Input: nums1 = [1,0,3], nums2 = [5,3,4]\n Output: 8\n Explanation: Rearrange nums2 so that it becomes [5,4,3]. \n The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1878, - "title": "Get Biggest Three Rhombus Sums in a Grid", - "question": "class Solution:\n def getBiggestThree(self, grid: List[List[int]]) -> List[int]:\n \"\"\"\n You are given an m x n integer matrix grid\u200b\u200b\u200b.\n A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid\u200b\u200b\u200b. 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:\n Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.\n Return 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:\n Input: 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]]\n Output: [228,216,211]\n Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n - Blue: 20 + 3 + 200 + 5 = 228\n - Red: 200 + 2 + 10 + 4 = 216\n - Green: 5 + 200 + 4 + 2 = 211\n Example 2:\n Input: grid = [[1,2,3],[4,5,6],[7,8,9]]\n Output: [20,9,8]\n Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.\n - Blue: 4 + 2 + 6 + 8 = 20\n - Red: 9 (area 0 rhombus in the bottom right corner)\n - Green: 8 (area 0 rhombus in the bottom middle)\n Example 3:\n Input: grid = [[7,7,7]]\n Output: [7]\n Explanation: All three possible rhombus sums are the same, so return [7].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1863, - "title": "Sum of All Subset XOR Totals", - "question": "class Solution:\n def subsetXORSum(self, nums: List[int]) -> int:\n \"\"\"\n The XOR total of an array is defined as the bitwise XOR of all its elements, or 0 if the array is empty.\n For example, the XOR total of the array [2,5,6] is 2 XOR 5 XOR 6 = 1.\n Given an array nums, return the sum of all XOR totals for every subset of nums. \n Note: Subsets with the same elements should be counted multiple times.\n An 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:\n Input: nums = [1,3]\n Output: 6\n Explanation: 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.\n 0 + 1 + 3 + 2 = 6\n Example 2:\n Input: nums = [5,1,6]\n Output: 28\n Explanation: 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.\n 0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28\n Example 3:\n Input: nums = [3,4,5,6,7,8]\n Output: 480\n Explanation: The sum of all XOR totals for every subset is 480.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1864, - "title": "Minimum Number of Swaps to Make the Binary String Alternating", - "question": "class Solution:\n def minSwaps(self, s: str) -> int:\n \"\"\"\n Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible.\n The 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.\n Any two characters may be swapped, even if they are not adjacent.\n Example 1:\n Input: s = \"111000\"\n Output: 1\n Explanation: Swap positions 1 and 4: \"111000\" -> \"101010\"\n The string is now alternating.\n Example 2:\n Input: s = \"010\"\n Output: 0\n Explanation: The string is already alternating, no swaps are needed.\n Example 3:\n Input: s = \"1110\"\n Output: -1\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1865, - "title": "Finding Pairs With a Certain Sum", - "question": "class FindSumPairs:\n def __init__(self, nums1: List[int], nums2: List[int]):\n def add(self, index: int, val: int) -> None:\n def count(self, tot: int) -> int:\n \"\"\"\n You are given two integer arrays nums1 and nums2. You are tasked to implement a data structure that supports queries of two types:\n Add a positive integer to an element of a given index in the array nums2.\n Count the number of pairs (i, j) such that nums1[i] + nums2[j] equals a given value (0 <= i < nums1.length and 0 <= j < nums2.length).\n Implement the FindSumPairs class:\n FindSumPairs(int[] nums1, int[] nums2) Initializes the FindSumPairs object with two integer arrays nums1 and nums2.\n void add(int index, int val) Adds val to nums2[index], i.e., apply nums2[index] += val.\n int count(int tot) Returns the number of pairs (i, j) such that nums1[i] + nums2[j] == tot.\n Example 1:\n Input\n [\"FindSumPairs\", \"count\", \"add\", \"count\", \"count\", \"add\", \"add\", \"count\"]\n [[[1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]], [7], [3, 2], [8], [4], [0, 1], [1, 1], [7]]\n Output\n [null, 8, null, 2, 1, null, null, 11]\n Explanation\n FindSumPairs findSumPairs = new FindSumPairs([1, 1, 2, 2, 2, 3], [1, 4, 5, 2, 5, 4]);\n findSumPairs.count(7); // return 8; pairs (2,2), (3,2), (4,2), (2,4), (3,4), (4,4) make 2 + 5 and pairs (5,1), (5,5) make 3 + 4\n findSumPairs.add(3, 2); // now nums2 = [1,4,5,4,5,4]\n findSumPairs.count(8); // return 2; pairs (5,2), (5,4) make 3 + 5\n findSumPairs.count(4); // return 1; pair (5,0) makes 3 + 1\n findSumPairs.add(0, 1); // now nums2 = [2,4,5,4,5,4]\n findSumPairs.add(1, 1); // now nums2 = [2,5,5,4,5,4]\n findSumPairs.count(7); // return 11; pairs (2,1), (2,2), (2,4), (3,1), (3,2), (3,4), (4,1), (4,2), (4,4) make 2 + 5 and pairs (5,3), (5,5) make 3 + 4\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1866, - "title": "Number of Ways to Rearrange Sticks With K Sticks Visible", - "question": "class Solution:\n def rearrangeSticks(self, n: int, k: int) -> int:\n \"\"\"\n 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.\n For 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.\n Given n and k, return the number of such arrangements. Since the answer may be large, return it modulo 109 + 7.\n Example 1:\n Input: n = 3, k = 2\n Output: 3\n Explanation: [1,3,2], [2,3,1], and [2,1,3] are the only arrangements such that exactly 2 sticks are visible.\n The visible sticks are underlined.\n Example 2:\n Input: n = 5, k = 5\n Output: 1\n Explanation: [1,2,3,4,5] is the only arrangement such that all 5 sticks are visible.\n The visible sticks are underlined.\n Example 3:\n Input: n = 20, k = 11\n Output: 647427950\n Explanation: There are 647427950 (mod 109 + 7) ways to rearrange the sticks such that exactly 11 sticks are visible.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1869, - "title": "Longer Contiguous Segments of Ones than Zeros", - "question": "class Solution:\n def checkZeroOnes(self, s: str) -> bool:\n \"\"\"\n 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.\n For example, in s = \"110100010\" the longest continuous segment of 1s has length 2, and the longest continuous segment of 0s has length 3.\n Note 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:\n Input: s = \"1101\"\n Output: true\n Explanation:\n The longest contiguous segment of 1s has length 2: \"1101\"\n The longest contiguous segment of 0s has length 1: \"1101\"\n The segment of 1s is longer, so return true.\n Example 2:\n Input: s = \"111000\"\n Output: false\n Explanation:\n The longest contiguous segment of 1s has length 3: \"111000\"\n The longest contiguous segment of 0s has length 3: \"111000\"\n The segment of 1s is not longer, so return false.\n Example 3:\n Input: s = \"110100010\"\n Output: false\n Explanation:\n The longest contiguous segment of 1s has length 2: \"110100010\"\n The longest contiguous segment of 0s has length 3: \"110100010\"\n The segment of 1s is not longer, so return false.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1870, - "title": "Minimum Speed to Arrive on Time", - "question": "class Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n \"\"\"\n 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.\n Each train can only depart at an integer hour, so you may need to wait in between each train ride.\n For 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.\n Return 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.\n Tests 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:\n Input: dist = [1,3,2], hour = 6\n Output: 1\n Explanation: At speed 1:\n - The first train ride takes 1/1 = 1 hour.\n - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.\n - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.\n - You will arrive at exactly the 6 hour mark.\n Example 2:\n Input: dist = [1,3,2], hour = 2.7\n Output: 3\n Explanation: At speed 3:\n - The first train ride takes 1/3 = 0.33333 hours.\n - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.\n - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.\n - You will arrive at the 2.66667 hour mark.\n Example 3:\n Input: dist = [1,3,2], hour = 1.9\n Output: -1\n Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1871, - "title": "Jump Game VII", - "question": "class Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n \"\"\"\n 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:\n i + minJump <= j <= min(i + maxJump, s.length - 1), and\n s[j] == '0'.\n Return true if you can reach index s.length - 1 in s, or false otherwise.\n Example 1:\n Input: s = \"011010\", minJump = 2, maxJump = 3\n Output: true\n Explanation:\n In the first step, move from index 0 to index 3. \n In the second step, move from index 3 to index 5.\n Example 2:\n Input: s = \"01101110\", minJump = 2, maxJump = 3\n Output: false\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1872, - "title": "Stone Game VIII", - "question": "class Solution:\n def stoneGameVIII(self, stones: List[int]) -> int:\n \"\"\"\n Alice and Bob take turns playing a game, with Alice starting first.\r\n There 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:\r\n Choose an integer x > 1, and remove the leftmost x stones from the row.\r\n Add the sum of the removed stones' values to the player's score.\r\n Place a new stone, whose value is equal to that sum, on the left side of the row.\r\n The game stops when only one stone is left in the row.\r\n The 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.\r\n Given 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.\r\n Example 1:\r\n Input: stones = [-1,2,-3,4,-5]\r\n Output: 5\r\n Explanation:\r\n - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of\r\n value 2 on the left. stones = [2,-5].\r\n - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on\r\n the left. stones = [-3].\r\n The difference between their scores is 2 - (-3) = 5.\r\n Example 2:\r\n Input: stones = [7,-6,5,10,5,-2,-6]\r\n Output: 13\r\n Explanation:\r\n - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a\r\n stone of value 13 on the left. stones = [13].\r\n The difference between their scores is 13 - 0 = 13.\r\n Example 3:\r\n Input: stones = [-10,-12]\r\n Output: -22\r\n Explanation:\r\n - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her\r\n score and places a stone of value -22 on the left. stones = [-22].\r\n The difference between their scores is (-22) - 0 = -22.\r\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1893, - "title": "Check if All the Integers in a Range Are Covered", - "question": "class Solution:\n def isCovered(self, ranges: List[List[int]], left: int, right: int) -> bool:\n \"\"\"\n 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.\n Return true if each integer in the inclusive range [left, right] is covered by at least one interval in ranges. Return false otherwise.\n An integer x is covered by an interval ranges[i] = [starti, endi] if starti <= x <= endi.\n Example 1:\n Input: ranges = [[1,2],[3,4],[5,6]], left = 2, right = 5\n Output: true\n Explanation: Every integer between 2 and 5 is covered:\n - 2 is covered by the first range.\n - 3 and 4 are covered by the second range.\n - 5 is covered by the third range.\n Example 2:\n Input: ranges = [[1,10],[10,20]], left = 21, right = 21\n Output: false\n Explanation: 21 is not covered by any range.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1894, - "title": "Find the Student that Will Replace the Chalk", - "question": "class Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n \"\"\"\n 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.\n You 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.\n Return the index of the student that will replace the chalk pieces.\n Example 1:\n Input: chalk = [5,1,5], k = 22\n Output: 0\n Explanation: 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.\n Student number 0 does not have enough chalk, so they will have to replace it.\n Example 2:\n Input: chalk = [3,4,1,2], k = 25\n Output: 1\n Explanation: 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.\n Student number 1 does not have enough chalk, so they will have to replace it.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1896, - "title": "Minimum Cost to Change the Final Value of Expression", - "question": "class Solution:\n def minOperationsToFlip(self, expression: str) -> int:\n \"\"\"\n You are given a valid boolean expression as a string expression consisting of the characters '1','0','&' (bitwise AND operator),'|' (bitwise OR operator),'(', and ')'.\n For example, \"()1|1\" and \"(1)&()\" are not valid while \"1\", \"(((1))|(0))\", and \"1|(0&(1))\" are valid expressions.\n Return the minimum cost to change the final value of the expression.\n For example, if expression = \"1|1|(0&0)&1\", its value is 1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1. We want to apply operations so that the new expression evaluates to 0.\n The 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:\n Turn a '1' into a '0'.\n Turn a '0' into a '1'.\n Turn a '&' into a '|'.\n Turn a '|' into a '&'.\n Note: '&' does not take precedence over '|' in the order of calculation. Evaluate parentheses first, then in left-to-right order.\n Example 1:\n Input: expression = \"1&(0|1)\"\n Output: 1\n Explanation: We can turn \"1&(0|1)\" into \"1&(0&1)\" by changing the '|' to a '&' using 1 operation.\n The new expression evaluates to 0. \n Example 2:\n Input: expression = \"(0&0)&(0&0&0)\"\n Output: 3\n Explanation: We can turn \"(0&0)&(0&0&0)\" into \"(0|1)|(0&0&0)\" using 3 operations.\n The new expression evaluates to 1.\n Example 3:\n Input: expression = \"(0|(1|0&1))\"\n Output: 1\n Explanation: We can turn \"(0|(1|0&1))\" into \"(0|(0|0&1))\" using 1 operation.\n The new expression evaluates to 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1880, - "title": "Check if Word Equals Summation of Two Words", - "question": "class Solution:\n def isSumEqual(self, firstWord: str, secondWord: str, targetWord: str) -> bool:\n \"\"\"\n The letter value of a letter is its position in the alphabet starting from 0 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, etc.).\n The 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.\n For example, if s = \"acb\", we concatenate each letter's letter value, resulting in \"021\". After converting it, we get 21.\n You are given three strings firstWord, secondWord, and targetWord, each consisting of lowercase English letters 'a' through 'j' inclusive.\n Return true if the summation of the numerical values of firstWord and secondWord equals the numerical value of targetWord, or false otherwise.\n Example 1:\n Input: firstWord = \"acb\", secondWord = \"cba\", targetWord = \"cdb\"\n Output: true\n Explanation:\n The numerical value of firstWord is \"acb\" -> \"021\" -> 21.\n The numerical value of secondWord is \"cba\" -> \"210\" -> 210.\n The numerical value of targetWord is \"cdb\" -> \"231\" -> 231.\n We return true because 21 + 210 == 231.\n Example 2:\n Input: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aab\"\n Output: false\n Explanation: \n The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\n The numerical value of secondWord is \"a\" -> \"0\" -> 0.\n The numerical value of targetWord is \"aab\" -> \"001\" -> 1.\n We return false because 0 + 0 != 1.\n Example 3:\n Input: firstWord = \"aaa\", secondWord = \"a\", targetWord = \"aaaa\"\n Output: true\n Explanation: \n The numerical value of firstWord is \"aaa\" -> \"000\" -> 0.\n The numerical value of secondWord is \"a\" -> \"0\" -> 0.\n The numerical value of targetWord is \"aaaa\" -> \"0000\" -> 0.\n We return true because 0 + 0 == 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1881, - "title": "Maximum Value after Insertion", - "question": "class Solution:\n def maxValue(self, n: str, x: int) -> str:\n \"\"\"\n You are given a very large integer n, represented as a string,\u200b\u200b\u200b\u200b\u200b\u200b 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.\n You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n\u200b\u200b\u200b\u200b\u200b\u200b. You cannot insert x to the left of the negative sign.\n For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.\n If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.\n Return a string representing the maximum value of n\u200b\u200b\u200b\u200b\u200b\u200b after the insertion.\n Example 1:\n Input: n = \"99\", x = 9\n Output: \"999\"\n Explanation: The result is the same regardless of where you insert 9.\n Example 2:\n Input: n = \"-13\", x = 2\n Output: \"-123\"\n Explanation: You can make n one of {-213, -123, -132}, and the largest of those three is -123.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1882, - "title": "Process Tasks Using Servers", - "question": "class Solution:\n def assignTasks(self, servers: List[int], tasks: List[int]) -> List[int]:\n \"\"\"\n You are given two 0-indexed integer arrays servers and tasks of lengths n\u200b\u200b\u200b\u200b\u200b\u200b and m\u200b\u200b\u200b\u200b\u200b\u200b respectively. servers[i] is the weight of the i\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b server, and tasks[j] is the time needed to process the j\u200b\u200b\u200b\u200b\u200b\u200bth\u200b\u200b\u200b\u200b task in seconds.\n Tasks are assigned to the servers using a task queue. Initially, all servers are free, and the queue is empty.\n At 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.\n If 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.\n A server that is assigned task j at second t will be free again at second t + tasks[j].\n Build an array ans\u200b\u200b\u200b\u200b of length m, where ans[j] is the index of the server the j\u200b\u200b\u200b\u200b\u200b\u200bth task will be assigned to.\n Return the array ans\u200b\u200b\u200b\u200b.\n Example 1:\n Input: servers = [3,3,2], tasks = [1,2,3,2,1,2]\n Output: [2,2,0,2,1,2]\n Explanation: Events in chronological order go as follows:\n - At second 0, task 0 is added and processed using server 2 until second 1.\n - At second 1, server 2 becomes free. Task 1 is added and processed using server 2 until second 3.\n - At second 2, task 2 is added and processed using server 0 until second 5.\n - At second 3, server 2 becomes free. Task 3 is added and processed using server 2 until second 5.\n - At second 4, task 4 is added and processed using server 1 until second 5.\n - At second 5, all servers become free. Task 5 is added and processed using server 2 until second 7.\n Example 2:\n Input: servers = [5,1,4,3,2], tasks = [2,1,2,4,5,2,1]\n Output: [1,4,1,4,1,3,2]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1883, - "title": "Minimum Skips to Arrive at Meeting On Time", - "question": "class Solution:\n def minSkips(self, dist: List[int], speed: int, hoursBefore: int) -> int:\n \"\"\"\n 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.\n After 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.\n For 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.\n However, 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.\n For 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.\n Return the minimum number of skips required to arrive at the meeting on time, or -1 if it is impossible.\n Example 1:\n Input: dist = [1,3,2], speed = 4, hoursBefore = 2\n Output: 1\n Explanation:\n Without skipping any rests, you will arrive in (1/4 + 3/4) + (3/4 + 1/4) + (2/4) = 2.5 hours.\n You can skip the first rest to arrive in ((1/4 + 0) + (3/4 + 0)) + (2/4) = 1.5 hours.\n Note that the second rest is shortened because you finish traveling the second road at an integer hour due to skipping the first rest.\n Example 2:\n Input: dist = [7,3,5,5], speed = 2, hoursBefore = 10\n Output: 2\n Explanation:\n Without skipping any rests, you will arrive in (7/2 + 1/2) + (3/2 + 1/2) + (5/2 + 1/2) + (5/2) = 11.5 hours.\n You can skip the first and third rest to arrive in ((7/2 + 0) + (3/2 + 0)) + ((5/2 + 0) + (5/2)) = 10 hours.\n Example 3:\n Input: dist = [7,3,5,5], speed = 1, hoursBefore = 10\n Output: -1\n Explanation: It is impossible to arrive at the meeting on time even if you skip all the rests.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1886, - "title": "Determine Whether Matrix Can Be Obtained By Rotation", - "question": "class Solution:\n def findRotation(self, mat: List[List[int]], target: List[List[int]]) -> bool:\n \"\"\"\n 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:\n Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]]\n Output: true\n Explanation: We can rotate mat 90 degrees clockwise to make mat equal target.\n Example 2:\n Input: mat = [[0,1],[1,1]], target = [[1,0],[0,1]]\n Output: false\n Explanation: It is impossible to make mat equal to target by rotating mat.\n Example 3:\n Input: mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]\n Output: true\n Explanation: We can rotate mat 90 degrees clockwise two times to make mat equal target.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1887, - "title": "Reduction Operations to Make the Array Elements Equal", - "question": "class Solution:\n def reductionOperations(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:\n Find 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.\n Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.\n Reduce nums[i] to nextLargest.\n Return the number of operations to make all elements in nums equal.\n Example 1:\n Input: nums = [5,1,3]\n Output: 3\n Explanation: It takes 3 operations to make all elements in nums equal:\n 1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3].\n 2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3].\n 3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].\n Example 2:\n Input: nums = [1,1,1]\n Output: 0\n Explanation: All elements in nums are already equal.\n Example 3:\n Input: nums = [1,1,2,2,3]\n Output: 4\n Explanation: It takes 4 operations to make all elements in nums equal:\n 1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2].\n 2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2].\n 3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2].\n 4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1888, - "title": "Minimum Number of Flips to Make the Binary String Alternating", - "question": "class Solution:\n def minFlips(self, s: str) -> int:\n \"\"\"\n You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence:\n Type-1: Remove the character at the start of the string s and append it to the end of the string.\n Type-2: Pick any character in s and flip its value, i.e., if its value is '0' it becomes '1' and vice-versa.\n Return the minimum number of type-2 operations you need to perform such that s becomes alternating.\n The string is called alternating if no two adjacent characters are equal.\n For example, the strings \"010\" and \"1010\" are alternating, while the string \"0100\" is not.\n Example 1:\n Input: s = \"111000\"\n Output: 2\n Explanation: Use the first operation two times to make s = \"100011\".\n Then, use the second operation on the third and sixth elements to make s = \"101010\".\n Example 2:\n Input: s = \"010\"\n Output: 0\n Explanation: The string is already alternating.\n Example 3:\n Input: s = \"1110\"\n Output: 1\n Explanation: Use the second operation on the second element to make s = \"1010\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1889, - "title": "Minimum Space Wasted From Packaging", - "question": "class Solution:\n def minWastedSpace(self, packages: List[int], boxes: List[List[int]]) -> int:\n \"\"\"\n 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.\n The 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.\n You 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.\n For 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.\n Return 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:\n Input: packages = [2,3,5], boxes = [[4,8],[2,8]]\n Output: 6\n Explanation: It is optimal to choose the first supplier, using two size-4 boxes and one size-8 box.\n The total waste is (4-2) + (4-3) + (8-5) = 6.\n Example 2:\n Input: packages = [2,3,5], boxes = [[1,4],[2,3],[3,4]]\n Output: -1\n Explanation: There is no box that the package of size 5 can fit in.\n Example 3:\n Input: packages = [3,5,8,10,11,12], boxes = [[12],[11,9],[10,5,14]]\n Output: 9\n Explanation: It is optimal to choose the third supplier, using two size-5 boxes, two size-10 boxes, and two size-14 boxes.\n The total waste is (5-3) + (5-5) + (10-8) + (10-10) + (14-11) + (14-12) = 9.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1909, - "title": "Remove One Element to Make the Array Strictly Increasing", - "question": "class Solution:\n def canBeIncreasing(self, nums: List[int]) -> bool:\n \"\"\"\n 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.\n The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).\n Example 1:\n Input: nums = [1,2,10,5,7]\n Output: true\n Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7].\n [1,2,5,7] is strictly increasing, so return true.\n Example 2:\n Input: nums = [2,3,1,2]\n Output: false\n Explanation:\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.\n No resulting array is strictly increasing, so return false.\n Example 3:\n Input: nums = [1,1,1]\n Output: false\n Explanation: The result of removing any element is [1,1].\n [1,1] is not strictly increasing, so return false.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1910, - "title": "Remove All Occurrences of a Substring", - "question": "class Solution:\n def removeOccurrences(self, s: str, part: str) -> str:\n \"\"\"\n Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:\n Find the leftmost occurrence of the substring part and remove it from s.\n Return s after removing all occurrences of part.\n A substring is a contiguous sequence of characters in a string.\n Example 1:\n Input: s = \"daabcbaabcbc\", part = \"abc\"\n Output: \"dab\"\n Explanation: 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\".\n Now s has no occurrences of \"abc\".\n Example 2:\n Input: s = \"axxxxyyyyb\", part = \"xy\"\n Output: \"ab\"\n Explanation: 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\".\n Now s has no occurrences of \"xy\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1911, - "title": "Maximum Alternating Subsequence Sum", - "question": "class Solution:\r\n def maxAlternatingSum(self, nums: List[int]) -> int:\n \"\"\"\n 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.\r\n For example, the alternating sum of [4,2,5,3] is (4 + 5) - (2 + 3) = 4.\r\n Given an array nums, return the maximum alternating sum of any subsequence of nums (after reindexing the elements of the subsequence).\r\n A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.\r\n Example 1:\r\n Input: nums = [4,2,5,3]\r\n Output: 7\r\n Explanation: It is optimal to choose the subsequence [4,2,5] with alternating sum (4 + 5) - 2 = 7.\r\n Example 2:\r\n Input: nums = [5,6,7,8]\r\n Output: 8\r\n Explanation: It is optimal to choose the subsequence [8] with alternating sum 8.\r\n Example 3:\r\n Input: nums = [6,2,1,2,4,5]\r\n Output: 10\r\n Explanation: It is optimal to choose the subsequence [6,1,5] with alternating sum (6 + 5) - 1 = 10.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1912, - "title": "Design Movie Rental System", - "question": "class MovieRentingSystem:\n def __init__(self, n: int, entries: List[List[int]]):\n def search(self, movie: int) -> List[int]:\n def rent(self, shop: int, movie: int) -> None:\n def drop(self, shop: int, movie: int) -> None:\n def report(self) -> List[List[int]]:\n \"\"\"\n You have a movie renting company consisting of n shops. You want to implement a renting system that supports searching for, booking, and returning movies. The system should also support generating a report of the currently rented movies.\n Each movie is given as a 2D integer array entries where entries[i] = [shopi, moviei, pricei] indicates that there is a copy of movie moviei at shop shopi with a rental price of pricei. Each shop carries at most one copy of a movie moviei.\n The system should support the following functions:\n Search: Finds the cheapest 5 shops that have an unrented copy of a given movie. The shops should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopi should appear first. If there are less than 5 matching shops, then all of them should be returned. If no shop has an unrented copy, then an empty list should be returned.\n Rent: Rents an unrented copy of a given movie from a given shop.\n Drop: Drops off a previously rented copy of a given movie at a given shop.\n Report: Returns the cheapest 5 rented movies (possibly of the same movie ID) as a 2D list res where res[j] = [shopj, moviej] describes that the jth cheapest rented movie moviej was rented from the shop shopj. The movies in res should be sorted by price in ascending order, and in case of a tie, the one with the smaller shopj should appear first, and if there is still tie, the one with the smaller moviej should appear first. If there are fewer than 5 rented movies, then all of them should be returned. If no movies are currently being rented, then an empty list should be returned.\n Implement the MovieRentingSystem class:\n MovieRentingSystem(int n, int[][] entries) Initializes the MovieRentingSystem object with n shops and the movies in entries.\n List search(int movie) Returns a list of shops that have an unrented copy of the given movie as described above.\n void rent(int shop, int movie) Rents the given movie from the given shop.\n void drop(int shop, int movie) Drops off a previously rented movie at the given shop.\n List> report() Returns a list of cheapest rented movies as described above.\n Note: The test cases will be generated such that rent will only be called if the shop has an unrented copy of the movie, and drop will only be called if the shop had previously rented out the movie.\n Example 1:\n Input\n [\"MovieRentingSystem\", \"search\", \"rent\", \"rent\", \"report\", \"drop\", \"search\"]\n [[3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]], [1], [0, 1], [1, 2], [], [1, 2], [2]]\n Output\n [null, [1, 0, 2], null, null, [[0, 1], [1, 2]], null, [0, 1]]\n Explanation\n MovieRentingSystem movieRentingSystem = new MovieRentingSystem(3, [[0, 1, 5], [0, 2, 6], [0, 3, 7], [1, 1, 4], [1, 2, 7], [2, 1, 5]]);\n movieRentingSystem.search(1); // return [1, 0, 2], Movies of ID 1 are unrented at shops 1, 0, and 2. Shop 1 is cheapest; shop 0 and 2 are the same price, so order by shop number.\n movieRentingSystem.rent(0, 1); // Rent movie 1 from shop 0. Unrented movies at shop 0 are now [2,3].\n movieRentingSystem.rent(1, 2); // Rent movie 2 from shop 1. Unrented movies at shop 1 are now [1].\n movieRentingSystem.report(); // return [[0, 1], [1, 2]]. Movie 1 from shop 0 is cheapest, followed by movie 2 from shop 1.\n movieRentingSystem.drop(1, 2); // Drop off movie 2 at shop 1. Unrented movies at shop 1 are now [1,2].\n movieRentingSystem.search(2); // return [0, 1]. Movies of ID 2 are unrented at shops 0 and 1. Shop 0 is cheapest, followed by shop 1.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1897, - "title": "Redistribute Characters to Make All Strings Equal", - "question": "class Solution:\n def makeEqual(self, words: List[str]) -> bool:\n \"\"\"\n You are given an array of strings words (0-indexed).\n In 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].\n Return true if you can make every string in words equal using any number of operations, and false otherwise.\n Example 1:\n Input: words = [\"abc\",\"aabc\",\"bc\"]\n Output: true\n Explanation: Move the first 'a' in words[1] to the front of words[2],\n to make words[1] = \"abc\" and words[2] = \"abc\".\n All the strings are now equal to \"abc\", so return true.\n Example 2:\n Input: words = [\"ab\",\"a\"]\n Output: false\n Explanation: It is impossible to make all the strings equal using the operation.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1899, - "title": "Merge Triplets to Form Target Triplet", - "question": "class Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n \"\"\"\n A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.\n To obtain target, you may apply the following operation on triplets any number of times (possibly zero):\n Choose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].\n For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].\n Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.\n Example 1:\n Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]\n Output: true\n Explanation: Perform the following operations:\n - Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]\n The target triplet [2,7,5] is now an element of triplets.\n Example 2:\n Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]\n Output: false\n Explanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.\n Example 3:\n Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]\n Output: true\n Explanation: Perform the following operations:\n - Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].\n - Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].\n The target triplet [5,5,5] is now an element of triplets.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1898, - "title": "Maximum Number of Removable Characters", - "question": "class Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n \"\"\"\n 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).\n You 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.\n Return the maximum k you can choose such that p is still a subsequence of s after the removals.\n A 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:\n Input: s = \"abcacb\", p = \"ab\", removable = [3,1,0]\n Output: 2\n Explanation: After removing the characters at indices 3 and 1, \"abcacb\" becomes \"accb\".\n \"ab\" is a subsequence of \"accb\".\n If we remove the characters at indices 3, 1, and 0, \"abcacb\" becomes \"ccb\", and \"ab\" is no longer a subsequence.\n Hence, the maximum k is 2.\n Example 2:\n Input: s = \"abcbddddd\", p = \"abcd\", removable = [3,2,1,4,5,6]\n Output: 1\n Explanation: After removing the character at index 3, \"abcbddddd\" becomes \"abcddddd\".\n \"abcd\" is a subsequence of \"abcddddd\".\n Example 3:\n Input: s = \"abcab\", p = \"abc\", removable = [0,1,2,3,4]\n Output: 0\n Explanation: If you remove the first index in the array removable, \"abc\" is no longer a subsequence.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1900, - "title": "The Earliest and Latest Rounds Where Players Compete", - "question": "class Solution:\n def earliestAndLatest(self, n: int, firstPlayer: int, secondPlayer: int) -> List[int]:\n \"\"\"\n There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.).\n The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round.\n For example, if the row consists of players 1, 2, 4, 6, 7\n Player 1 competes against player 7.\n Player 2 competes against player 6.\n Player 4 automatically advances to the next round.\n After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order).\n The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round.\n Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.\n Example 1:\n Input: n = 11, firstPlayer = 2, secondPlayer = 4\n Output: [3,4]\n Explanation:\n One possible scenario which leads to the earliest round number:\n First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\n Second round: 2, 3, 4, 5, 6, 11\n Third round: 2, 3, 4\n One possible scenario which leads to the latest round number:\n First round: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11\n Second round: 1, 2, 3, 4, 5, 6\n Third round: 1, 2, 4\n Fourth round: 2, 4\n Example 2:\n Input: n = 5, firstPlayer = 1, secondPlayer = 5\n Output: [1,1]\n Explanation: The players numbered 1 and 5 compete in the first round.\n There is no way to make them compete in any other round.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1884, - "title": "Egg Drop With 2 Eggs and N Floors", - "question": "class Solution:\n def twoEggDrop(self, n: int) -> int:\n \"\"\"\n You are given two identical eggs and you have access to a building with n floors labeled from 1 to n.\n You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break.\n In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.\n Return the minimum number of moves that you need to determine with certainty what the value of f is.\n Example 1:\n Input: n = 2\n Output: 2\n Explanation: We can drop the first egg from floor 1 and the second egg from floor 2.\n If the first egg breaks, we know that f = 0.\n If the second egg breaks but the first egg didn't, we know that f = 1.\n Otherwise, if both eggs survive, we know that f = 2.\n Example 2:\n Input: n = 100\n Output: 14\n Explanation: 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.\n Regardless of the outcome, it takes at most 14 drops to determine f.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1903, - "title": "Largest Odd Number in String", - "question": "class Solution:\n def largestOddNumber(self, num: str) -> str:\n \"\"\"\n 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.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: num = \"52\"\n Output: \"5\"\n Explanation: The only non-empty substrings are \"5\", \"2\", and \"52\". \"5\" is the only odd number.\n Example 2:\n Input: num = \"4206\"\n Output: \"\"\n Explanation: There are no odd numbers in \"4206\".\n Example 3:\n Input: num = \"35427\"\n Output: \"35427\"\n Explanation: \"35427\" is already an odd number.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1904, - "title": "The Number of Full Rounds You Have Played", - "question": "class Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n \"\"\"\n 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.\n For example, the second round starts at 00:15, the fourth round starts at 00:45, and the seventh round starts at 01:30.\n You are given two strings loginTime and logoutTime where:\n loginTime is the time you will login to the game, and\n logoutTime is the time you will logout from the game.\n If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime.\n Return the number of full chess rounds you have played in the tournament.\n Note: 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:\n Input: loginTime = \"09:31\", logoutTime = \"10:14\"\n Output: 1\n Explanation: You played one full round from 09:45 to 10:00.\n You did not play the full round from 09:30 to 09:45 because you logged in at 09:31 after it began.\n You did not play the full round from 10:00 to 10:15 because you logged out at 10:14 before it ended.\n Example 2:\n Input: loginTime = \"21:30\", logoutTime = \"03:00\"\n Output: 22\n Explanation: You played 10 full rounds from 21:30 to 00:00 and 12 full rounds from 00:00 to 03:00.\n 10 + 12 = 22.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1906, - "title": "Minimum Absolute Difference Queries", - "question": "class Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.\n You 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).\n Return an array ans where ans[i] is the answer to the ith query.\n A subarray is a contiguous sequence of elements in an array.\n The value of |x| is defined as:\n x if x >= 0.\n -x if x < 0.\n Example 1:\n Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]\n Output: [2,1,4,1]\n Explanation: The queries are processed as follows:\n - queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.\n - queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.\n - queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.\n - queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.\n Example 2:\n Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]\n Output: [-1,1,1,3]\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1905, - "title": "Count Sub Islands", - "question": "class Solution:\n def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n \"\"\"\n 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.\n An 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.\n Return the number of islands in grid2 that are considered sub-islands.\n Example 1:\n Input: 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]]\n Output: 3\n Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\n The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.\n Example 2:\n Input: 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]]\n Output: 2 \n Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.\n The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1925, - "title": "Count Square Sum Triples", - "question": "class Solution:\n def countTriples(self, n: int) -> int:\n \"\"\"\n A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.\n Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.\n Example 1:\n Input: n = 5\n Output: 2\n Explanation: The square triples are (3,4,5) and (4,3,5).\n Example 2:\n Input: n = 10\n Output: 4\n Explanation: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1926, - "title": "Nearest Exit from Entrance in Maze", - "question": "class Solution:\n def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:\n \"\"\"\n 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.\n In 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.\n Return 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:\n Input: maze = [[\"+\",\"+\",\".\",\"+\"],[\".\",\".\",\".\",\"+\"],[\"+\",\"+\",\"+\",\".\"]], entrance = [1,2]\n Output: 1\n Explanation: There are 3 exits in this maze at [1,0], [0,2], and [2,3].\n Initially, 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.\n It is impossible to reach [2,3] from the entrance.\n Thus, the nearest exit is [0,2], which is 1 step away.\n Example 2:\n Input: maze = [[\"+\",\"+\",\"+\"],[\".\",\".\",\".\"],[\"+\",\"+\",\"+\"]], entrance = [1,0]\n Output: 2\n Explanation: 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.\n Initially, you are at the entrance cell [1,0].\n - You can reach [1,2] by moving 2 steps right.\n Thus, the nearest exit is [1,2], which is 2 steps away.\n Example 3:\n Input: maze = [[\".\",\"+\"]], entrance = [0,0]\n Output: -1\n Explanation: There are no exits in this maze.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1927, - "title": "Sum Game", - "question": "class Solution:\n def sumGame(self, num: str) -> bool:\n \"\"\"\n Alice and Bob take turns playing a game, with Alice starting first.\n You 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:\n Choose an index i where num[i] == '?'.\n Replace num[i] with any digit between '0' and '9'.\n The game ends when there are no more '?' characters in num.\n For 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.\n For 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.\n Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.\n Example 1:\n Input: num = \"5023\"\n Output: false\n Explanation: There are no moves to be made.\n The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.\n Example 2:\n Input: num = \"25??\"\n Output: true\n Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.\n Example 3:\n Input: num = \"?3295???\"\n Output: false\n Explanation: 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\".\n Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1928, - "title": "Minimum Cost to Reach Destination in Time", - "question": "class Solution:\n def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int:\n \"\"\"\n 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.\n Each 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.\n In 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).\n Given 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:\n Input: 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]\n Output: 11\n Explanation: The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.\n Example 2:\n Input: 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]\n Output: 48\n Explanation: The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.\n You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.\n Example 3:\n Input: 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]\n Output: -1\n Explanation: There is no way to reach city 5 from city 0 within 25 minutes.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1913, - "title": "Maximum Product Difference Between Two Pairs", - "question": "class Solution:\r\n def maxProductDifference(self, nums: List[int]) -> int:\n \"\"\"\n The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).\r\n For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.\r\n Given 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.\r\n Return the maximum such product difference.\r\n Example 1:\r\n Input: nums = [5,6,2,7,4]\r\n Output: 34\r\n Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).\r\n The product difference is (6 * 7) - (2 * 4) = 34.\r\n Example 2:\r\n Input: nums = [4,2,5,9,7,4,8]\r\n Output: 64\r\n Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).\r\n The product difference is (9 * 8) - (2 * 4) = 64.\r\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1914, - "title": "Cyclically Rotating a Grid", - "question": "class Solution:\r\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n \"\"\"\n You are given an m x n integer matrix grid\u200b\u200b\u200b, where m and n are both even integers, and an integer k.\r\n The matrix is composed of several layers, which is shown in the below image, where each color is its own layer:\r\n A 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:\r\n Return the matrix after applying k cyclic rotations to it.\r\n Example 1:\r\n Input: grid = [[40,10],[30,20]], k = 1\r\n Output: [[10,20],[40,30]]\r\n Explanation: The figures above represent the grid at every state.\r\n Example 2:\r\n Input: grid = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], k = 2\r\n Output: [[3,4,8,12],[2,11,10,16],[1,7,6,15],[5,9,13,14]]\r\n Explanation: The figures above represent the grid at every state.\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1915, - "title": "Number of Wonderful Substrings", - "question": "class Solution:\r\n def wonderfulSubstrings(self, word: str) -> int:\n \"\"\"\n A wonderful string is a string where at most one letter appears an odd number of times.\r\n For example, \"ccjjc\" and \"abab\" are wonderful, but \"ab\" is not.\r\n Given 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.\r\n A substring is a contiguous sequence of characters in a string.\r\n Example 1:\r\n Input: word = \"aba\"\r\n Output: 4\r\n Explanation: The four wonderful substrings are underlined below:\r\n - \"aba\" -> \"a\"\r\n - \"aba\" -> \"b\"\r\n - \"aba\" -> \"a\"\r\n - \"aba\" -> \"aba\"\r\n Example 2:\r\n Input: word = \"aabb\"\r\n Output: 9\r\n Explanation: The nine wonderful substrings are underlined below:\r\n - \"aabb\" -> \"a\"\r\n - \"aabb\" -> \"aa\"\r\n - \"aabb\" -> \"aab\"\r\n - \"aabb\" -> \"aabb\"\r\n - \"aabb\" -> \"a\"\r\n - \"aabb\" -> \"abb\"\r\n - \"aabb\" -> \"b\"\r\n - \"aabb\" -> \"bb\"\r\n - \"aabb\" -> \"b\"\r\n Example 3:\r\n Input: word = \"he\"\r\n Output: 2\r\n Explanation: The two wonderful substrings are underlined below:\r\n - \"he\" -> \"h\"\r\n - \"he\" -> \"e\"\r\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1901, - "title": "Find a Peak Element II", - "question": "class Solution:\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n Given 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].\n You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell.\n You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.\n Example 1:\n Input: mat = [[1,4],[3,2]]\n Output: [0,1]\n Explanation: Both 3 and 4 are peak elements so [1,0] and [0,1] are both acceptable answers.\n Example 2:\n Input: mat = [[10,20,15],[21,30,14],[7,16,32]]\n Output: [1,1]\n Explanation: Both 30 and 32 are peak elements so [1,1] and [2,2] are both acceptable answers.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1920, - "title": "Build Array from Permutation", - "question": "class Solution:\n def buildArray(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).\n Example 1:\n Input: nums = [0,2,1,5,3,4]\n Output: [0,1,2,4,5,3]\n Explanation: The array ans is built as follows: \n ans = [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]\n Example 2:\n Input: nums = [5,0,1,2,3,4]\n Output: [4,5,0,1,2,3]\n Explanation: The array ans is built as follows:\n ans = [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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1921, - "title": "Eliminate Maximum Number of Monsters", - "question": "class Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n \"\"\"\n 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.\n The 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.\n You 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.\n You 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.\n Return 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:\n Input: dist = [1,3,4], speed = [1,1,1]\n Output: 3\n Explanation:\n In the beginning, the distances of the monsters are [1,3,4]. You eliminate the first monster.\n After a minute, the distances of the monsters are [X,2,3]. You eliminate the second monster.\n After a minute, the distances of the monsters are [X,X,2]. You eliminate the thrid monster.\n All 3 monsters can be eliminated.\n Example 2:\n Input: dist = [1,1,2,3], speed = [1,1,1,1]\n Output: 1\n Explanation:\n In the beginning, the distances of the monsters are [1,1,2,3]. You eliminate the first monster.\n After a minute, the distances of the monsters are [X,0,1,2], so you lose.\n You can only eliminate 1 monster.\n Example 3:\n Input: dist = [3,2,4], speed = [5,3,2]\n Output: 1\n Explanation:\n In the beginning, the distances of the monsters are [3,2,4]. You eliminate the first monster.\n After a minute, the distances of the monsters are [X,0,2], so you lose.\n You can only eliminate 1 monster.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1922, - "title": "Count Good Numbers", - "question": "class Solution:\n def countGoodNumbers(self, n: int) -> int:\n \"\"\"\n 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).\n For 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.\n Given 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.\n A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.\n Example 1:\n Input: n = 1\n Output: 5\n Explanation: The good numbers of length 1 are \"0\", \"2\", \"4\", \"6\", \"8\".\n Example 2:\n Input: n = 4\n Output: 400\n Example 3:\n Input: n = 50\n Output: 564908303\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1923, - "title": "Longest Common Subpath", - "question": "class Solution:\n def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int:\n \"\"\"\n There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities.\n There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively.\n Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all.\n A subpath of a path is a contiguous sequence of cities within that path.\n Example 1:\n Input: n = 5, paths = [[0,1,2,3,4],\n [2,3,4],\n [4,0,1,2,3]]\n Output: 2\n Explanation: The longest common subpath is [2,3].\n Example 2:\n Input: n = 3, paths = [[0],[1],[2]]\n Output: 0\n Explanation: There is no common subpath shared by the three paths.\n Example 3:\n Input: n = 5, paths = [[0,1,2,3,4],\n [4,3,2,1,0]]\n Output: 1\n Explanation: The possible longest common subpaths are [0], [1], [2], [3], and [4]. All have a length of 1.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1941, - "title": "Check if All Characters Have Equal Number of Occurrences", - "question": "class Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n \"\"\"\n Given a string s, return true if s is a good string, or false otherwise.\n A 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:\n Input: s = \"abacbc\"\n Output: true\n Explanation: The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.\n Example 2:\n Input: s = \"aaabb\"\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1942, - "title": "The Number of the Smallest Unoccupied Chair", - "question": "class Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n \"\"\"\n 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.\n For example, if chairs 0, 1, and 5 are occupied when a friend comes, they will sit on chair number 2.\n When 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.\n You 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.\n Return the chair number that the friend numbered targetFriend will sit on.\n Example 1:\n Input: times = [[1,4],[2,3],[4,6]], targetFriend = 1\n Output: 1\n Explanation: \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.\n Since friend 1 sat on chair 1, we return 1.\n Example 2:\n Input: times = [[3,10],[1,5],[2,6]], targetFriend = 0\n Output: 2\n Explanation: \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.\n Since friend 0 sat on chair 2, we return 2.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1943, - "title": "Describe the Painting", - "question": "class Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n The 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.\n For example, if colors 2, 4, and 6 are mixed, then the resulting mixed color is {2,4,6}.\n For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set.\n You 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.\n For 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.\n Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order.\n A 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:\n Input: segments = [[1,4,5],[4,7,7],[1,7,9]]\n Output: [[1,4,14],[4,7,16]]\n Explanation: 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.\n Example 2:\n Input: segments = [[1,7,9],[6,8,15],[8,10,7]]\n Output: [[1,6,9],[6,7,24],[7,8,15],[8,10,7]]\n Explanation: 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.\n Example 3:\n Input: segments = [[1,4,5],[1,4,7],[4,7,1],[4,7,11]]\n Output: [[1,4,12],[4,7,12]]\n Explanation: 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.\n Note that returning a single segment [1,7) is incorrect because the mixed color sets are different.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1929, - "title": "Concatenation of Array", - "question": "class Solution:\n def getConcatenation(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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).\n Specifically, ans is the concatenation of two nums arrays.\n Return the array ans.\n Example 1:\n Input: nums = [1,2,1]\n Output: [1,2,1,1,2,1]\n Explanation: The array ans is formed as follows:\n - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]\n - ans = [1,2,1,1,2,1]\n Example 2:\n Input: nums = [1,3,2,1]\n Output: [1,3,2,1,1,3,2,1]\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1930, - "title": "Unique Length-3 Palindromic Subsequences", - "question": "class Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n \"\"\"\n Given a string s, return the number of unique palindromes of length three that are a subsequence of s.\n Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.\n A palindrome is a string that reads the same forwards and backwards.\n A 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 For example, \"ace\" is a subsequence of \"abcde\".\n Example 1:\n Input: s = \"aabca\"\n Output: 3\n Explanation: The 3 palindromic subsequences of length 3 are:\n - \"aba\" (subsequence of \"aabca\")\n - \"aaa\" (subsequence of \"aabca\")\n - \"aca\" (subsequence of \"aabca\")\n Example 2:\n Input: s = \"adc\"\n Output: 0\n Explanation: There are no palindromic subsequences of length 3 in \"adc\".\n Example 3:\n Input: s = \"bbcbaba\"\n Output: 4\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1932, - "title": "Merge BSTs to Create Single BST", - "question": "class Solution:\n def canMerge(self, trees: List[TreeNode]) -> Optional[TreeNode]:\n \"\"\"\n 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:\n Select 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].\n Replace the leaf node in trees[i] with trees[j].\n Remove trees[j] from trees.\n Return 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.\n A BST (binary search tree) is a binary tree where each node satisfies the following property:\n Every node in the node's left subtree has a value strictly less than the node's value.\n Every node in the node's right subtree has a value strictly greater than the node's value.\n A leaf is a node that has no children.\n Example 1:\n Input: trees = [[2,1],[3,2,5],[5,4]]\n Output: [3,2,5,1,null,4]\n Explanation:\n In the first operation, pick i=1 and j=0, and merge trees[0] into trees[1].\n Delete trees[0], so trees = [[3,2,5,1],[5,4]].\n In the second operation, pick i=0 and j=1, and merge trees[1] into trees[0].\n Delete trees[1], so trees = [[3,2,5,1,null,4]].\n The resulting tree, shown above, is a valid BST, so return its root.\n Example 2:\n Input: trees = [[5,3,8],[3,2,6]]\n Output: []\n Explanation:\n Pick i=0 and j=1 and merge trees[1] into trees[0].\n Delete trees[1], so trees = [[5,3,8,2,6]].\n The resulting tree is shown above. This is the only valid operation that can be performed, but the resulting tree is not a valid BST, so return null.\n Example 3:\n Input: trees = [[5,4],[3]]\n Output: []\n Explanation: It is impossible to perform any operations.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1931, - "title": "Painting a Grid With Three Different Colors", - "question": "class Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n \"\"\"\n 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.\n Return 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:\n Input: m = 1, n = 1\n Output: 3\n Explanation: The three possible colorings are shown in the image above.\n Example 2:\n Input: m = 1, n = 2\n Output: 6\n Explanation: The six possible colorings are shown in the image above.\n Example 3:\n Input: m = 5, n = 5\n Output: 580986\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1936, - "title": "Add Minimum Number of Rungs", - "question": "class Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n \"\"\"\n 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.\n You 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.\n Return 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:\n Input: rungs = [1,3,5,10], dist = 2\n Output: 2\n Explanation:\n You currently cannot reach the last rung.\n Add rungs at heights 7 and 8 to climb this ladder. \n The ladder will now have rungs at [1,3,5,7,8,10].\n Example 2:\n Input: rungs = [3,6,8,10], dist = 3\n Output: 0\n Explanation:\n This ladder can be climbed without adding additional rungs.\n Example 3:\n Input: rungs = [3,4,6,7], dist = 2\n Output: 1\n Explanation:\n You currently cannot reach the first rung from the ground.\n Add a rung at height 1 to climb this ladder.\n The ladder will now have rungs at [1,3,4,6,7].\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1937, - "title": "Maximum Number of Points with Cost", - "question": "class Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n \"\"\"\n 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.\n To 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.\n However, 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.\n Return the maximum number of points you can achieve.\n abs(x) is defined as:\n x for x >= 0.\n -x for x < 0.\n Example 1: \n Input: points = [[1,2,3],[1,5,1],[3,1,1]]\n Output: 9\n Explanation:\n The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).\n You add 3 + 5 + 3 = 11 to your score.\n However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.\n Your final score is 11 - 2 = 9.\n Example 2:\n Input: points = [[1,5],[2,3],[4,2]]\n Output: 11\n Explanation:\n The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).\n You add 5 + 3 + 4 = 12 to your score.\n However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.\n Your final score is 12 - 1 = 11.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1938, - "title": "Maximum Genetic Difference Query", - "question": "class Solution:\n def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:\n \"\"\"\n There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node's number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.\n You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.\n Return an array ans where ans[i] is the answer to the ith query.\n Example 1:\n Input: parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]\n Output: [2,3,7]\n Explanation: The queries are processed as follows:\n - [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.\n - [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.\n - [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.\n Example 2:\n Input: parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]\n Output: [6,14,7]\n Explanation: The queries are processed as follows:\n - [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.\n - [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.\n - [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1945, - "title": "Sum of Digits of String After Convert", - "question": "class Solution:\n def getLucky(self, s: str, k: int) -> int:\n \"\"\"\n You are given a string s consisting of lowercase English letters, and an integer k.\n First, 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.\n For example, if s = \"zbax\" and k = 2, then the resulting integer would be 8 by the following operations:\n Convert: \"zbax\" \u279d \"(26)(2)(1)(24)\" \u279d \"262124\" \u279d 262124\n Transform #1: 262124 \u279d 2 + 6 + 2 + 1 + 2 + 4 \u279d 17\n Transform #2: 17 \u279d 1 + 7 \u279d 8\n Return the resulting integer after performing the operations described above.\n Example 1:\n Input: s = \"iiii\", k = 1\n Output: 36\n Explanation: 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\n Thus the resulting integer is 36.\n Example 2:\n Input: s = \"leetcode\", k = 2\n Output: 6\n Explanation: 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\n Thus the resulting integer is 6.\n Example 3:\n Input: s = \"zbax\", k = 2\n Output: 8\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1946, - "title": "Largest Number After Mutating Substring", - "question": "class Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n \"\"\"\n 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].\n You 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]]).\n Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num.\n A substring is a contiguous sequence of characters within the string.\n Example 1:\n Input: num = \"132\", change = [9,8,5,0,3,6,4,2,6,8]\n Output: \"832\"\n Explanation: Replace the substring \"1\":\n - 1 maps to change[1] = 8.\n Thus, \"132\" becomes \"832\".\n \"832\" is the largest number that can be created, so return it.\n Example 2:\n Input: num = \"021\", change = [9,4,3,5,7,2,1,9,0,6]\n Output: \"934\"\n Explanation: 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.\n Thus, \"021\" becomes \"934\".\n \"934\" is the largest number that can be created, so return it.\n Example 3:\n Input: num = \"5\", change = [1,4,7,5,3,2,5,6,9,4]\n Output: \"5\"\n Explanation: \"5\" is already the largest number that can be created, so return it.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1947, - "title": "Maximum Compatibility Score Sum", - "question": "class Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n \"\"\"\n There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes).\n The 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).\n Each 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.\n For 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.\n You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores.\n Given students and mentors, return the maximum compatibility score sum that can be achieved.\n Example 1:\n Input: students = [[1,1,0],[1,0,1],[0,0,1]], mentors = [[1,0,0],[0,0,1],[1,1,0]]\n Output: 8\n Explanation: 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.\n The compatibility score sum is 3 + 2 + 3 = 8.\n Example 2:\n Input: students = [[0,0],[0,0],[0,0]], mentors = [[1,1],[1,1],[1,1]]\n Output: 0\n Explanation: The compatibility score of any student-mentor pair is 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1948, - "title": "Delete Duplicate Folders in System", - "question": "class Solution:\n def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:\n \"\"\"\n 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.\n For example, [\"one\", \"two\", \"three\"] represents the path \"/one/two/three\".\n Two 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.\n For 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\n However, 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.\n Once 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.\n Return 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:\n Input: paths = [[\"a\"],[\"c\"],[\"d\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"d\",\"a\"]]\n Output: [[\"d\"],[\"d\",\"a\"]]\n Explanation: The file structure is as shown.\n Folders \"/a\" and \"/c\" (and their subfolders) are marked for deletion because they both contain an empty\n folder named \"b\".\n Example 2:\n Input: paths = [[\"a\"],[\"c\"],[\"a\",\"b\"],[\"c\",\"b\"],[\"a\",\"b\",\"x\"],[\"a\",\"b\",\"x\",\"y\"],[\"w\"],[\"w\",\"y\"]]\n Output: [[\"c\"],[\"c\",\"b\"],[\"a\"],[\"a\",\"b\"]]\n Explanation: The file structure is as shown. \n Folders \"/a/b/x\" and \"/w\" (and their subfolders) are marked for deletion because they both contain an empty folder named \"y\".\n Note that folders \"/a\" and \"/c\" are identical after the deletion, but they are not deleted because they were not marked beforehand.\n Example 3:\n Input: paths = [[\"a\",\"b\"],[\"c\",\"d\"],[\"c\"],[\"a\"]]\n Output: [[\"c\"],[\"c\",\"d\"],[\"a\"],[\"a\",\"b\"]]\n Explanation: All folders are unique in the file system.\n Note that the returned array can be in a different order as the order does not matter.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1958, - "title": "Check if Move is Legal", - "question": "class Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n \"\"\"\n 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'.\n Each 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).\n A 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:\n Given 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:\n Input: board = [[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"],[\"W\",\"B\",\"B\",\".\",\"W\",\"W\",\"W\",\"B\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"B\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\".\",\".\",\".\",\".\"]], rMove = 4, cMove = 3, color = \"B\"\n Output: true\n Explanation: '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.\n The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.\n Example 2:\n Input: board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\"B\",\".\",\".\",\"W\",\".\",\".\",\".\"],[\".\",\".\",\"W\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"W\",\"B\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\".\",\"B\",\"W\",\".\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\"W\",\".\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\"B\"]], rMove = 4, cMove = 4, color = \"W\"\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1959, - "title": "Minimum Total Space Wasted With K Resizing Operations", - "question": "class Solution:\n def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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).\n The 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.\n Return the minimum total space wasted if you can resize the array at most k times.\n Note: The array can have any size at the start and does not count towards the number of resizing operations.\n Example 1:\n Input: nums = [10,20], k = 0\n Output: 10\n Explanation: size = [20,20].\n We can set the initial size to be 20.\n The total wasted space is (20 - 10) + (20 - 20) = 10.\n Example 2:\n Input: nums = [10,20,30], k = 1\n Output: 10\n Explanation: size = [20,20,30].\n We can set the initial size to be 20 and resize to 30 at time 2. \n The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.\n Example 3:\n Input: nums = [10,20,15,30,20], k = 2\n Output: 15\n Explanation: size = [10,20,20,30,30].\n We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.\n The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1952, - "title": "Three Divisors", - "question": "class Solution:\n def isThree(self, n: int) -> bool:\n \"\"\"\n Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false.\n An integer m is a divisor of n if there exists an integer k such that n = k * m.\n Example 1:\n Input: n = 2\n Output: false\n Explantion: 2 has only two divisors: 1 and 2.\n Example 2:\n Input: n = 4\n Output: true\n Explantion: 4 has three divisors: 1, 2, and 4.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1953, - "title": "Maximum Number of Weeks for Which You Can Work", - "question": "class Solution:\n def numberOfWeeks(self, milestones: List[int]) -> int:\n \"\"\"\n 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.\n You can work on the projects following these two rules:\n Every week, you will finish exactly one milestone of one project. You must work every week.\n You cannot work on two milestones from the same project for two consecutive weeks.\n Once 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.\n Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.\n Example 1:\n Input: milestones = [1,2,3]\n Output: 6\n Explanation: One possible scenario is:\n \u200b\u200b\u200b\u200b- 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.\n The total number of weeks is 6.\n Example 2:\n Input: milestones = [5,2,1]\n Output: 7\n Explanation: 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.\n The total number of weeks is 7.\n Note that you cannot work on the last milestone of project 0 on 8th week because it would violate the rules.\n Thus, one milestone in project 0 will remain unfinished.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1968, - "title": "Array With Elements Not Equal to Average of Neighbors", - "question": "class Solution:\n def rearrangeArray(self, nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n More 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].\n Return any rearrangement of nums that meets the requirements.\n Example 1:\n Input: nums = [1,2,3,4,5]\n Output: [1,2,4,5,3]\n Explanation:\n When i=1, nums[i] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.\n When i=2, nums[i] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.\n When i=3, nums[i] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.\n Example 2:\n Input: nums = [6,2,0,9,7]\n Output: [9,7,6,2,0]\n Explanation:\n When i=1, nums[i] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.\n When i=2, nums[i] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.\n When i=3, nums[i] = 2, and the average of its neighbors is (6+0) / 2 = 3.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1955, - "title": "Count Number of Special Subsequences", - "question": "class Solution:\n def countSpecialSubsequences(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n For example, [0,1,2] and [0,0,1,1,1,2] are special.\n In contrast, [2,1,0], [1], and [0,1,2,0] are not special.\n Given 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.\n A 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:\n Input: nums = [0,1,2,2]\n Output: 3\n Explanation: The special subsequences are bolded [0,1,2,2], [0,1,2,2], and [0,1,2,2].\n Example 2:\n Input: nums = [2,2,0,0]\n Output: 0\n Explanation: There are no special subsequences in [2,2,0,0].\n Example 3:\n Input: nums = [0,1,2,0,1,2]\n Output: 7\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1974, - "title": "Minimum Time to Type Word Using Special Typewriter", - "question": "class Solution:\n def minTimeToType(self, word: str) -> int:\n \"\"\"\n 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'.\n Each second, you may perform one of the following operations:\n Move the pointer one character counterclockwise or clockwise.\n Type the character the pointer is currently on.\n Given a string word, return the minimum number of seconds to type out the characters in word.\n Example 1:\n Input: word = \"abc\"\n Output: 5\n Explanation: \n The characters are printed as follows:\n - Type the character 'a' in 1 second since the pointer is initially on 'a'.\n - Move the pointer clockwise to 'b' in 1 second.\n - Type the character 'b' in 1 second.\n - Move the pointer clockwise to 'c' in 1 second.\n - Type the character 'c' in 1 second.\n Example 2:\n Input: word = \"bza\"\n Output: 7\n Explanation:\n The characters are printed as follows:\n - Move the pointer clockwise to 'b' in 1 second.\n - Type the character 'b' in 1 second.\n - Move the pointer counterclockwise to 'z' in 2 seconds.\n - Type the character 'z' in 1 second.\n - Move the pointer clockwise to 'a' in 1 second.\n - Type the character 'a' in 1 second.\n Example 3:\n Input: word = \"zjpc\"\n Output: 34\n Explanation:\n The 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1975, - "title": "Maximum Matrix Sum", - "question": "class Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n \"\"\"\n You are given an n x n integer matrix. You can do the following operation any number of times:\n Choose any two adjacent elements of matrix and multiply each of them by -1.\n Two elements are considered adjacent if and only if they share a border.\n Your 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:\n Input: matrix = [[1,-1],[-1,1]]\n Output: 4\n Explanation: We can follow the following steps to reach sum equals 4:\n - Multiply the 2 elements in the first row by -1.\n - Multiply the 2 elements in the first column by -1.\n Example 2:\n Input: matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]\n Output: 16\n Explanation: We can follow the following step to reach sum equals 16:\n - Multiply the 2 last elements in the second row by -1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1976, - "title": "Number of Ways to Arrive at Destination", - "question": "class Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n \"\"\"\n 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.\n You 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.\n Return 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:\n Input: 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]]\n Output: 4\n Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.\n The 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\n Example 2:\n Input: n = 2, roads = [[1,0,10]]\n Output: 1\n Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1977, - "title": "Number of Ways to Separate Numbers", - "question": "class Solution:\n def numberOfCombinations(self, num: str) -> int:\n \"\"\"\n 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.\n Return 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:\n Input: num = \"327\"\n Output: 2\n Explanation: You could have written down the numbers:\n 3, 27\n 327\n Example 2:\n Input: num = \"094\"\n Output: 0\n Explanation: No numbers can have leading zeros and all numbers must be positive.\n Example 3:\n Input: num = \"0\"\n Output: 0\n Explanation: No numbers can have leading zeros and all numbers must be positive.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1961, - "title": "Check If String Is a Prefix of Array", - "question": "class Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n \"\"\"\n Given a string s and an array of strings words, determine whether s is a prefix string of words.\n A 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.\n Return true if s is a prefix string of words, or false otherwise.\n Example 1:\n Input: s = \"iloveleetcode\", words = [\"i\",\"love\",\"leetcode\",\"apples\"]\n Output: true\n Explanation:\n s can be made by concatenating \"i\", \"love\", and \"leetcode\" together.\n Example 2:\n Input: s = \"iloveleetcode\", words = [\"apples\",\"i\",\"love\",\"leetcode\"]\n Output: false\n Explanation:\n It is impossible to make s using a prefix of arr.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1962, - "title": "Remove Stones to Minimize the Total", - "question": "class Solution:\n def minStoneSum(self, piles: List[int], k: int) -> int:\n \"\"\"\n 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:\n Choose any piles[i] and remove floor(piles[i] / 2) stones from it.\n Notice that you can apply the operation on the same pile more than once.\n Return the minimum possible total number of stones remaining after applying the k operations.\n floor(x) is the greatest integer that is smaller than or equal to x (i.e., rounds x down).\n Example 1:\n Input: piles = [5,4,9], k = 2\n Output: 12\n Explanation: 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].\n The total number of stones in [3,4,5] is 12.\n Example 2:\n Input: piles = [4,3,6,7], k = 3\n Output: 12\n Explanation: 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].\n The total number of stones in [2,3,3,4] is 12.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1963, - "title": "Minimum Number of Swaps to Make the String Balanced", - "question": "class Solution:\n def minSwaps(self, s: str) -> int:\n \"\"\"\n 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 ']'.\n A string is called balanced if and only if:\n It is the empty string, or\n It can be written as AB, where both A and B are balanced strings, or\n It can be written as [C], where C is a balanced string.\n You may swap the brackets at any two indices any number of times.\n Return the minimum number of swaps to make s balanced.\n Example 1:\n Input: s = \"][][\"\n Output: 1\n Explanation: You can make the string balanced by swapping index 0 with index 3.\n The resulting string is \"[[]]\".\n Example 2:\n Input: s = \"]]][[[\"\n Output: 2\n Explanation: 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 = \"[[][]]\".\n The resulting string is \"[[][]]\".\n Example 3:\n Input: s = \"[]\"\n Output: 0\n Explanation: The string is already balanced.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1964, - "title": "Find the Longest Valid Obstacle Course at Each Position", - "question": "class Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n \"\"\"\n 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.\n For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that:\n You choose any number of obstacles between 0 and i inclusive.\n You must include the ith obstacle in the course.\n You must put the chosen obstacles in the same order as they appear in obstacles.\n Every obstacle (except the first) is taller than or the same height as the obstacle immediately before it.\n Return 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:\n Input: obstacles = [1,2,3,2]\n Output: [1,2,3,3]\n Explanation: The longest valid obstacle course at each position is:\n - i = 0: [1], [1] has length 1.\n - i = 1: [1,2], [1,2] has length 2.\n - i = 2: [1,2,3], [1,2,3] has length 3.\n - i = 3: [1,2,3,2], [1,2,2] has length 3.\n Example 2:\n Input: obstacles = [2,2,1]\n Output: [1,2,1]\n Explanation: The longest valid obstacle course at each position is:\n - i = 0: [2], [2] has length 1.\n - i = 1: [2,2], [2,2] has length 2.\n - i = 2: [2,2,1], [1] has length 1.\n Example 3:\n Input: obstacles = [3,1,5,6,4,2]\n Output: [1,1,2,3,2,2]\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1967, - "title": "Number of Strings That Appear as Substrings in Word", - "question": "class Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n \"\"\"\n Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word.\n A substring is a contiguous sequence of characters within a string.\n Example 1:\n Input: patterns = [\"a\",\"abc\",\"bc\",\"d\"], word = \"abc\"\n Output: 3\n Explanation:\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\".\n 3 of the strings in patterns appear as a substring in word.\n Example 2:\n Input: patterns = [\"a\",\"b\",\"c\"], word = \"aaaaabbbbb\"\n Output: 2\n Explanation:\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\".\n 2 of the strings in patterns appear as a substring in word.\n Example 3:\n Input: patterns = [\"a\",\"a\",\"a\"], word = \"ab\"\n Output: 3\n Explanation: Each of the patterns appears as a substring in word \"ab\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1969, - "title": "Minimum Non-Zero Product of the Array Elements", - "question": "class Solution:\n def minNonZeroProduct(self, p: int) -> int:\n \"\"\"\n 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:\n Choose two elements x and y from nums.\n Choose 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.\n For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001.\n Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7.\n Note: The answer should be the minimum product before the modulo operation is done.\n Example 1:\n Input: p = 1\n Output: 1\n Explanation: nums = [1].\n There is only one element, so the product equals that element.\n Example 2:\n Input: p = 2\n Output: 6\n Explanation: nums = [01, 10, 11].\n Any swap would either make the product 0 or stay the same.\n Thus, the array product of 1 * 2 * 3 = 6 is already minimized.\n Example 3:\n Input: p = 3\n Output: 1512\n Explanation: 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].\n The array product is 1 * 6 * 1 * 6 * 1 * 6 * 7 = 1512, which is the minimum possible product.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1970, - "title": "Last Day Where You Can Still Cross", - "question": "class Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n \"\"\"\n There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively.\n Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1).\n You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down).\n Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.\n Example 1:\n Input: row = 2, col = 2, cells = [[1,1],[2,1],[1,2],[2,2]]\n Output: 2\n Explanation: The above image depicts how the matrix changes each day starting from day 0.\n The last day where it is possible to cross from top to bottom is on day 2.\n Example 2:\n Input: row = 2, col = 2, cells = [[1,1],[1,2],[2,1],[2,2]]\n Output: 1\n Explanation: The above image depicts how the matrix changes each day starting from day 0.\n The last day where it is possible to cross from top to bottom is on day 1.\n Example 3:\n Input: row = 3, col = 3, cells = [[1,2],[2,1],[3,3],[2,2],[1,1],[1,3],[2,3],[3,2],[3,1]]\n Output: 3\n Explanation: The above image depicts how the matrix changes each day starting from day 0.\n The last day where it is possible to cross from top to bottom is on day 3.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1991, - "title": "Find the Middle Index in Array", - "question": "class Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n \"\"\"\n Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones).\n A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1].\n If 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.\n Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.\n Example 1:\n Input: nums = [2,3,-1,8,4]\n Output: 3\n Explanation: The sum of the numbers before index 3 is: 2 + 3 + -1 = 4\n The sum of the numbers after index 3 is: 4 = 4\n Example 2:\n Input: nums = [1,-1,4]\n Output: 2\n Explanation: The sum of the numbers before index 2 is: 1 + -1 = 0\n The sum of the numbers after index 2 is: 0\n Example 3:\n Input: nums = [2,5]\n Output: -1\n Explanation: There is no valid middleIndex.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1992, - "title": "Find All Groups of Farmland", - "question": "class Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n To 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.\n land 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].\n Return 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:\n Input: land = [[1,0,0],[0,1,1],[0,1,1]]\n Output: [[0,0,0,0],[1,1,2,2]]\n Explanation:\n The first group has a top left corner at land[0][0] and a bottom right corner at land[0][0].\n The second group has a top left corner at land[1][1] and a bottom right corner at land[2][2].\n Example 2:\n Input: land = [[1,1],[1,1]]\n Output: [[0,0,1,1]]\n Explanation:\n The first group has a top left corner at land[0][0] and a bottom right corner at land[1][1].\n Example 3:\n Input: land = [[0]]\n Output: []\n Explanation:\n There are no groups of farmland.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1993, - "title": "Operations on Tree", - "question": "class LockingTree:\n def __init__(self, parent: List[int]):\n def lock(self, num: int, user: int) -> bool:\n def unlock(self, num: int, user: int) -> bool:\n def upgrade(self, num: int, user: int) -> bool:\n \"\"\"\n You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree.\n The data structure should support the following functions:\n Lock: Locks the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlocked.\n Unlock: Unlocks the given node for the given user. You may only unlock a node using this function if it is currently locked by the same user.\n Upgrade: Locks the given node for the given user and unlocks all of its descendants regardless of who locked it. You may only upgrade a node if all 3 conditions are true:\n The node is unlocked,\n It has at least one locked descendant (by any user), and\n It does not have any locked ancestors.\n Implement the LockingTree class:\n LockingTree(int[] parent) initializes the data structure with the parent array.\n lock(int num, int user) returns true if it is possible for the user with id user to lock the node num, or false otherwise. If it is possible, the node num will become locked by the user with id user.\n unlock(int num, int user) returns true if it is possible for the user with id user to unlock the node num, or false otherwise. If it is possible, the node num will become unlocked.\n upgrade(int num, int user) returns true if it is possible for the user with id user to upgrade the node num, or false otherwise. If it is possible, the node num will be upgraded.\n Example 1:\n Input\n [\"LockingTree\", \"lock\", \"unlock\", \"unlock\", \"lock\", \"upgrade\", \"lock\"]\n [[[-1, 0, 0, 1, 1, 2, 2]], [2, 2], [2, 3], [2, 2], [4, 5], [0, 1], [0, 1]]\n Output\n [null, true, false, true, true, true, false]\n Explanation\n LockingTree lockingTree = new LockingTree([-1, 0, 0, 1, 1, 2, 2]);\n lockingTree.lock(2, 2); // return true because node 2 is unlocked.\n // Node 2 will now be locked by user 2.\n lockingTree.unlock(2, 3); // return false because user 3 cannot unlock a node locked by user 2.\n lockingTree.unlock(2, 2); // return true because node 2 was previously locked by user 2.\n // Node 2 will now be unlocked.\n lockingTree.lock(4, 5); // return true because node 4 is unlocked.\n // Node 4 will now be locked by user 5.\n lockingTree.upgrade(0, 1); // return true because node 0 is unlocked and has at least one locked descendant (node 4).\n // Node 0 will now be locked by user 1 and node 4 will now be unlocked.\n lockingTree.lock(0, 1); // return false because node 0 is already locked.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1994, - "title": "The Number of Good Subsets", - "question": "class Solution:\n def numberOfGoodSubsets(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n For example, if nums = [1, 2, 3, 4]:\n [2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3, and 3 = 3 respectively.\n [1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.\n Return the number of different good subsets in nums modulo 109 + 7.\n A 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:\n Input: nums = [1,2,3,4]\n Output: 6\n Explanation: The good subsets are:\n - [1,2]: product is 2, which is the product of distinct prime 2.\n - [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.\n - [1,3]: product is 3, which is the product of distinct prime 3.\n - [2]: product is 2, which is the product of distinct prime 2.\n - [2,3]: product is 6, which is the product of distinct primes 2 and 3.\n - [3]: product is 3, which is the product of distinct prime 3.\n Example 2:\n Input: nums = [4,2,3,15]\n Output: 5\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1979, - "title": "Find Greatest Common Divisor of Array", - "question": "class Solution:\n def findGCD(self, nums: List[int]) -> int:\n \"\"\"\n Given an integer array nums, return the greatest common divisor of the smallest number and largest number in nums.\n The greatest common divisor of two numbers is the largest positive integer that evenly divides both numbers.\n Example 1:\n Input: nums = [2,5,6,9,10]\n Output: 2\n Explanation:\n The smallest number in nums is 2.\n The largest number in nums is 10.\n The greatest common divisor of 2 and 10 is 2.\n Example 2:\n Input: nums = [7,5,6,8,3]\n Output: 1\n Explanation:\n The smallest number in nums is 3.\n The largest number in nums is 8.\n The greatest common divisor of 3 and 8 is 1.\n Example 3:\n Input: nums = [3,3]\n Output: 3\n Explanation:\n The smallest number in nums is 3.\n The largest number in nums is 3.\n The greatest common divisor of 3 and 3 is 3.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1980, - "title": "Find Unique Binary String", - "question": "class Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n \"\"\"\n 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:\n Input: nums = [\"01\",\"10\"]\n Output: \"11\"\n Explanation: \"11\" does not appear in nums. \"00\" would also be correct.\n Example 2:\n Input: nums = [\"00\",\"01\"]\n Output: \"11\"\n Explanation: \"11\" does not appear in nums. \"10\" would also be correct.\n Example 3:\n Input: nums = [\"111\",\"011\",\"001\"]\n Output: \"101\"\n Explanation: \"101\" does not appear in nums. \"000\", \"010\", \"100\", and \"110\" would also be correct.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1981, - "title": "Minimize the Difference Between Target and Chosen Elements", - "question": "class Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \"\"\"\n You are given an m x n integer matrix mat and an integer target.\n Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.\n Return the minimum absolute difference.\n The absolute difference between two numbers a and b is the absolute value of a - b.\n Example 1:\n Input: mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13\n Output: 0\n Explanation: 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.\n The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0.\n Example 2:\n Input: mat = [[1],[2],[3]], target = 100\n Output: 94\n Explanation: 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.\n The sum of the chosen elements is 6, and the absolute difference is 94.\n Example 3:\n Input: mat = [[1,2,9,8,7]], target = 6\n Output: 1\n Explanation: The best choice is to choose 7 from the first row.\n The absolute difference is 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1982, - "title": "Find Array Given Subset Sums", - "question": "class Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n \"\"\"\n 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).\n Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them.\n An 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.\n Note: Test cases are generated such that there will always be at least one correct answer.\n Example 1:\n Input: n = 3, sums = [-3,-2,-1,0,0,1,2,3]\n Output: [1,2,-3]\n Explanation: [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\n Note that any permutation of [1,2,-3] and also any permutation of [-1,-2,3] will also be accepted.\n Example 2:\n Input: n = 2, sums = [0,0,0,0]\n Output: [0,0]\n Explanation: The only correct answer is [0,0].\n Example 3:\n Input: n = 4, sums = [0,0,5,5,4,-1,4,9,9,-1,4,3,4,8,3,8]\n Output: [0,-1,4,5]\n Explanation: [0,-1,4,5] is able to achieve the given subset sums.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1984, - "title": "Minimum Difference Between Highest and Lowest of K Scores", - "question": "class Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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.\n Pick 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.\n Return the minimum possible difference.\n Example 1:\n Input: nums = [90], k = 1\n Output: 0\n Explanation: 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.\n The minimum possible difference is 0.\n Example 2:\n Input: nums = [9,4,1,7], k = 2\n Output: 2\n Explanation: 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.\n The minimum possible difference is 2.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1985, - "title": "Find the Kth Largest Integer in the Array", - "question": "class Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n \"\"\"\n You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros.\n Return the string that represents the kth largest integer in nums.\n Note: 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:\n Input: nums = [\"3\",\"6\",\"7\",\"10\"], k = 4\n Output: \"3\"\n Explanation:\n The numbers in nums sorted in non-decreasing order are [\"3\",\"6\",\"7\",\"10\"].\n The 4th largest integer in nums is \"3\".\n Example 2:\n Input: nums = [\"2\",\"21\",\"12\",\"1\"], k = 3\n Output: \"2\"\n Explanation:\n The numbers in nums sorted in non-decreasing order are [\"1\",\"2\",\"12\",\"21\"].\n The 3rd largest integer in nums is \"2\".\n Example 3:\n Input: nums = [\"0\",\"0\"], k = 2\n Output: \"0\"\n Explanation:\n The numbers in nums sorted in non-decreasing order are [\"0\",\"0\"].\n The 2nd largest integer in nums is \"0\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1986, - "title": "Minimum Number of Work Sessions to Finish the Tasks", - "question": "class Solution:\n def minSessions(self, tasks: List[int], sessionTime: int) -> int:\n \"\"\"\n 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.\n You should finish the given tasks in a way that satisfies the following conditions:\n If you start a task in a work session, you must complete it in the same work session.\n You can start a new task immediately after finishing the previous one.\n You may complete the tasks in any order.\n Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above.\n The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].\n Example 1:\n Input: tasks = [1,2,3], sessionTime = 3\n Output: 2\n Explanation: You can finish the tasks in two work sessions.\n - First work session: finish the first and the second tasks in 1 + 2 = 3 hours.\n - Second work session: finish the third task in 3 hours.\n Example 2:\n Input: tasks = [3,1,3,1,1], sessionTime = 8\n Output: 2\n Explanation: You can finish the tasks in two work sessions.\n - First work session: finish all the tasks except the last one in 3 + 1 + 3 + 1 = 8 hours.\n - Second work session: finish the last task in 1 hour.\n Example 3:\n Input: tasks = [1,2,3,4,5], sessionTime = 15\n Output: 1\n Explanation: You can finish all the tasks in one work session.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1987, - "title": "Number of Unique Good Subsequences", - "question": "class Solution:\n def numberOfUniqueGoodSubsequences(self, binary: str) -> int:\n \"\"\"\n You are given a binary string binary. A subsequence of binary is considered good if it is not empty and has no leading zeros (with the exception of \"0\").\n Find the number of unique good subsequences of binary.\n For example, if binary = \"001\", then all the good subsequences are [\"0\", \"0\", \"1\"], so the unique good subsequences are \"0\" and \"1\". Note that subsequences \"00\", \"01\", and \"001\" are not good because they have leading zeros.\n Return the number of unique good subsequences of binary. Since the answer may be very large, return it modulo 109 + 7.\n A 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:\n Input: binary = \"001\"\n Output: 2\n Explanation: The good subsequences of binary are [\"0\", \"0\", \"1\"].\n The unique good subsequences are \"0\" and \"1\".\n Example 2:\n Input: binary = \"11\"\n Output: 2\n Explanation: The good subsequences of binary are [\"1\", \"1\", \"11\"].\n The unique good subsequences are \"1\" and \"11\".\n Example 3:\n Input: binary = \"101\"\n Output: 5\n Explanation: The good subsequences of binary are [\"1\", \"0\", \"1\", \"10\", \"11\", \"101\"]. \n The unique good subsequences are \"0\", \"1\", \"10\", \"11\", and \"101\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2006, - "title": "Count Number of Pairs With Absolute Difference K", - "question": "class Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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.\n The value of |x| is defined as:\n x if x >= 0.\n -x if x < 0.\n Example 1:\n Input: nums = [1,2,2,1], k = 1\n Output: 4\n Explanation: The pairs with an absolute difference of 1 are:\n - [1,2,2,1]\n - [1,2,2,1]\n - [1,2,2,1]\n - [1,2,2,1]\n Example 2:\n Input: nums = [1,3], k = 3\n Output: 0\n Explanation: There are no pairs with an absolute difference of 3.\n Example 3:\n Input: nums = [3,2,1,5,4], k = 2\n Output: 3\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2007, - "title": "Find Original Array From Doubled Array", - "question": "class Solution:\n def findOriginalArray(self, changed: List[int]) -> List[int]:\n \"\"\"\n 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.\n Given 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:\n Input: changed = [1,3,4,2,6,8]\n Output: [1,3,4]\n Explanation: 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.\n Other original arrays could be [4,3,1] or [3,1,4].\n Example 2:\n Input: changed = [6,3,0,1]\n Output: []\n Explanation: changed is not a doubled array.\n Example 3:\n Input: changed = [1]\n Output: []\n Explanation: changed is not a doubled array.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2008, - "title": "Maximum Earnings From Taxi", - "question": "class Solution:\n def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:\n \"\"\"\n 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.\n The 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.\n For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time.\n Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally.\n Note: You may drop off a passenger and pick up a different passenger at the same point.\n Example 1:\n Input: n = 5, rides = [[2,5,4],[1,5,1]]\n Output: 7\n Explanation: We can pick up passenger 0 to earn 5 - 2 + 4 = 7 dollars.\n Example 2:\n Input: n = 20, rides = [[1,6,1],[3,10,2],[10,12,3],[11,12,2],[12,15,2],[13,18,1]]\n Output: 20\n Explanation: 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.\n We earn 9 + 5 + 6 = 20 dollars in total.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2009, - "title": "Minimum Number of Operations to Make Array Continuous", - "question": "class Solution:\n def minOperations(self, nums: List[int]) -> int:\n \"\"\"\n You are given an integer array nums. In one operation, you can replace any element in nums with any integer.\n nums is considered continuous if both of the following conditions are fulfilled:\n All elements in nums are unique.\n The difference between the maximum element and the minimum element in nums equals nums.length - 1.\n For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous.\n Return the minimum number of operations to make nums continuous.\n Example 1:\n Input: nums = [4,2,5,3]\n Output: 0\n Explanation: nums is already continuous.\n Example 2:\n Input: nums = [1,2,3,5,6]\n Output: 1\n Explanation: One possible solution is to change the last element to 4.\n The resulting array is [1,2,3,5,4], which is continuous.\n Example 3:\n Input: nums = [1,10,100,1000]\n Output: 3\n Explanation: 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.\n The resulting array is [1,2,3,4], which is continuous.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 1971, - "title": "Find if Path Exists in Graph", - "question": "class Solution:\n def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n \"\"\"\n There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself.\n You want to determine if there is a valid path that exists from vertex source to vertex destination.\n Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.\n Example 1:\n Input: n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2\n Output: true\n Explanation: There are two paths from vertex 0 to vertex 2:\n - 0 \u2192 1 \u2192 2\n - 0 \u2192 2\n Example 2:\n Input: n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5\n Output: false\n Explanation: There is no path from vertex 0 to vertex 5.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1995, - "title": "Count Special Quadruplets", - "question": "class Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n \"\"\"\n Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:\n nums[a] + nums[b] + nums[c] == nums[d], and\n a < b < c < d\n Example 1:\n Input: nums = [1,2,3,6]\n Output: 1\n Explanation: The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.\n Example 2:\n Input: nums = [3,3,6,4,5]\n Output: 0\n Explanation: There are no such quadruplets in [3,3,6,4,5].\n Example 3:\n Input: nums = [1,1,1,3,5]\n Output: 4\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 1996, - "title": "The Number of Weak Characters in the Game", - "question": "class Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \"\"\"\n 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.\n A 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.\n Return the number of weak characters.\n Example 1:\n Input: properties = [[5,5],[6,3],[3,6]]\n Output: 0\n Explanation: No character has strictly greater attack and defense than the other.\n Example 2:\n Input: properties = [[2,2],[3,3]]\n Output: 1\n Explanation: The first character is weak because the second character has a strictly greater attack and defense.\n Example 3:\n Input: properties = [[1,5],[10,4],[4,3]]\n Output: 1\n Explanation: The third character is weak because the second character has a strictly greater attack and defense.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1997, - "title": "First Day Where You Have Been in All the Rooms", - "question": "class Solution:\n def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:\n \"\"\"\n 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.\n Initially 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:\n Assuming that on a day, you visit room i,\n if 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;\n if 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.\n Return 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:\n Input: nextVisit = [0,0]\n Output: 2\n Explanation:\n - On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.\n On the next day you will visit room nextVisit[0] = 0\n - On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.\n On the next day you will visit room (0 + 1) mod 2 = 1\n - On day 2, you visit room 1. This is the first day where you have been in all the rooms.\n Example 2:\n Input: nextVisit = [0,0,2]\n Output: 6\n Explanation:\n Your room visiting order for each day is: [0,0,1,0,0,1,2,...].\n Day 6 is the first day where you have been in all the rooms.\n Example 3:\n Input: nextVisit = [0,1,2,0]\n Output: 6\n Explanation:\n Your room visiting order for each day is: [0,0,1,1,2,2,3,...].\n Day 6 is the first day where you have been in all the rooms.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 1998, - "title": "GCD Sort of an Array", - "question": "class Solution:\n def gcdSort(self, nums: List[int]) -> bool:\n \"\"\"\n You are given an integer array nums, and you can perform the following operation any number of times on nums:\n Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1 where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j].\n Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.\n Example 1:\n Input: nums = [7,21,3]\n Output: true\n Explanation: We can sort [7,21,3] by performing the following operations:\n - Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]\n - Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]\n Example 2:\n Input: nums = [5,2,6,2]\n Output: false\n Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.\n Example 3:\n Input: nums = [10,5,9,3,15]\n Output: true\n We can sort [10,5,9,3,15] by performing the following operations:\n - Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]\n - Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]\n - Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2000, - "title": "Reverse Prefix of Word", - "question": "class Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n \"\"\"\n 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.\n For 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\".\n Return the resulting string.\n Example 1:\n Input: word = \"abcdefd\", ch = \"d\"\n Output: \"dcbaefd\"\n Explanation: The first occurrence of \"d\" is at index 3. \n Reverse the part of word from 0 to 3 (inclusive), the resulting string is \"dcbaefd\".\n Example 2:\n Input: word = \"xyxzxe\", ch = \"z\"\n Output: \"zxyxxe\"\n Explanation: The first and only occurrence of \"z\" is at index 3.\n Reverse the part of word from 0 to 3 (inclusive), the resulting string is \"zxyxxe\".\n Example 3:\n Input: word = \"abcd\", ch = \"z\"\n Output: \"abcd\"\n Explanation: \"z\" does not exist in word.\n You should not do any reverse operation, the resulting string is \"abcd\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2001, - "title": "Number of Pairs of Interchangeable Rectangles", - "question": "class Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n \"\"\"\n 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.\n Two 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).\n Return the number of pairs of interchangeable rectangles in rectangles.\n Example 1:\n Input: rectangles = [[4,8],[3,6],[10,20],[15,30]]\n Output: 6\n Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed):\n - Rectangle 0 with rectangle 1: 4/8 == 3/6.\n - Rectangle 0 with rectangle 2: 4/8 == 10/20.\n - Rectangle 0 with rectangle 3: 4/8 == 15/30.\n - Rectangle 1 with rectangle 2: 3/6 == 10/20.\n - Rectangle 1 with rectangle 3: 3/6 == 15/30.\n - Rectangle 2 with rectangle 3: 10/20 == 15/30.\n Example 2:\n Input: rectangles = [[4,5],[7,8]]\n Output: 0\n Explanation: There are no interchangeable pairs of rectangles.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2002, - "title": "Maximum Product of the Length of Two Palindromic Subsequences", - "question": "class Solution:\n def maxProduct(self, s: str) -> int:\n \"\"\"\n 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.\n Return the maximum possible product of the lengths of the two palindromic subsequences.\n A 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:\n Input: s = \"leetcodecom\"\n Output: 9\n Explanation: An optimal solution is to choose \"ete\" for the 1st subsequence and \"cdc\" for the 2nd subsequence.\n The product of their lengths is: 3 * 3 = 9.\n Example 2:\n Input: s = \"bb\"\n Output: 1\n Explanation: An optimal solution is to choose \"b\" (the first character) for the 1st subsequence and \"b\" (the second character) for the 2nd subsequence.\n The product of their lengths is: 1 * 1 = 1.\n Example 3:\n Input: s = \"accbcaxxcxx\"\n Output: 25\n Explanation: An optimal solution is to choose \"accca\" for the 1st subsequence and \"xxcxx\" for the 2nd subsequence.\n The product of their lengths is: 5 * 5 = 25.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2003, - "title": "Smallest Missing Genetic Value in Each Subtree", - "question": "class Solution:\n def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:\n \"\"\"\n 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.\n There 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.\n Return an array ans of length n where ans[i] is the smallest genetic value that is missing from the subtree rooted at node i.\n The subtree rooted at a node x contains node x and all of its descendant nodes.\n Example 1:\n Input: parents = [-1,0,0,2], nums = [1,2,3,4]\n Output: [5,1,1,1]\n Explanation: The answer for each subtree is calculated as follows:\n - 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.\n - 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.\n - 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.\n - 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.\n Example 2:\n Input: parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]\n Output: [7,1,1,4,2,1]\n Explanation: The answer for each subtree is calculated as follows:\n - 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.\n - 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.\n - 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.\n - 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.\n - 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.\n - 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.\n Example 3:\n Input: parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]\n Output: [1,1,1,1,1,1,1]\n Explanation: The value 1 is missing from all the subtrees.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2022, - "title": "Convert 1D Array Into 2D Array", - "question": "class Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n \"\"\"\n 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.\n The 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.\n Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.\n Example 1:\n Input: original = [1,2,3,4], m = 2, n = 2\n Output: [[1,2],[3,4]]\n Explanation: The constructed 2D array should contain 2 rows and 2 columns.\n The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.\n The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.\n Example 2:\n Input: original = [1,2,3], m = 1, n = 3\n Output: [[1,2,3]]\n Explanation: The constructed 2D array should contain 1 row and 3 columns.\n Put all three elements in original into the first row of the constructed 2D array.\n Example 3:\n Input: original = [1,2], m = 1, n = 1\n Output: []\n Explanation: There are 2 elements in original.\n It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2023, - "title": "Number of Pairs of Strings With Concatenation Equal to Target", - "question": "class Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n \"\"\"\n 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:\n Input: nums = [\"777\",\"7\",\"77\",\"77\"], target = \"7777\"\n Output: 4\n Explanation: Valid pairs are:\n - (0, 1): \"777\" + \"7\"\n - (1, 0): \"7\" + \"777\"\n - (2, 3): \"77\" + \"77\"\n - (3, 2): \"77\" + \"77\"\n Example 2:\n Input: nums = [\"123\",\"4\",\"12\",\"34\"], target = \"1234\"\n Output: 2\n Explanation: Valid pairs are:\n - (0, 1): \"123\" + \"4\"\n - (2, 3): \"12\" + \"34\"\n Example 3:\n Input: nums = [\"1\",\"1\",\"1\"], target = \"11\"\n Output: 6\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2024, - "title": "Maximize the Confusion of an Exam", - "question": "class Solution:\n def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:\n \"\"\"\n 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).\n You 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:\n Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').\n Return 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:\n Input: answerKey = \"TTFF\", k = 2\n Output: 4\n Explanation: We can replace both the 'F's with 'T's to make answerKey = \"TTTT\".\n There are four consecutive 'T's.\n Example 2:\n Input: answerKey = \"TFFT\", k = 1\n Output: 3\n Explanation: We can replace the first 'T' with an 'F' to make answerKey = \"FFFT\".\n Alternatively, we can replace the second 'T' with an 'F' to make answerKey = \"TFFF\".\n In both cases, there are three consecutive 'F's.\n Example 3:\n Input: answerKey = \"TTFTTFTT\", k = 1\n Output: 5\n Explanation: We can replace the first 'F' to make answerKey = \"TTTTTFTT\"\n Alternatively, we can replace the second 'F' to make answerKey = \"TTFTTTTT\". \n In both cases, there are five consecutive 'T's.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2025, - "title": "Maximum Number of Ways to Partition an Array", - "question": "class Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n \"\"\"\n 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:\n 1 <= pivot < n\n nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1]\n You 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.\n Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.\n Example 1:\n Input: nums = [2,-1,2], k = 3\n Output: 1\n Explanation: One optimal approach is to change nums[0] to k. The array becomes [3,-1,2].\n There is one way to partition the array:\n - For pivot = 2, we have the partition [3,-1 | 2]: 3 + -1 == 2.\n Example 2:\n Input: nums = [0,0,0], k = 1\n Output: 2\n Explanation: The optimal approach is to leave the array unchanged.\n There are two ways to partition the array:\n - For pivot = 1, we have the partition [0 | 0,0]: 0 == 0 + 0.\n - For pivot = 2, we have the partition [0,0 | 0]: 0 + 0 == 0.\n Example 3:\n Input: nums = [22,4,-25,-20,-15,15,-16,7,19,-10,0,-13,-14], k = -33\n Output: 4\n Explanation: 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].\n There are four ways to partition the array.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2011, - "title": "Final Value of Variable After Performing Operations", - "question": "class Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n \"\"\"\n 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.\n Initially, the value of X is 0.\n Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.\n Example 1:\n Input: operations = [\"--X\",\"X++\",\"X++\"]\n Output: 1\n Explanation: The operations are performed as follows:\n Initially, X = 0.\n --X: X is decremented by 1, X = 0 - 1 = -1.\n X++: X is incremented by 1, X = -1 + 1 = 0.\n X++: X is incremented by 1, X = 0 + 1 = 1.\n Example 2:\n Input: operations = [\"++X\",\"++X\",\"X++\"]\n Output: 3\n Explanation: The operations are performed as follows:\n Initially, X = 0.\n ++X: X is incremented by 1, X = 0 + 1 = 1.\n ++X: X is incremented by 1, X = 1 + 1 = 2.\n X++: X is incremented by 1, X = 2 + 1 = 3.\n Example 3:\n Input: operations = [\"X++\",\"++X\",\"--X\",\"X--\"]\n Output: 0\n Explanation: The operations are performed as follows:\n Initially, X = 0.\n X++: 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.\n X--: X is decremented by 1, X = 1 - 1 = 0.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2012, - "title": "Sum of Beauty in the Array", - "question": "class Solution:\n def sumOfBeauties(self, nums: List[int]) -> int:\n \"\"\"\n You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:\n 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.\n 1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.\n 0, if none of the previous conditions holds.\n Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.\n Example 1:\n Input: nums = [1,2,3]\n Output: 2\n Explanation: For each index i in the range 1 <= i <= 1:\n - The beauty of nums[1] equals 2.\n Example 2:\n Input: nums = [2,4,6,4]\n Output: 1\n Explanation: For each index i in the range 1 <= i <= 2:\n - The beauty of nums[1] equals 1.\n - The beauty of nums[2] equals 0.\n Example 3:\n Input: nums = [3,2,1]\n Output: 0\n Explanation: For each index i in the range 1 <= i <= 1:\n - The beauty of nums[1] equals 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2013, - "title": "Detect Squares", - "question": "class DetectSquares:\n def __init__(self):\n def add(self, point: List[int]) -> None:\n def count(self, point: List[int]) -> int:\n \"\"\"\n You are given a stream of points on the X-Y plane. Design an algorithm that:\n Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.\n Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.\n An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis.\n Implement the DetectSquares class:\n DetectSquares() Initializes the object with an empty data structure.\n void add(int[] point) Adds a new point point = [x, y] to the data structure.\n int count(int[] point) Counts the number of ways to form axis-aligned squares with point point = [x, y] as described above.\n Example 1:\n Input\n [\"DetectSquares\", \"add\", \"add\", \"add\", \"count\", \"count\", \"add\", \"count\"]\n [[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]]\n Output\n [null, null, null, null, 1, 0, null, 2]\n Explanation\n DetectSquares detectSquares = new DetectSquares();\n detectSquares.add([3, 10]);\n detectSquares.add([11, 2]);\n detectSquares.add([3, 2]);\n detectSquares.count([11, 10]); // return 1. You can choose:\n // - The first, second, and third points\n detectSquares.count([14, 8]); // return 0. The query point cannot form a square with any points in the data structure.\n detectSquares.add([11, 2]); // Adding duplicate points is allowed.\n detectSquares.count([11, 10]); // return 2. You can choose:\n // - The first, second, and third points\n // - The first, third, and fourth points\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2014, - "title": "Longest Subsequence Repeated k Times", - "question": "class Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n \"\"\"\n 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.\n A 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 A 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.\n For 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\".\n Return 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:\n Input: s = \"letsleetcode\", k = 2\n Output: \"let\"\n Explanation: There are two longest subsequences repeated 2 times: \"let\" and \"ete\".\n \"let\" is the lexicographically largest one.\n Example 2:\n Input: s = \"bb\", k = 2\n Output: \"b\"\n Explanation: The longest subsequence repeated 2 times is \"b\".\n Example 3:\n Input: s = \"ab\", k = 2\n Output: \"\"\n Explanation: There is no subsequence repeated 2 times. Empty string is returned.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2016, - "title": "Maximum Difference Between Increasing Elements", - "question": "class Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n \"\"\"\n 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].\n Return the maximum difference. If no such i and j exists, return -1.\n Example 1:\n Input: nums = [7,1,5,4]\n Output: 4\n Explanation:\n The maximum difference occurs with i = 1 and j = 2, nums[j] - nums[i] = 5 - 1 = 4.\n Note that with i = 1 and j = 0, the difference nums[j] - nums[i] = 7 - 1 = 6, but i > j, so it is not valid.\n Example 2:\n Input: nums = [9,4,3,2]\n Output: -1\n Explanation:\n There is no i and j such that i < j and nums[i] < nums[j].\n Example 3:\n Input: nums = [1,5,2,10]\n Output: 9\n Explanation:\n The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2017, - "title": "Grid Game", - "question": "class Solution:\n def gridGame(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n Both 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)).\n At 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.\n The 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:\n Input: grid = [[2,5,4],[1,5,1]]\n Output: 4\n Explanation: 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.\n The cells visited by the first robot are set to 0.\n The second robot will collect 0 + 0 + 4 + 0 = 4 points.\n Example 2:\n Input: grid = [[3,3,1],[8,5,2]]\n Output: 4\n Explanation: 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.\n The cells visited by the first robot are set to 0.\n The second robot will collect 0 + 3 + 1 + 0 = 4 points.\n Example 3:\n Input: grid = [[1,3,1,15],[1,3,3,1]]\n Output: 7\n Explanation: 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.\n The cells visited by the first robot are set to 0.\n The second robot will collect 0 + 1 + 3 + 3 + 0 = 7 points.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2018, - "title": "Check if Word Can Be Placed In Crossword", - "question": "class Solution:\n def placeWordInCrossword(self, board: List[List[str]], word: str) -> bool:\n \"\"\"\n 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.\n A 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:\n It does not occupy a cell containing the character '#'.\n The cell each letter is placed in must either be ' ' (empty) or match the letter already on the board.\n There must not be any empty cells ' ' or other lowercase letters directly left or right of the word if the word was placed horizontally.\n There must not be any empty cells ' ' or other lowercase letters directly above or below the word if the word was placed vertically.\n Given a string word, return true if word can be placed in board, or false otherwise.\n Example 1:\n Input: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \"c\", \" \"]], word = \"abc\"\n Output: true\n Explanation: The word \"abc\" can be placed as shown above (top to bottom).\n Example 2:\n Input: board = [[\" \", \"#\", \"a\"], [\" \", \"#\", \"c\"], [\" \", \"#\", \"a\"]], word = \"ac\"\n Output: false\n Explanation: It is impossible to place the word because there will always be a space/letter above or below it.\n Example 3:\n Input: board = [[\"#\", \" \", \"#\"], [\" \", \" \", \"#\"], [\"#\", \" \", \"c\"]], word = \"ca\"\n Output: true\n Explanation: The word \"ca\" can be placed as shown above (right to left). \n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2019, - "title": "The Score of Students Solving Math Expression", - "question": "class Solution:\n def scoreOfStudents(self, s: str, answers: List[int]) -> int:\n \"\"\"\n 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:\n Compute multiplication, reading from left to right; Then,\n Compute addition, reading from left to right.\n You 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:\n If an answer equals the correct answer of the expression, this student will be rewarded 5 points;\n Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded 2 points;\n Otherwise, this student will be rewarded 0 points.\n Return the sum of the points of the students.\n Example 1:\n Input: s = \"7+3*1*2\", answers = [20,13,42]\n Output: 7\n Explanation: As illustrated above, the correct answer of the expression is 13, therefore one student is rewarded 5 points: [20,13,42]\n A 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]\n The points for the students are: [2,5,0]. The sum of the points is 2+5+0=7.\n Example 2:\n Input: s = \"3+5*2\", answers = [13,0,10,13,13,16,16]\n Output: 19\n Explanation: The correct answer of the expression is 13, therefore three students are rewarded 5 points each: [13,0,10,13,13,16,16]\n A 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]\n The points for the students are: [5,0,0,5,5,2,2]. The sum of the points is 5+0+0+5+5+2+2=19.\n Example 3:\n Input: s = \"6+0*1\", answers = [12,9,6,4,8,6]\n Output: 10\n Explanation: The correct answer of the expression is 6.\n If a student had incorrectly done (6+0)*1, the answer would also be 6.\n By the rules of grading, the students will still be rewarded 5 points (as they got the correct answer), not 2 points.\n The points for the students are: [0,0,5,0,0,5]. The sum of the points is 10.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2037, - "title": "Minimum Number of Moves to Seat Everyone", - "question": "class Solution:\n def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:\n \"\"\"\n 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.\n You may perform the following move any number of times:\n Increase 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)\n Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.\n Note that there may be multiple seats or students in the same position at the beginning.\n Example 1:\n Input: seats = [3,1,5], students = [2,7,4]\n Output: 4\n Explanation: 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.\n In total, 1 + 2 + 1 = 4 moves were used.\n Example 2:\n Input: seats = [4,1,5,9], students = [1,3,2,6]\n Output: 7\n Explanation: 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.\n In total, 0 + 1 + 3 + 3 = 7 moves were used.\n Example 3:\n Input: seats = [2,2,6,6], students = [1,3,2,6]\n Output: 4\n Explanation: Note that there are two seats at position 2 and two seats at position 6.\n The 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.\n In total, 1 + 3 + 0 + 0 = 4 moves were used.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2038, - "title": "Remove Colored Pieces if Both Neighbors are the Same Color", - "question": "class Solution:\n def winnerOfGame(self, colors: str) -> bool:\n \"\"\"\n 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.\n Alice and Bob are playing a game where they take alternating turns removing pieces from the line. In this game, Alice moves first.\n Alice 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'.\n Bob 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'.\n Alice and Bob cannot remove pieces from the edge of the line.\n If a player cannot make a move on their turn, that player loses and the other player wins.\n Assuming Alice and Bob play optimally, return true if Alice wins, or return false if Bob wins.\n Example 1:\n Input: colors = \"AAABABB\"\n Output: true\n Explanation:\n AAABABB -> AABABB\n Alice moves first.\n She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.\n Now it's Bob's turn.\n Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.\n Thus, Alice wins, so return true.\n Example 2:\n Input: colors = \"AA\"\n Output: false\n Explanation:\n Alice has her turn first.\n There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.\n Thus, Bob wins, so return false.\n Example 3:\n Input: colors = \"ABBBBBBBAAA\"\n Output: false\n Explanation:\n ABBBBBBBAAA -> ABBBBBBBAA\n Alice moves first.\n Her only option is to remove the second to last 'A' from the right.\n ABBBBBBBAA -> ABBBBBBAA\n Next is Bob's turn.\n He has many options for which 'B' piece to remove. He can pick any.\n On Alice's second turn, she has no more pieces that she can remove.\n Thus, Bob wins, so return false.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2040, - "title": "Kth Smallest Product of Two Sorted Arrays", - "question": "class Solution:\n def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:\n \"\"\"\n 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:\n Input: nums1 = [2,5], nums2 = [3,4], k = 2\n Output: 8\n Explanation: The 2 smallest products are:\n - nums1[0] * nums2[0] = 2 * 3 = 6\n - nums1[0] * nums2[1] = 2 * 4 = 8\n The 2nd smallest product is 8.\n Example 2:\n Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6\n Output: 0\n Explanation: 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\n The 6th smallest product is 0.\n Example 3:\n Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3\n Output: -6\n Explanation: 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\n The 3rd smallest product is -6.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2039, - "title": "The Time When the Network Becomes Idle", - "question": "class Solution:\n def networkBecomesIdle(self, edges: List[List[int]], patience: List[int]) -> int:\n \"\"\"\n 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.\n All 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.\n The 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.\n At 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:\n If 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.\n Otherwise, no more resending will occur from this server.\n The network becomes idle when there are no messages passing between servers or arriving at servers.\n Return the earliest second starting from which the network becomes idle.\n Example 1:\n Input: edges = [[0,1],[1,2]], patience = [0,2,1]\n Output: 8\n Explanation:\n At (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 At 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 At 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 ...\n At second 4,\n - The reply 2A arrives at server 2. No more resending will occur from server 2.\n ...\n At second 7, reply 2D arrives at server 2.\n Starting from the beginning of the second 8, there are no messages passing between servers or arriving at servers.\n This is the time when the network becomes idle.\n Example 2:\n Input: edges = [[0,1],[0,2],[1,2]], patience = [0,10,10]\n Output: 3\n Explanation: Data servers 1 and 2 receive a reply back at the beginning of second 2.\n From the beginning of the second 3, the network becomes idle.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2027, - "title": "Minimum Moves to Convert String", - "question": "class Solution:\n def minimumMoves(self, s: str) -> int:\n \"\"\"\n You are given a string s consisting of n characters which are either 'X' or 'O'.\n A 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.\n Return the minimum number of moves required so that all the characters of s are converted to 'O'.\n Example 1:\n Input: s = \"XXX\"\n Output: 1\n Explanation: XXX -> OOO\n We select all the 3 characters and convert them in one move.\n Example 2:\n Input: s = \"XXOX\"\n Output: 2\n Explanation: XXOX -> OOOX -> OOOO\n We select the first 3 characters in the first move, and convert them to 'O'.\n Then we select the last 3 characters and convert them so that the final string contains all 'O's.\n Example 3:\n Input: s = \"OOOO\"\n Output: 0\n Explanation: There are no 'X's in s to convert.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2028, - "title": "Find Missing Observations", - "question": "class Solution:\n def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]:\n \"\"\"\n 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.\n You 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.\n Return 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.\n The average value of a set of k numbers is the sum of the numbers divided by k.\n Note that mean is an integer, so the sum of the n + m rolls should be divisible by n + m.\n Example 1:\n Input: rolls = [3,2,4,3], mean = 4, n = 2\n Output: [6,6]\n Explanation: The mean of all n + m rolls is (3 + 2 + 4 + 3 + 6 + 6) / 6 = 4.\n Example 2:\n Input: rolls = [1,5,6], mean = 3, n = 4\n Output: [2,3,2,2]\n Explanation: The mean of all n + m rolls is (1 + 5 + 6 + 2 + 3 + 2 + 2) / 7 = 3.\n Example 3:\n Input: rolls = [1,2,3,4], mean = 6, n = 4\n Output: []\n Explanation: It is impossible for the mean to be 6 no matter what the 4 missing rolls are.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2029, - "title": "Stone Game IX", - "question": "class Solution:\n def stoneGameIX(self, stones: List[int]) -> bool:\n \"\"\"\n 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.\n Alice 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).\n Assuming both players play optimally, return true if Alice wins and false if Bob wins.\n Example 1:\n Input: stones = [2,1]\n Output: true\n Explanation: The game will be played as follows:\n - Turn 1: Alice can remove either stone.\n - Turn 2: Bob removes the remaining stone. \n The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.\n Example 2:\n Input: stones = [2]\n Output: false\n Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2. \n Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.\n Example 3:\n Input: stones = [5,1,2,4,3]\n Output: false\n Explanation: 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.\n Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2030, - "title": "Smallest K-Length Subsequence With Occurrences of a Letter", - "question": "class Solution:\n def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str:\n \"\"\"\n You are given a string s, an integer k, a letter letter, and an integer repetition.\n Return the lexicographically smallest subsequence of s of length k that has the letter letter appear at least repetition times. The test cases are generated so that the letter appears in s at least repetition times.\n A 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 A string a is lexicographically smaller than a string b if in the first position where a and b differ, string a has a letter that appears earlier in the alphabet than the corresponding letter in b.\n Example 1:\n Input: s = \"leet\", k = 3, letter = \"e\", repetition = 1\n Output: \"eet\"\n Explanation: There are four subsequences of length 3 that have the letter 'e' appear at least 1 time:\n - \"lee\" (from \"leet\")\n - \"let\" (from \"leet\")\n - \"let\" (from \"leet\")\n - \"eet\" (from \"leet\")\n The lexicographically smallest subsequence among them is \"eet\".\n Example 2:\n Input: s = \"leetcode\", k = 4, letter = \"e\", repetition = 2\n Output: \"ecde\"\n Explanation: \"ecde\" is the lexicographically smallest subsequence of length 4 that has the letter \"e\" appear at least 2 times.\n Example 3:\n Input: s = \"bb\", k = 2, letter = \"b\", repetition = 2\n Output: \"bb\"\n Explanation: \"bb\" is the only subsequence of length 2 that has the letter \"b\" appear at least 2 times.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2032, - "title": "Two Out of Three", - "question": "class Solution:\n def twoOutOfThree(self, nums1: List[int], nums2: List[int], nums3: List[int]) -> List[int]:\n \"\"\"\n 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:\n Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3]\n Output: [3,2]\n Explanation: The values that are present in at least two arrays are:\n - 3, in all three arrays.\n - 2, in nums1 and nums2.\n Example 2:\n Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2]\n Output: [2,3,1]\n Explanation: The values that are present in at least two arrays are:\n - 2, in nums2 and nums3.\n - 3, in nums1 and nums2.\n - 1, in nums1 and nums3.\n Example 3:\n Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5]\n Output: []\n Explanation: No value is present in at least two arrays.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2033, - "title": "Minimum Operations to Make a Uni-Value Grid", - "question": "class Solution:\n def minOperations(self, grid: List[List[int]], x: int) -> int:\n \"\"\"\n 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.\n A uni-value grid is a grid where all the elements of it are equal.\n Return the minimum number of operations to make the grid uni-value. If it is not possible, return -1.\n Example 1:\n Input: grid = [[2,4],[6,8]], x = 2\n Output: 4\n Explanation: 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.\n A total of 4 operations were used.\n Example 2:\n Input: grid = [[1,5],[2,3]], x = 1\n Output: 5\n Explanation: We can make every element equal to 3.\n Example 3:\n Input: grid = [[1,2],[3,4]], x = 2\n Output: -1\n Explanation: It is impossible to make every element equal.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2034, - "title": "Stock Price Fluctuation ", - "question": "class StockPrice:\n def __init__(self):\n def update(self, timestamp: int, price: int) -> None:\n def current(self) -> int:\n def maximum(self) -> int:\n def minimum(self) -> int:\n \"\"\"\n You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.\n Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.\n Design an algorithm that:\n Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.\n Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.\n Finds the maximum price the stock has been based on the current records.\n Finds the minimum price the stock has been based on the current records.\n Implement the StockPrice class:\n StockPrice() Initializes the object with no price records.\n void update(int timestamp, int price) Updates the price of the stock at the given timestamp.\n int current() Returns the latest price of the stock.\n int maximum() Returns the maximum price of the stock.\n int minimum() Returns the minimum price of the stock.\n Example 1:\n Input\n [\"StockPrice\", \"update\", \"update\", \"current\", \"maximum\", \"update\", \"maximum\", \"update\", \"minimum\"]\n [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]\n Output\n [null, null, null, 5, 10, null, 5, null, 2]\n Explanation\n StockPrice stockPrice = new StockPrice();\n stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].\n stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].\n stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.\n stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.\n stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3.\n // Timestamps are [1,2] with corresponding prices [3,5].\n stockPrice.maximum(); // return 5, the maximum price is 5 after the correction.\n stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].\n stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2035, - "title": "Partition Array Into Two Arrays to Minimize Sum Difference", - "question": "class Solution:\n def minimumDifference(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n Return the minimum possible absolute difference.\n Example 1:\n Input: nums = [3,9,7,3]\n Output: 2\n Explanation: One optimal partition is: [3,9] and [7,3].\n The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.\n Example 2:\n Input: nums = [-36,36]\n Output: 72\n Explanation: One optimal partition is: [-36] and [36].\n The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.\n Example 3:\n Input: nums = [2,-1,0,4,-2,-9]\n Output: 0\n Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].\n The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2053, - "title": "Kth Distinct String in an Array", - "question": "class Solution:\n def kthDistinct(self, arr: List[str], k: int) -> str:\n \"\"\"\n A distinct string is a string that is present only once in an array.\n Given 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 \"\".\n Note that the strings are considered in the order in which they appear in the array.\n Example 1:\n Input: arr = [\"d\",\"b\",\"c\",\"b\",\"c\",\"a\"], k = 2\n Output: \"a\"\n Explanation:\n The 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.\n Since k == 2, \"a\" is returned. \n Example 2:\n Input: arr = [\"aaa\",\"aa\",\"a\"], k = 1\n Output: \"aaa\"\n Explanation:\n All strings in arr are distinct, so the 1st string \"aaa\" is returned.\n Example 3:\n Input: arr = [\"a\",\"b\",\"a\"], k = 3\n Output: \"\"\n Explanation:\n The only distinct string is \"b\". Since there are fewer than 3 distinct strings, we return an empty string \"\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2054, - "title": "Two Best Non-Overlapping Events", - "question": "class Solution:\n def maxTwoEvents(self, events: List[List[int]]) -> int:\n \"\"\"\n You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.\n Return this maximum sum.\n Note that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.\n Example 1:\n Input: events = [[1,3,2],[4,5,2],[2,4,3]]\n Output: 4\n Explanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.\n Example 2:\n Input: events = [[1,3,2],[4,5,2],[1,5,5]]\n Output: 5\n Explanation: Choose event 2 for a sum of 5.\n Example 3:\n Input: events = [[1,5,3],[1,5,1],[6,6,5]]\n Output: 8\n Explanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2055, - "title": "Plates Between Candles", - "question": "class Solution:\n def platesBetweenCandles(self, s: str, queries: List[List[int]]) -> List[int]:\n \"\"\"\n 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.\n You 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.\n For 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.\n Return an integer array answer where answer[i] is the answer to the ith query.\n Example 1:\n Input: s = \"**|**|***|\", queries = [[2,5],[5,9]]\n Output: [2,3]\n Explanation:\n - queries[0] has two plates between candles.\n - queries[1] has three plates between candles.\n Example 2:\n Input: s = \"***|**|*****|**||**|*\", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]\n Output: [9,0,0,0,0]\n Explanation:\n - queries[0] has nine plates between candles.\n - The other queries have zero plates between candles.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2056, - "title": "Number of Valid Move Combinations On Chessboard", - "question": "class Solution:\n def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int:\n \"\"\"\n 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.\n When making a move for a piece, you choose a destination square that the piece will travel toward and stop on.\n A 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).\n A 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).\n A 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).\n You 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.\n Return the number of valid move combinations\u200b\u200b\u200b\u200b\u200b.\n Notes:\n No two pieces will start in the same square.\n You may choose the square a piece is already on as its destination.\n If 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:\n Input: pieces = [\"rook\"], positions = [[1,1]]\n Output: 15\n Explanation: The image above shows the possible squares the piece can move to.\n Example 2:\n Input: pieces = [\"queen\"], positions = [[1,1]]\n Output: 22\n Explanation: The image above shows the possible squares the piece can move to.\n Example 3:\n Input: pieces = [\"bishop\"], positions = [[4,3]]\n Output: 12\n Explanation: The image above shows the possible squares the piece can move to.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2042, - "title": "Check if Numbers Are Ascending in a Sentence", - "question": "class Solution:\n def areNumbersAscending(self, s: str) -> bool:\n \"\"\"\n 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.\n For 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.\n Given 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).\n Return true if so, or false otherwise.\n Example 1:\n Input: s = \"1 box has 3 blue 4 red 6 green and 12 yellow marbles\"\n Output: true\n Explanation: The numbers in s are: 1, 3, 4, 6, 12.\n They are strictly increasing from left to right: 1 < 3 < 4 < 6 < 12.\n Example 2:\n Input: s = \"hello world 5 x 5\"\n Output: false\n Explanation: The numbers in s are: 5, 5. They are not strictly increasing.\n Example 3:\n Input: s = \"sunset is at 7 51 pm overnight lows will be in the low 50 and 60 s\"\n Output: false\n Explanation: The numbers in s are: 7, 51, 50, 60. They are not strictly increasing.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2043, - "title": "Simple Bank System", - "question": "class Bank:\n def __init__(self, balance: List[int]):\n def transfer(self, account1: int, account2: int, money: int) -> bool:\n def deposit(self, account: int, money: int) -> bool:\n def withdraw(self, account: int, money: int) -> bool:\n \"\"\"\n You have been tasked with writing a program for a popular bank that will automate all its incoming transactions (transfer, deposit, and withdraw). The bank has n accounts numbered from 1 to n. The initial balance of each account is stored in a 0-indexed integer array balance, with the (i + 1)th account having an initial balance of balance[i].\n Execute all the valid transactions. A transaction is valid if:\n The given account number(s) are between 1 and n, and\n The amount of money withdrawn or transferred from is less than or equal to the balance of the account.\n Implement the Bank class:\n Bank(long[] balance) Initializes the object with the 0-indexed integer array balance.\n boolean transfer(int account1, int account2, long money) Transfers money dollars from the account numbered account1 to the account numbered account2. Return true if the transaction was successful, false otherwise.\n boolean deposit(int account, long money) Deposit money dollars into the account numbered account. Return true if the transaction was successful, false otherwise.\n boolean withdraw(int account, long money) Withdraw money dollars from the account numbered account. Return true if the transaction was successful, false otherwise.\n Example 1:\n Input\n [\"Bank\", \"withdraw\", \"transfer\", \"deposit\", \"transfer\", \"withdraw\"]\n [[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]]\n Output\n [null, true, true, true, false, false]\n Explanation\n Bank bank = new Bank([10, 100, 20, 50, 30]);\n bank.withdraw(3, 10); // return true, account 3 has a balance of $20, so it is valid to withdraw $10.\n // Account 3 has $20 - $10 = $10.\n bank.transfer(5, 1, 20); // return true, account 5 has a balance of $30, so it is valid to transfer $20.\n // Account 5 has $30 - $20 = $10, and account 1 has $10 + $20 = $30.\n bank.deposit(5, 20); // return true, it is valid to deposit $20 to account 5.\n // Account 5 has $10 + $20 = $30.\n bank.transfer(3, 4, 15); // return false, the current balance of account 3 is $10,\n // so it is invalid to transfer $15 from it.\n bank.withdraw(10, 50); // return false, it is invalid because account 10 does not exist.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2044, - "title": "Count Number of Maximum Bitwise-OR Subsets", - "question": "class Solution:\n def countMaxOrSubsets(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n An 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.\n The 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:\n Input: nums = [3,1]\n Output: 2\n Explanation: 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]\n Example 2:\n Input: nums = [2,2,2]\n Output: 7\n Explanation: All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 23 - 1 = 7 total subsets.\n Example 3:\n Input: nums = [3,2,1,5]\n Output: 6\n Explanation: 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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2045, - "title": "Second Minimum Time to Reach Destination", - "question": "class Solution:\n def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:\n \"\"\"\n 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.\n Each 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.\n The second minimum value is defined as the smallest value strictly larger than the minimum value.\n For example the second minimum value of [2, 3, 4] is 3, and the second minimum value of [2, 2, 4] is 4.\n Given n, edges, time, and change, return the second minimum time it will take to go from vertex 1 to vertex n.\n Notes:\n You can go through any vertex any number of times, including 1 and n.\n You can assume that when the journey starts, all signals have just turned green.\n Example 1:\n Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5\n Output: 13\n Explanation:\n The figure on the left shows the given graph.\n The blue path in the figure on the right is the minimum time path.\n The 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\n Hence the minimum time needed is 6 minutes.\n The 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\n Hence the second minimum time is 13 minutes. \n Example 2:\n Input: n = 2, edges = [[1,2]], time = 3, change = 2\n Output: 11\n Explanation:\n The minimum time path is 1 -> 2 with time = 3 minutes.\n The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2047, - "title": "Number of Valid Words in a Sentence", - "question": "class Solution:\n def countValidWords(self, sentence: str) -> int:\n \"\"\"\n 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 ' '.\n A token is a valid word if all three of the following are true:\n It only contains lowercase letters, hyphens, and/or punctuation (no digits).\n There 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).\n There 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).\n Examples of valid words include \"a-b.\", \"afad\", \"ba-c\", \"a!\", and \"!\".\n Given a string sentence, return the number of valid words in sentence.\n Example 1:\n Input: sentence = \"cat and dog\"\n Output: 3\n Explanation: The valid words in the sentence are \"cat\", \"and\", and \"dog\".\n Example 2:\n Input: sentence = \"!this 1-s b8d!\"\n Output: 0\n Explanation: 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.\n Example 3:\n Input: sentence = \"alice and bob are playing stone-game10\"\n Output: 5\n Explanation: The valid words in the sentence are \"alice\", \"and\", \"bob\", \"are\", and \"playing\".\n \"stone-game10\" is invalid because it contains digits.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2048, - "title": "Next Greater Numerically Balanced Number", - "question": "class Solution:\n def nextBeautifulNumber(self, n: int) -> int:\n \"\"\"\n 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.\n Given an integer n, return the smallest numerically balanced number strictly greater than n.\n Example 1:\n Input: n = 1\n Output: 22\n Explanation: \n 22 is numerically balanced since:\n - The digit 2 occurs 2 times. \n It is also the smallest numerically balanced number strictly greater than 1.\n Example 2:\n Input: n = 1000\n Output: 1333\n Explanation: \n 1333 is numerically balanced since:\n - The digit 1 occurs 1 time.\n - The digit 3 occurs 3 times. \n It is also the smallest numerically balanced number strictly greater than 1000.\n Note that 1022 cannot be the answer because 0 appeared more than 0 times.\n Example 3:\n Input: n = 3000\n Output: 3133\n Explanation: \n 3133 is numerically balanced since:\n - The digit 1 occurs 1 time.\n - The digit 3 occurs 3 times.\n It is also the smallest numerically balanced number strictly greater than 3000.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2049, - "title": "Count Nodes With the Highest Score", - "question": "class Solution:\n def countHighestScoreNodes(self, parents: List[int]) -> int:\n \"\"\"\n 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.\n Each 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.\n Return the number of nodes that have the highest score.\n Example 1:\n Input: parents = [-1,2,0,2,0]\n Output: 3\n Explanation:\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\n The highest score is 4, and three nodes (node 1, node 3, and node 4) have the highest score.\n Example 2:\n Input: parents = [-1,2,0]\n Output: 2\n Explanation:\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\n The highest score is 2, and two nodes (node 0 and node 1) have the highest score.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2050, - "title": "Parallel Courses III", - "question": "class Solution:\n def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:\n \"\"\"\n 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.\n You must find the minimum number of months needed to complete all the courses following these rules:\n You may start taking a course at any time if the prerequisites are met.\n Any number of courses can be taken at the same time.\n Return the minimum number of months needed to complete all the courses.\n Note: 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:\n Input: n = 3, relations = [[1,3],[2,3]], time = [3,2,5]\n Output: 8\n Explanation: The figure above represents the given graph and the time required to complete each course. \n We start course 1 and course 2 simultaneously at month 0.\n Course 1 takes 3 months and course 2 takes 2 months to complete respectively.\n Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.\n Example 2:\n Input: n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]\n Output: 12\n Explanation: The figure above represents the given graph and the time required to complete each course.\n You can start courses 1, 2, and 3 at month 0.\n You can complete them after 1, 2, and 3 months respectively.\n Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.\n Course 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.\n Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2068, - "title": "Check Whether Two Strings are Almost Equivalent", - "question": "class Solution:\n def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:\n \"\"\"\n 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.\n Given two strings word1 and word2, each of length n, return true if word1 and word2 are almost equivalent, or false otherwise.\n The frequency of a letter x is the number of times it occurs in the string.\n Example 1:\n Input: word1 = \"aaaa\", word2 = \"bccb\"\n Output: false\n Explanation: There are 4 'a's in \"aaaa\" but 0 'a's in \"bccb\".\n The difference is 4, which is more than the allowed 3.\n Example 2:\n Input: word1 = \"abcdeef\", word2 = \"abaaacc\"\n Output: true\n Explanation: 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.\n Example 3:\n Input: word1 = \"cccddabba\", word2 = \"babababab\"\n Output: true\n Explanation: 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 \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2069, - "title": "Walking Robot Simulation II", - "question": "class Robot:\n def __init__(self, width: int, height: int):\n def step(self, num: int) -> None:\n def getPos(self) -> List[int]:\n def getDir(self) -> str:\n \"\"\"\n A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions (\"North\", \"East\", \"South\", and \"West\"). A robot is initially at cell (0, 0) facing direction \"East\".\n The robot can be instructed to move for a specific number of steps. For each step, it does the following.\n Attempts to move forward one cell in the direction it is facing.\n If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.\n After the robot finishes moving the number of steps required, it stops and awaits the next instruction.\n Implement the Robot class:\n Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing \"East\".\n void step(int num) Instructs the robot to move forward num steps.\n int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].\n String getDir() Returns the current direction of the robot, \"North\", \"East\", \"South\", or \"West\".\n Example 1:\n Input\n [\"Robot\", \"step\", \"step\", \"getPos\", \"getDir\", \"step\", \"step\", \"step\", \"getPos\", \"getDir\"]\n [[6, 3], [2], [2], [], [], [2], [1], [4], [], []]\n Output\n [null, null, null, [4, 0], \"East\", null, null, null, [1, 2], \"West\"]\n Explanation\n Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.\n robot.step(2); // It moves two steps East to (2, 0), and faces East.\n robot.step(2); // It moves two steps East to (4, 0), and faces East.\n robot.getPos(); // return [4, 0]\n robot.getDir(); // return \"East\"\n robot.step(2); // It moves one step East to (5, 0), and faces East.\n // Moving the next step East would be out of bounds, so it turns and faces North.\n // Then, it moves one step North to (5, 1), and faces North.\n robot.step(1); // It moves one step North to (5, 2), and faces North (not West).\n robot.step(4); // Moving the next step North would be out of bounds, so it turns and faces West.\n // Then, it moves four steps West to (1, 2), and faces West.\n robot.getPos(); // return [1, 2]\n robot.getDir(); // return \"West\"\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2070, - "title": "Most Beautiful Item for Each Query", - "question": "class Solution:\n def maximumBeauty(self, items: List[List[int]], queries: List[int]) -> List[int]:\n \"\"\"\n You are given a 2D integer array items where items[i] = [pricei, beautyi] denotes the price and beauty of an item respectively.\n You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.\n Return an array answer of the same length as queries where answer[j] is the answer to the jth query.\n Example 1:\n Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]\n Output: [2,4,5,5,6,6]\n Explanation:\n - For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.\n - For queries[1]=2, the items which can be considered are [1,2] and [2,4]. \n The maximum beauty among them is 4.\n - For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].\n The maximum beauty among them is 5.\n - For queries[4]=5 and queries[5]=6, all items can be considered.\n Hence, the answer for them is the maximum beauty of all items, i.e., 6.\n Example 2:\n Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]\n Output: [4]\n Explanation: \n The price of every item is equal to 1, so we choose the item with the maximum beauty 4. \n Note that multiple items can have the same price and/or beauty. \n Example 3:\n Input: items = [[10,1000]], queries = [5]\n Output: [0]\n Explanation:\n No item has a price less than or equal to 5, so no item can be chosen.\n Hence, the answer to the query is 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2071, - "title": "Maximum Number of Tasks You Can Assign", - "question": "class Solution:\n def maxTaskAssign(self, tasks: List[int], workers: List[int], pills: int, strength: int) -> int:\n \"\"\"\n 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]).\n Additionally, 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.\n Given 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:\n Input: tasks = [3,2,1], workers = [0,3,3], pills = 1, strength = 1\n Output: 3\n Explanation:\n We 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)\n Example 2:\n Input: tasks = [5,4], workers = [0,0,0], pills = 1, strength = 5\n Output: 1\n Explanation:\n We 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)\n Example 3:\n Input: tasks = [10,15,30], workers = [0,10,10,10,10], pills = 3, strength = 10\n Output: 2\n Explanation:\n We 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)\n The last pill is not given because it will not make any worker strong enough for the last task.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2057, - "title": "Smallest Index With Equal Value", - "question": "class Solution:\n def smallestEqual(self, nums: List[int]) -> int:\n \"\"\"\n 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.\n x mod y denotes the remainder when x is divided by y.\n Example 1:\n Input: nums = [0,1,2]\n Output: 0\n Explanation: \n i=0: 0 mod 10 = 0 == nums[0].\n i=1: 1 mod 10 = 1 == nums[1].\n i=2: 2 mod 10 = 2 == nums[2].\n All indices have i mod 10 == nums[i], so we return the smallest index 0.\n Example 2:\n Input: nums = [4,3,2,1]\n Output: 2\n Explanation: \n i=0: 0 mod 10 = 0 != nums[0].\n i=1: 1 mod 10 = 1 != nums[1].\n i=2: 2 mod 10 = 2 == nums[2].\n i=3: 3 mod 10 = 3 != nums[3].\n 2 is the only index which has i mod 10 == nums[i].\n Example 3:\n Input: nums = [1,2,3,4,5,6,7,8,9,0]\n Output: -1\n Explanation: No index satisfies i mod 10 == nums[i].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2058, - "title": "Find the Minimum and Maximum Number of Nodes Between Critical Points", - "question": "class Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n \"\"\"\n A critical point in a linked list is defined as either a local maxima or a local minima.\n A node is a local maxima if the current node has a value strictly greater than the previous node and the next node.\n A node is a local minima if the current node has a value strictly smaller than the previous node and the next node.\n Note that a node can only be a local maxima/minima if there exists both a previous node and a next node.\n Given 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:\n Input: head = [3,1]\n Output: [-1,-1]\n Explanation: There are no critical points in [3,1].\n Example 2:\n Input: head = [5,3,1,2,5,1,2]\n Output: [1,3]\n Explanation: 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.\n The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.\n The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.\n Example 3:\n Input: head = [1,3,2,2,3,2,2,2,7]\n Output: [3,3]\n Explanation: 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.\n Both the minimum and maximum distances are between the second and the fifth node.\n Thus, minDistance and maxDistance is 5 - 2 = 3.\n Note that the last node is not considered a local maxima because it does not have a next node.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2059, - "title": "Minimum Operations to Convert Number", - "question": "class Solution:\n def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:\n \"\"\"\n 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:\n If 0 <= x <= 1000, then for any index i in the array (0 <= i < nums.length), you can set x to any of the following:\n x + nums[i]\n x - nums[i]\n x ^ nums[i] (bitwise-XOR)\n Note 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.\n Return the minimum number of operations needed to convert x = start into goal, and -1 if it is not possible.\n Example 1:\n Input: nums = [2,4,12], start = 2, goal = 12\n Output: 2\n Explanation: We can go from 2 \u2192 14 \u2192 12 with the following 2 operations.\n - 2 + 12 = 14\n - 14 - 2 = 12\n Example 2:\n Input: nums = [3,5,7], start = 0, goal = -4\n Output: 2\n Explanation: We can go from 0 \u2192 3 \u2192 -4 with the following 2 operations. \n - 0 + 3 = 3\n - 3 - 7 = -4\n Note that the last operation sets x out of the range 0 <= x <= 1000, which is valid.\n Example 3:\n Input: nums = [2,8,16], start = 0, goal = 1\n Output: -1\n Explanation: There is no way to convert 0 into 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2060, - "title": "Check if an Original String Exists Given Two Encoded Strings", - "question": "class Solution:\n def possiblyEquals(self, s1: str, s2: str) -> bool:\n \"\"\"\n An original string, consisting of lowercase English letters, can be encoded by the following steps:\n Arbitrarily split it into a sequence of some number of non-empty substrings.\n Arbitrarily choose some elements (possibly none) of the sequence, and replace each with its length (as a numeric string).\n Concatenate the sequence as the encoded string.\n For example, one way to encode an original string \"abcdefghijklmnop\" might be:\n Split it as a sequence: [\"ab\", \"cdefghijklmn\", \"o\", \"p\"].\n Choose the second and third elements to be replaced by their lengths, respectively. The sequence becomes [\"ab\", \"12\", \"1\", \"p\"].\n Concatenate the elements of the sequence to get the encoded string: \"ab121p\".\n Given 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.\n Note: The test cases are generated such that the number of consecutive digits in s1 and s2 does not exceed 3.\n Example 1:\n Input: s1 = \"internationalization\", s2 = \"i18n\"\n Output: true\n Explanation: 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\n Example 2:\n Input: s1 = \"l123e\", s2 = \"44\"\n Output: true\n Explanation: 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.\n Example 3:\n Input: s1 = \"a5b\", s2 = \"c5b\"\n Output: false\n Explanation: 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 \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2062, - "title": "Count Vowel Substrings of a String", - "question": "class Solution:\n def countVowelSubstrings(self, word: str) -> int:\n \"\"\"\n A substring is a contiguous (non-empty) sequence of characters within a string.\n A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.\n Given a string word, return the number of vowel substrings in word.\n Example 1:\n Input: word = \"aeiouu\"\n Output: 2\n Explanation: The vowel substrings of word are as follows (underlined):\n - \"aeiouu\"\n - \"aeiouu\"\n Example 2:\n Input: word = \"unicornarihan\"\n Output: 0\n Explanation: Not all 5 vowels are present, so there are no vowel substrings.\n Example 3:\n Input: word = \"cuaieuouac\"\n Output: 7\n Explanation: The vowel substrings of word are as follows (underlined):\n - \"cuaieuouac\"\n - \"cuaieuouac\"\n - \"cuaieuouac\"\n - \"cuaieuouac\"\n - \"cuaieuouac\"\n - \"cuaieuouac\"\n - \"cuaieuouac\"\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2063, - "title": "Vowels of All Substrings", - "question": "class Solution:\n def countVowels(self, word: str) -> int:\n \"\"\"\n Given a string word, return the sum of the number of vowels ('a', 'e', 'i', 'o', and 'u') in every substring of word.\n A substring is a contiguous (non-empty) sequence of characters within a string.\n Note: 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:\n Input: word = \"aba\"\n Output: 6\n Explanation: \n All 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\n Hence, the total sum of vowels = 0 + 1 + 1 + 1 + 1 + 2 = 6. \n Example 2:\n Input: word = \"abc\"\n Output: 3\n Explanation: \n All 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\n Hence, the total sum of vowels = 1 + 1 + 1 + 0 + 0 + 0 = 3.\n Example 3:\n Input: word = \"ltcd\"\n Output: 0\n Explanation: There are no vowels in any substring of \"ltcd\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2064, - "title": "Minimized Maximum of Products Distributed to Any Store", - "question": "class Solution:\n def minimizedMaximum(self, n: int, quantities: List[int]) -> int:\n \"\"\"\n 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.\n You need to distribute all products to the retail stores following these rules:\n A store can only be given at most one product type but can be given any amount of it.\n After 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.\n Return the minimum possible x.\n Example 1:\n Input: n = 6, quantities = [11,6]\n Output: 3\n Explanation: 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\n The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.\n Example 2:\n Input: n = 7, quantities = [15,10,10]\n Output: 5\n Explanation: 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\n The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.\n Example 3:\n Input: n = 1, quantities = [100000]\n Output: 100000\n Explanation: The only optimal way is:\n - The 100000 products of type 0 are distributed to the only store.\n The maximum number of products given to any store is max(100000) = 100000.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2065, - "title": "Maximum Path Quality of a Graph", - "question": "class Solution:\n def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:\n \"\"\"\n 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.\n A 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).\n Return the maximum quality of a valid path.\n Note: There are at most four edges connected to each node.\n Example 1:\n Input: values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49\n Output: 75\n Explanation:\n One possible path is 0 -> 1 -> 0 -> 3 -> 0. The total time taken is 10 + 10 + 10 + 10 = 40 <= 49.\n The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.\n Example 2:\n Input: values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30\n Output: 25\n Explanation:\n One possible path is 0 -> 3 -> 0. The total time taken is 10 + 10 = 20 <= 30.\n The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.\n Example 3:\n Input: values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50\n Output: 7\n Explanation:\n One possible path is 0 -> 1 -> 3 -> 1 -> 0. The total time taken is 10 + 13 + 13 + 10 = 46 <= 50.\n The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2085, - "title": "Count Common Words With One Occurrence", - "question": "class Solution:\n def countWords(self, words1: List[str], words2: List[str]) -> int:\n \"\"\"\n 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:\n Input: words1 = [\"leetcode\",\"is\",\"amazing\",\"as\",\"is\"], words2 = [\"amazing\",\"leetcode\",\"is\"]\n Output: 2\n Explanation:\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.\n Thus, there are 2 strings that appear exactly once in each of the two arrays.\n Example 2:\n Input: words1 = [\"b\",\"bb\",\"bbb\"], words2 = [\"a\",\"aa\",\"aaa\"]\n Output: 0\n Explanation: There are no strings that appear in each of the two arrays.\n Example 3:\n Input: words1 = [\"a\",\"ab\"], words2 = [\"a\",\"a\",\"a\",\"ab\"]\n Output: 1\n Explanation: The only string that appears exactly once in each of the two arrays is \"ab\".\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2086, - "title": "Minimum Number of Food Buckets to Feed the Hamsters", - "question": "class Solution:\n def minimumBuckets(self, hamsters: str) -> int:\n \"\"\"\n 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.\n You 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.\n Return 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:\n Input: hamsters = \"H..H\"\n Output: 2\n Explanation: We place two food buckets at indices 1 and 2.\n It can be shown that if we place only one food bucket, one of the hamsters will not be fed.\n Example 2:\n Input: hamsters = \".H.H.\"\n Output: 1\n Explanation: We place one food bucket at index 2.\n Example 3:\n Input: hamsters = \".HHH.\"\n Output: -1\n Explanation: If we place a food bucket at every empty index as shown, the hamster at index 2 will not be able to eat.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2087, - "title": "Minimum Cost Homecoming of a Robot in a Grid", - "question": "class Solution:\n def minCost(self, startPos: List[int], homePos: List[int], rowCosts: List[int], colCosts: List[int]) -> int:\n \"\"\"\n 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).\n The 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.\n If the robot moves up or down into a cell whose row is r, then this move costs rowCosts[r].\n If the robot moves left or right into a cell whose column is c, then this move costs colCosts[c].\n Return the minimum total cost for this robot to return home.\n Example 1:\n Input: startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]\n Output: 18\n Explanation: One optimal path is that:\n Starting 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.\n The total cost is 3 + 2 + 6 + 7 = 18\n Example 2:\n Input: startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]\n Output: 0\n Explanation: The robot is already at its home. Since no moves occur, the total cost is 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2088, - "title": "Count Fertile Pyramids in a Land", - "question": "class Solution:\n def countPyramids(self, grid: List[List[int]]) -> int:\n \"\"\"\n 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.\n A pyramidal plot of land can be defined as a set of cells with the following criteria:\n The number of cells in the set has to be greater than 1 and all cells must be fertile.\n The 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).\n An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:\n The number of cells in the set has to be greater than 1 and all cells must be fertile.\n The 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).\n Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.\n Given 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:\n Input: grid = [[0,1,1,0],[1,1,1,1]]\n Output: 2\n Explanation: The 2 possible pyramidal plots are shown in blue and red respectively.\n There are no inverse pyramidal plots in this grid. \n Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.\n Example 2:\n Input: grid = [[1,1,1],[1,1,1]]\n Output: 2\n Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red. \n Hence the total number of plots is 1 + 1 = 2.\n Example 3:\n Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]\n Output: 13\n Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.\n There are 6 inverse pyramidal plots, 2 of which are shown in the last figure.\n The total number of plots is 7 + 6 = 13.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2073, - "title": "Time Needed to Buy Tickets", - "question": "class Solution:\n def timeRequiredToBuy(self, tickets: List[int], k: int) -> int:\n \"\"\"\n 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.\n You 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].\n Each 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.\n Return the time taken for the person at position k (0-indexed) to finish buying tickets.\n Example 1:\n Input: tickets = [2,3,2], k = 2\n Output: 6\n Explanation: \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].\n The person at position 2 has successfully bought 2 tickets and it took 3 + 3 = 6 seconds.\n Example 2:\n Input: tickets = [5,1,1,1], k = 0\n Output: 8\n Explanation:\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.\n The person at position 0 has successfully bought 5 tickets and it took 4 + 1 + 1 + 1 + 1 = 8 seconds.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2074, - "title": "Reverse Nodes in Even Length Groups", - "question": "class Solution:\n def reverseEvenLengthGroups(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n You are given the head of a linked list.\n The 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,\n The 1st node is assigned to the first group.\n The 2nd and the 3rd nodes are assigned to the second group.\n The 4th, 5th, and 6th nodes are assigned to the third group, and so on.\n Note that the length of the last group may be less than or equal to 1 + the length of the second to last group.\n Reverse the nodes in each group with an even length, and return the head of the modified linked list.\n Example 1:\n Input: head = [5,2,6,3,9,1,7,3,8,4]\n Output: [5,6,2,3,9,1,4,8,3,7]\n Explanation:\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.\n Example 2:\n Input: head = [1,1,0,6]\n Output: [1,0,1,6]\n Explanation:\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.\n Example 3:\n Input: head = [1,1,0,6,5]\n Output: [1,0,1,5,6]\n Explanation:\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 \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2075, - "title": "Decode the Slanted Ciphertext", - "question": "class Solution:\n def decodeCiphertext(self, encodedText: str, rows: int) -> str:\n \"\"\"\n 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.\n originalText is placed first in a top-left to bottom-right manner.\n The 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.\n encodedText is then formed by appending all characters of the matrix in a row-wise fashion.\n The 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.\n For example, if originalText = \"cipher\" and rows = 3, then we encode it in the following manner:\n The 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\".\n Given the encoded string encodedText and number of rows rows, return the original string originalText.\n Note: originalText does not have any trailing spaces ' '. The test cases are generated such that there is only one possible originalText.\n Example 1:\n Input: encodedText = \"ch ie pr\", rows = 3\n Output: \"cipher\"\n Explanation: This is the same example described in the problem description.\n Example 2:\n Input: encodedText = \"iveo eed l te olc\", rows = 4\n Output: \"i love leetcode\"\n Explanation: The figure above denotes the matrix that was used to encode originalText. \n The blue arrows show how we can find originalText from encodedText.\n Example 3:\n Input: encodedText = \"coding\", rows = 1\n Output: \"coding\"\n Explanation: Since there is only 1 row, both originalText and encodedText are the same.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2076, - "title": "Process Restricted Friend Requests", - "question": "class Solution:\n def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]:\n \"\"\"\n You are given an integer n indicating the number of people in a network. Each person is labeled from 0 to n - 1.\n You 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.\n Initially, 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.\n A 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.\n Return a boolean array result, where each result[j] is true if the jth friend request is successful or false if it is not.\n Note: If uj and vj are already direct friends, the request is still successful.\n Example 1:\n Input: n = 3, restrictions = [[0,1]], requests = [[0,2],[2,1]]\n Output: [true,false]\n Explanation:\n Request 0: Person 0 and person 2 can be friends, so they become direct friends. \n Request 1: Person 2 and person 1 cannot be friends since person 0 and person 1 would be indirect friends (1--2--0).\n Example 2:\n Input: n = 3, restrictions = [[0,1]], requests = [[1,2],[0,2]]\n Output: [true,false]\n Explanation:\n Request 0: Person 1 and person 2 can be friends, so they become direct friends.\n Request 1: Person 0 and person 2 cannot be friends since person 0 and person 1 would be indirect friends (0--2--1).\n Example 3:\n Input: n = 5, restrictions = [[0,1],[1,2],[2,3]], requests = [[0,4],[1,2],[3,1],[3,4]]\n Output: [true,false,true,false]\n Explanation:\n Request 0: Person 0 and person 4 can be friends, so they become direct friends.\n Request 1: Person 1 and person 2 cannot be friends since they are directly restricted.\n Request 2: Person 3 and person 1 can be friends, so they become direct friends.\n Request 3: Person 3 and person 4 cannot be friends since person 0 and person 1 would be indirect friends (0--4--3--1).\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2078, - "title": "Two Furthest Houses With Different Colors", - "question": "class Solution:\n def maxDistance(self, colors: List[int]) -> int:\n \"\"\"\n 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.\n Return the maximum distance between two houses with different colors.\n The distance between the ith and jth houses is abs(i - j), where abs(x) is the absolute value of x.\n Example 1:\n Input: colors = [1,1,1,6,1,1,1]\n Output: 3\n Explanation: In the above image, color 1 is blue, and color 6 is red.\n The furthest two houses with different colors are house 0 and house 3.\n House 0 has color 1, and house 3 has color 6. The distance between them is abs(0 - 3) = 3.\n Note that houses 3 and 6 can also produce the optimal answer.\n Example 2:\n Input: colors = [1,8,3,8,3]\n Output: 4\n Explanation: In the above image, color 1 is blue, color 8 is yellow, and color 3 is green.\n The furthest two houses with different colors are house 0 and house 4.\n House 0 has color 1, and house 4 has color 3. The distance between them is abs(0 - 4) = 4.\n Example 3:\n Input: colors = [0,1]\n Output: 1\n Explanation: The furthest two houses with different colors are house 0 and house 1.\n House 0 has color 0, and house 1 has color 1. The distance between them is abs(0 - 1) = 1.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2132, - "title": "Stamping the Grid", - "question": "class Solution:\n def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool:\n \"\"\"\n You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).\n You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements:\n Cover all the empty cells.\n Do not cover any of the occupied cells.\n We can put as many stamps as we want.\n Stamps can overlap with each other.\n Stamps are not allowed to be rotated.\n Stamps must stay completely inside the grid.\n Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.\n Example 1:\n Input: 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\n Output: true\n Explanation: We have two overlapping stamps (labeled 1 and 2 in the image) that are able to cover all the empty cells.\n Example 2:\n Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2 \n Output: false \n Explanation: There is no way to fit the stamps onto all the empty cells without the stamps going outside the grid.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2097, - "title": "Valid Arrangement of Pairs", - "question": "class Solution:\n def validArrangement(self, pairs: List[List[int]]) -> List[List[int]]:\n \"\"\"\n 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.\n Return any valid arrangement of pairs.\n Note: The inputs will be generated such that there exists a valid arrangement of pairs.\n Example 1:\n Input: pairs = [[5,1],[4,5],[11,9],[9,4]]\n Output: [[11,9],[9,4],[4,5],[5,1]]\n Explanation:\n This is a valid arrangement since endi-1 always equals starti.\n end0 = 9 == 9 = start1 \n end1 = 4 == 4 = start2\n end2 = 5 == 5 = start3\n Example 2:\n Input: pairs = [[1,3],[3,2],[2,1]]\n Output: [[1,3],[3,2],[2,1]]\n Explanation:\n This is a valid arrangement since endi-1 always equals starti.\n end0 = 3 == 3 = start1\n end1 = 2 == 2 = start2\n The arrangements [[2,1],[1,3],[3,2]] and [[3,2],[2,1],[1,3]] are also valid.\n Example 3:\n Input: pairs = [[1,2],[1,3],[2,1]]\n Output: [[1,2],[2,1],[1,3]]\n Explanation:\n This is a valid arrangement since endi-1 always equals starti.\n end0 = 2 == 2 = start1\n end1 = 1 == 1 = start2\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2081, - "title": "Sum of k-Mirror Numbers", - "question": "class Solution:\n def kMirror(self, k: int, n: int) -> int:\n \"\"\"\n 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.\n For 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.\n On 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.\n Given the base k and the number n, return the sum of the n smallest k-mirror numbers.\n Example 1:\n Input: k = 2, n = 5\n Output: 25\n Explanation:\n The 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\n Their sum = 1 + 3 + 5 + 7 + 9 = 25. \n Example 2:\n Input: k = 3, n = 7\n Output: 499\n Explanation:\n The 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\n Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.\n Example 3:\n Input: k = 7, n = 17\n Output: 20379000\n Explanation: The 17 smallest 7-mirror numbers are:\n 1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2099, - "title": "Find Subsequence of Length K With the Largest Sum", - "question": "class Solution:\n def maxSubsequence(self, nums: List[int], k: int) -> List[int]:\n \"\"\"\n 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.\n Return any such subsequence as an integer array of length k.\n A 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:\n Input: nums = [2,1,3,3], k = 2\n Output: [3,3]\n Explanation:\n The subsequence has the largest sum of 3 + 3 = 6.\n Example 2:\n Input: nums = [-1,-2,3,4], k = 3\n Output: [-1,3,4]\n Explanation: \n The subsequence has the largest sum of -1 + 3 + 4 = 6.\n Example 3:\n Input: nums = [3,4,3,3], k = 2\n Output: [3,4]\n Explanation:\n The subsequence has the largest sum of 3 + 4 = 7. \n Another possible subsequence is [4, 3].\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2100, - "title": "Find Good Days to Rob the Bank", - "question": "class Solution:\n def goodDaysToRobBank(self, security: List[int], time: int) -> List[int]:\n \"\"\"\n 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.\n The ith day is a good day to rob the bank if:\n There are at least time days before and after the ith day,\n The number of guards at the bank for the time days before i are non-increasing, and\n The number of guards at the bank for the time days after i are non-decreasing.\n More 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].\n Return 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:\n Input: security = [5,3,3,3,5,6,2], time = 2\n Output: [2,3]\n Explanation:\n On day 2, we have security[0] >= security[1] >= security[2] <= security[3] <= security[4].\n On day 3, we have security[1] >= security[2] >= security[3] <= security[4] <= security[5].\n No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.\n Example 2:\n Input: security = [1,1,1,1,1], time = 0\n Output: [0,1,2,3,4]\n Explanation:\n Since time equals 0, every day is a good day to rob the bank, so return every day.\n Example 3:\n Input: security = [1,2,3,4,5,6], time = 2\n Output: []\n Explanation:\n No day has 2 days before it that have a non-increasing number of guards.\n Thus, no day is a good day to rob the bank, so return an empty list.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2101, - "title": "Detonate the Maximum Bombs", - "question": "class Solution:\n def maximumDetonation(self, bombs: List[List[int]]) -> int:\n \"\"\"\n 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.\n The 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.\n You 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.\n Given 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:\n Input: bombs = [[2,1,3],[6,1,4]]\n Output: 2\n Explanation:\n The above figure shows the positions and ranges of the 2 bombs.\n If we detonate the left bomb, the right bomb will not be affected.\n But if we detonate the right bomb, both bombs will be detonated.\n So the maximum bombs that can be detonated is max(1, 2) = 2.\n Example 2:\n Input: bombs = [[1,1,5],[10,10,5]]\n Output: 1\n Explanation:\n Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.\n Example 3:\n Input: bombs = [[1,2,3],[2,3,1],[3,4,2],[4,5,3],[5,6,4]]\n Output: 5\n Explanation:\n The 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.\n Thus all 5 bombs are detonated.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2102, - "title": "Sequentially Ordinal Rank Tracker", - "question": "class SORTracker:\n def __init__(self):\n def add(self, name: str, score: int) -> None:\n def get(self) -> str:\n \"\"\"\n A scenic location is represented by its name and attractiveness score, where name is a unique string among all locations and score is an integer. Locations can be ranked from the best to the worst. The higher the score, the better the location. If the scores of two locations are equal, then the location with the lexicographically smaller name is better.\n You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports:\n Adding scenic locations, one at a time.\n Querying the ith best location of all locations already added, where i is the number of times the system has been queried (including the current query).\n For example, when the system is queried for the 4th time, it returns the 4th best location of all locations already added.\n Note that the test data are generated so that at any time, the number of queries does not exceed the number of locations added to the system.\n Implement the SORTracker class:\n SORTracker() Initializes the tracker system.\n void add(string name, int score) Adds a scenic location with name and score to the system.\n string get() Queries and returns the ith best location, where i is the number of times this method has been invoked (including this invocation).\n Example 1:\n Input\n [\"SORTracker\", \"add\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"add\", \"get\", \"get\"]\n [[], [\"bradford\", 2], [\"branford\", 3], [], [\"alps\", 2], [], [\"orland\", 2], [], [\"orlando\", 3], [], [\"alpine\", 2], [], []]\n Output\n [null, null, null, \"branford\", null, \"alps\", null, \"bradford\", null, \"bradford\", null, \"bradford\", \"orland\"]\n Explanation\n SORTracker tracker = new SORTracker(); // Initialize the tracker system.\n tracker.add(\"bradford\", 2); // Add location with name=\"bradford\" and score=2 to the system.\n tracker.add(\"branford\", 3); // Add location with name=\"branford\" and score=3 to the system.\n tracker.get(); // The sorted locations, from best to worst, are: branford, bradford.\n // Note that branford precedes bradford due to its higher score (3 > 2).\n // This is the 1st time get() is called, so return the best location: \"branford\".\n tracker.add(\"alps\", 2); // Add location with name=\"alps\" and score=2 to the system.\n tracker.get(); // Sorted locations: branford, alps, bradford.\n // Note that alps precedes bradford even though they have the same score (2).\n // This is because \"alps\" is lexicographically smaller than \"bradford\".\n // Return the 2nd best location \"alps\", as it is the 2nd time get() is called.\n tracker.add(\"orland\", 2); // Add location with name=\"orland\" and score=2 to the system.\n tracker.get(); // Sorted locations: branford, alps, bradford, orland.\n // Return \"bradford\", as it is the 3rd time get() is called.\n tracker.add(\"orlando\", 3); // Add location with name=\"orlando\" and score=3 to the system.\n tracker.get(); // Sorted locations: branford, orlando, alps, bradford, orland.\n // Return \"bradford\".\n tracker.add(\"alpine\", 2); // Add location with name=\"alpine\" and score=2 to the system.\n tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"bradford\".\n tracker.get(); // Sorted locations: branford, orlando, alpine, alps, bradford, orland.\n // Return \"orland\".\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2089, - "title": "Find Target Indices After Sorting Array", - "question": "class Solution:\n def targetIndices(self, nums: List[int], target: int) -> List[int]:\n \"\"\"\n You are given a 0-indexed integer array nums and a target element target.\n A target index is an index i such that nums[i] == target.\n Return 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:\n Input: nums = [1,2,5,2,3], target = 2\n Output: [1,2]\n Explanation: After sorting, nums is [1,2,2,3,5].\n The indices where nums[i] == 2 are 1 and 2.\n Example 2:\n Input: nums = [1,2,5,2,3], target = 3\n Output: [3]\n Explanation: After sorting, nums is [1,2,2,3,5].\n The index where nums[i] == 3 is 3.\n Example 3:\n Input: nums = [1,2,5,2,3], target = 5\n Output: [4]\n Explanation: After sorting, nums is [1,2,2,3,5].\n The index where nums[i] == 5 is 4.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2090, - "title": "K Radius Subarray Averages", - "question": "class Solution:\n def getAverages(self, nums: List[int], k: int) -> List[int]:\n \"\"\"\n You are given a 0-indexed array nums of n integers, and an integer k.\n The 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.\n Build and return an array avgs of length n where avgs[i] is the k-radius average for the subarray centered at index i.\n The 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.\n For 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:\n Input: nums = [7,4,3,9,1,8,5,2,6], k = 3\n Output: [-1,-1,-1,5,4,4,-1,-1,-1]\n Explanation:\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.\n Example 2:\n Input: nums = [100000], k = 0\n Output: [100000]\n Explanation:\n - The sum of the subarray centered at index 0 with radius 0 is: 100000.\n avg[0] = 100000 / 1 = 100000.\n Example 3:\n Input: nums = [8], k = 100000\n Output: [-1]\n Explanation: \n - avg[0] is -1 because there are less than k elements before and after index 0.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2091, - "title": "Removing Minimum and Maximum From Array", - "question": "class Solution:\n def minimumDeletions(self, nums: List[int]) -> int:\n \"\"\"\n You are given a 0-indexed array of distinct integers nums.\n There 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.\n A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.\n Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.\n Example 1:\n Input: nums = [2,10,7,5,4,1,8,6]\n Output: 5\n Explanation: \n The minimum element in the array is nums[5], which is 1.\n The maximum element in the array is nums[1], which is 10.\n We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.\n This results in 2 + 3 = 5 deletions, which is the minimum number possible.\n Example 2:\n Input: nums = [0,-4,19,1,8,-2,-3,5]\n Output: 3\n Explanation: \n The minimum element in the array is nums[1], which is -4.\n The maximum element in the array is nums[2], which is 19.\n We can remove both the minimum and maximum by removing 3 elements from the front.\n This results in only 3 deletions, which is the minimum number possible.\n Example 3:\n Input: nums = [101]\n Output: 1\n Explanation: \n There is only one element in the array, which makes it both the minimum and maximum element.\n We can remove it with 1 deletion.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2092, - "title": "Find All People With Secret", - "question": "class Solution:\n def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]:\n \"\"\"\n 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.\n Person 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.\n The 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.\n Return 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:\n Input: n = 6, meetings = [[1,2,5],[2,3,8],[1,5,10]], firstPerson = 1\n Output: [0,1,2,3,5]\n Explanation:\n At time 0, person 0 shares the secret with person 1.\n At time 5, person 1 shares the secret with person 2.\n At time 8, person 2 shares the secret with person 3.\n At time 10, person 1 shares the secret with person 5.\u200b\u200b\u200b\u200b\n Thus, people 0, 1, 2, 3, and 5 know the secret after all the meetings.\n Example 2:\n Input: n = 4, meetings = [[3,1,3],[1,2,2],[0,3,3]], firstPerson = 3\n Output: [0,1,3]\n Explanation:\n At time 0, person 0 shares the secret with person 3.\n At time 2, neither person 1 nor person 2 know the secret.\n At time 3, person 3 shares the secret with person 0 and person 1.\n Thus, people 0, 1, and 3 know the secret after all the meetings.\n Example 3:\n Input: n = 5, meetings = [[3,4,2],[1,2,1],[2,3,1]], firstPerson = 1\n Output: [0,1,2,3,4]\n Explanation:\n At time 0, person 0 shares the secret with person 1.\n At time 1, person 1 shares the secret with person 2, and person 2 shares the secret with person 3.\n Note that person 2 can share the secret at the same time as receiving it.\n At time 2, person 3 shares the secret with person 4.\n Thus, people 0, 1, 2, 3, and 4 know the secret after all the meetings.\n \"\"\"\n", - "difficulty": 2 - }, - { - "number": 2094, - "title": "Finding 3-Digit Even Numbers", - "question": "class Solution:\n def findEvenNumbers(self, digits: List[int]) -> List[int]:\n \"\"\"\n You are given an integer array digits, where each element is a digit. The array may contain duplicates.\n You need to find all the unique integers that follow the given requirements:\n The integer consists of the concatenation of three elements from digits in any arbitrary order.\n The integer does not have leading zeros.\n The integer is even.\n For example, if the given digits were [1, 2, 3], integers 132 and 312 follow the requirements.\n Return a sorted array of the unique integers.\n Example 1:\n Input: digits = [2,1,3,0]\n Output: [102,120,130,132,210,230,302,310,312,320]\n Explanation: All the possible integers that follow the requirements are in the output array. \n Notice that there are no odd integers or integers with leading zeros.\n Example 2:\n Input: digits = [2,2,8,8,2]\n Output: [222,228,282,288,822,828,882]\n Explanation: The same digit can be used as many times as it appears in digits. \n In this example, the digit 8 is used twice each time in 288, 828, and 882. \n Example 3:\n Input: digits = [3,7,5]\n Output: []\n Explanation: No even integers can be formed using the given digits.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2095, - "title": "Delete the Middle Node of a Linked List", - "question": "class Solution:\n def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \"\"\"\n You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.\n The 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.\n For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.\n Example 1:\n Input: head = [1,3,4,7,1,2,6]\n Output: [1,3,4,1,2,6]\n Explanation:\n The above figure represents the given linked list. The indices of the nodes are written below.\n Since n = 7, node 3 with value 7 is the middle node, which is marked in red.\n We return the new list after removing this node. \n Example 2:\n Input: head = [1,2,3,4]\n Output: [1,2,4]\n Explanation:\n The above figure represents the given linked list.\n For n = 4, node 2 with value 3 is the middle node, which is marked in red.\n Example 3:\n Input: head = [2,1]\n Output: [2]\n Explanation:\n The above figure represents the given linked list.\n For n = 2, node 1 with value 1 is the middle node, which is marked in red.\n Node 0 with value 2 is the only node remaining after removing node 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2096, - "title": "Step-By-Step Directions From a Binary Tree Node to Another", - "question": "class Solution:\n def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:\n \"\"\"\n 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.\n Find 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.\n Return the step-by-step directions of the shortest path from node s to node t.\n Example 1:\n Input: root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6\n Output: \"UURL\"\n Explanation: The shortest path is: 3 \u2192 1 \u2192 5 \u2192 2 \u2192 6.\n Example 2:\n Input: root = [2,1], startValue = 2, destValue = 1\n Output: \"L\"\n Explanation: The shortest path is: 2 \u2192 1.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2114, - "title": "Maximum Number of Words Found in Sentences", - "question": "class Solution:\n def mostWordsFound(self, sentences: List[str]) -> int:\n \"\"\"\n A sentence is a list of words that are separated by a single space with no leading or trailing spaces.\n You are given an array of strings sentences, where each sentences[i] represents a single sentence.\n Return the maximum number of words that appear in a single sentence.\n Example 1:\n Input: sentences = [\"alice and bob love leetcode\", \"i think so too\", \"this is great thanks very much\"]\n Output: 6\n Explanation: \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.\n Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.\n Example 2:\n Input: sentences = [\"please wait\", \"continue to fight\", \"continue to win\"]\n Output: 3\n Explanation: It is possible that multiple sentences contain the same number of words. \n In this example, the second and third sentences (underlined) have the same number of words.\n \"\"\"\n", - "difficulty": 0 - }, - { - "number": 2115, - "title": "Find All Possible Recipes from Given Supplies", - "question": "class Solution:\n def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]:\n \"\"\"\n 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.\n You 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.\n Return a list of all the recipes that you can create. You may return the answer in any order.\n Note that two recipes may contain each other in their ingredients.\n Example 1:\n Input: recipes = [\"bread\"], ingredients = [[\"yeast\",\"flour\"]], supplies = [\"yeast\",\"flour\",\"corn\"]\n Output: [\"bread\"]\n Explanation:\n We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\n Example 2:\n Input: recipes = [\"bread\",\"sandwich\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\n Output: [\"bread\",\"sandwich\"]\n Explanation:\n We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\n We can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\n Example 3:\n Input: recipes = [\"bread\",\"sandwich\",\"burger\"], ingredients = [[\"yeast\",\"flour\"],[\"bread\",\"meat\"],[\"sandwich\",\"meat\",\"bread\"]], supplies = [\"yeast\",\"flour\",\"meat\"]\n Output: [\"bread\",\"sandwich\",\"burger\"]\n Explanation:\n We can create \"bread\" since we have the ingredients \"yeast\" and \"flour\".\n We can create \"sandwich\" since we have the ingredient \"meat\" and can create the ingredient \"bread\".\n We can create \"burger\" since we have the ingredient \"meat\" and can create the ingredients \"bread\" and \"sandwich\".\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2116, - "title": "Check if a Parentheses String Can Be Valid", - "question": "class Solution:\n def canBeValid(self, s: str, locked: str) -> bool:\n \"\"\"\n A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:\n It is ().\n It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.\n It can be written as (A), where A is a valid parentheses string.\n You 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,\n If locked[i] is '1', you cannot change s[i].\n But if locked[i] is '0', you can change s[i] to either '(' or ')'.\n Return true if you can make s a valid parentheses string. Otherwise, return false.\n Example 1:\n Input: s = \"))()))\", locked = \"010100\"\n Output: true\n Explanation: locked[1] == '1' and locked[3] == '1', so we cannot change s[1] or s[3].\n We change s[0] and s[4] to '(' while leaving s[2] and s[5] unchanged to make s valid.\n Example 2:\n Input: s = \"()()\", locked = \"0000\"\n Output: true\n Explanation: We do not need to make any changes because s is already valid.\n Example 3:\n Input: s = \")\", locked = \"0\"\n Output: false\n Explanation: locked permits us to change s[0]. \n Changing s[0] to either '(' or ')' will not make s valid.\n \"\"\"\n", - "difficulty": 1 - }, - { - "number": 2117, - "title": "Abbreviating the Product of a Range", - "question": "class Solution:\n def abbreviateProduct(self, left: int, right: int) -> str:\n \"\"\"\n You are given two positive integers left and right with left <= right. Calculate the product of all integers in the inclusive range [left, right].\n Since the product may be very large, you will abbreviate it following these steps:\n Count all trailing zeros in the product and remove them. Let us denote this count as C.\n For example, there are 3 trailing zeros in 1000, and there are 0 trailing zeros in 546.\n Denote 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.\n                For example, we express 1234567654321 as 12345...54321, but 1234567 is represented as 1234567.\n            Finally, represent the product as a string \"
...eC\".\n                For example, 12345678987600000 will be represented as \"12345...89876e5\".\n        Return a string denoting the abbreviated product of all integers in the inclusive range [left, right].\n        Example 1:\n        Input: left = 1, right = 4\n        Output: \"24e0\"\n        Explanation: The product is 1 \u00d7 2 \u00d7 3 \u00d7 4 = 24.\n        There are no trailing zeros, so 24 remains the same. The abbreviation will end with \"e0\".\n        Since the number of digits is 2, which is less than 10, we do not have to abbreviate it further.\n        Thus, the final representation is \"24e0\".\n        Example 2:\n        Input: left = 2, right = 11\n        Output: \"399168e2\"\n        Explanation: The product is 39916800.\n        There are 2 trailing zeros, which we remove to get 399168. The abbreviation will end with \"e2\".\n        The number of digits after removing the trailing zeros is 6, so we do not abbreviate it further.\n        Hence, the abbreviated product is \"399168e2\".\n        Example 3:\n        Input: left = 371, right = 375\n        Output: \"7219856259e3\"\n        Explanation: The product is 7219856259000.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2103,
-        "title": "Rings and Rods",
-        "question": "class Solution:\n    def countPoints(self, rings: str) -> int:\n        \"\"\"\n        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.\n        You 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:\n            The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B').\n            The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9').\n        For 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.\n        Return the number of rods that have all three colors of rings on them.\n        Example 1:\n        Input: rings = \"B0B6G0R6R0R6G9\"\n        Output: 1\n        Explanation: \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.\n        Thus, the number of rods with all three colors is 1.\n        Example 2:\n        Input: rings = \"B0R0G0R9R0B0G0\"\n        Output: 1\n        Explanation: \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.\n        Thus, the number of rods with all three colors is 1.\n        Example 3:\n        Input: rings = \"G4\"\n        Output: 0\n        Explanation: \n        Only one ring is given. Thus, no rods have all three colors.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2104,
-        "title": "Sum of Subarray Ranges",
-        "question": "class Solution:\n    def subArrayRanges(self, nums: List[int]) -> int:\n        \"\"\"\n        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.\n        Return the sum of all subarray ranges of nums.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,2,3]\n        Output: 4\n        Explanation: 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\n        So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.\n        Example 2:\n        Input: nums = [1,3,3]\n        Output: 4\n        Explanation: 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\n        So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.\n        Example 3:\n        Input: nums = [4,-2,-3,4,1]\n        Output: 59\n        Explanation: The sum of all subarray ranges of nums is 59.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2105,
-        "title": "Watering Plants II",
-        "question": "class Solution:\n    def minimumRefill(self, plants: List[int], capacityA: int, capacityB: int) -> int:\n        \"\"\"\n        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.\n        Each 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:\n            Alice 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.\n            It takes the same amount of time to water each plant regardless of how much water it needs.\n            Alice/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.\n            In 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.\n        Given 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:\n        Input: plants = [2,2,3,3], capacityA = 5, capacityB = 5\n        Output: 1\n        Explanation:\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.\n        So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.\n        Example 2:\n        Input: plants = [2,2,3,3], capacityA = 3, capacityB = 4\n        Output: 2\n        Explanation:\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.\n        So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.\n        Example 3:\n        Input: plants = [5], capacityA = 10, capacityB = 8\n        Output: 0\n        Explanation:\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.\n        So, the total number of times they have to refill is 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2106,
-        "title": "Maximum Fruits Harvested After at Most K Steps",
-        "question": "class Solution:\n    def maxTotalFruits(self, fruits: List[List[int]], startPos: int, k: int) -> int:\n        \"\"\"\n        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.\n        You 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.\n        Return the maximum total number of fruits you can harvest.\n        Example 1:\n        Input: fruits = [[2,8],[6,3],[8,6]], startPos = 5, k = 4\n        Output: 9\n        Explanation: \n        The optimal way is to:\n        - Move right to position 6 and harvest 3 fruits\n        - Move right to position 8 and harvest 6 fruits\n        You moved 3 steps and harvested 3 + 6 = 9 fruits in total.\n        Example 2:\n        Input: fruits = [[0,9],[4,1],[5,7],[6,2],[7,4],[10,9]], startPos = 5, k = 4\n        Output: 14\n        Explanation: \n        You can move at most k = 4 steps, so you cannot reach position 0 nor 10.\n        The 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\n        You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.\n        Example 3:\n        Input: fruits = [[0,3],[6,4],[8,5]], startPos = 3, k = 2\n        Output: 0\n        Explanation:\n        You can move at most k = 2 steps and cannot reach any position with fruits.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2108,
-        "title": "Find First Palindromic String in the Array",
-        "question": "class Solution:\n    def firstPalindrome(self, words: List[str]) -> str:\n        \"\"\"\n        Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string \"\".\n        A string is palindromic if it reads the same forward and backward.\n        Example 1:\n        Input: words = [\"abc\",\"car\",\"ada\",\"racecar\",\"cool\"]\n        Output: \"ada\"\n        Explanation: The first string that is palindromic is \"ada\".\n        Note that \"racecar\" is also palindromic, but it is not the first.\n        Example 2:\n        Input: words = [\"notapalindrome\",\"racecar\"]\n        Output: \"racecar\"\n        Explanation: The first and only string that is palindromic is \"racecar\".\n        Example 3:\n        Input: words = [\"def\",\"ghi\"]\n        Output: \"\"\n        Explanation: There are no palindromic strings, so the empty string is returned.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2109,
-        "title": "Adding Spaces to a String",
-        "question": "class Solution:\n    def addSpaces(self, s: str, spaces: List[int]) -> str:\n        \"\"\"\n        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.\n            For 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\".\n        Return the modified string after the spaces have been added.\n        Example 1:\n        Input: s = \"LeetcodeHelpsMeLearn\", spaces = [8,13,15]\n        Output: \"Leetcode Helps Me Learn\"\n        Explanation: \n        The indices 8, 13, and 15 correspond to the underlined characters in \"LeetcodeHelpsMeLearn\".\n        We then place spaces before those characters.\n        Example 2:\n        Input: s = \"icodeinpython\", spaces = [1,5,7,9]\n        Output: \"i code in py thon\"\n        Explanation:\n        The indices 1, 5, 7, and 9 correspond to the underlined characters in \"icodeinpython\".\n        We then place spaces before those characters.\n        Example 3:\n        Input: s = \"spacing\", spaces = [0,1,2,3,4,5,6]\n        Output: \" s p a c i n g\"\n        Explanation:\n        We are also able to place spaces before the first character of the string.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2110,
-        "title": "Number of Smooth Descent Periods of a Stock",
-        "question": "class Solution:\n    def getDescentPeriods(self, prices: List[int]) -> int:\n        \"\"\"\n        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.\n        A 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.\n        Return the number of smooth descent periods.\n        Example 1:\n        Input: prices = [3,2,1,4]\n        Output: 7\n        Explanation: There are 7 smooth descent periods:\n        [3], [2], [1], [4], [3,2], [2,1], and [3,2,1]\n        Note that a period with one day is a smooth descent period by the definition.\n        Example 2:\n        Input: prices = [8,6,7,7]\n        Output: 4\n        Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7]\n        Note that [8,6] is not a smooth descent period as 8 - 6 \u2260 1.\n        Example 3:\n        Input: prices = [1]\n        Output: 1\n        Explanation: There is 1 smooth descent period: [1]\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2111,
-        "title": "Minimum Operations to Make the Array K-Increasing",
-        "question": "class Solution:\n    def kIncreasing(self, arr: List[int], k: int) -> int:\n        \"\"\"\n        You are given a 0-indexed array arr consisting of n positive integers, and a positive integer k.\n        The array arr is called K-increasing if arr[i-k] <= arr[i] holds for every index i, where k <= i <= n-1.\n            For example, arr = [4, 1, 5, 2, 6, 2] is K-increasing for k = 2 because:\n                arr[0] <= arr[2] (4 <= 5)\n                arr[1] <= arr[3] (1 <= 2)\n                arr[2] <= arr[4] (5 <= 6)\n                arr[3] <= arr[5] (2 <= 2)\n            However, the same arr is not K-increasing for k = 1 (because arr[0] > arr[1]) or k = 3 (because arr[0] > arr[3]).\n        In one operation, you can choose an index i and change arr[i] into any positive integer.\n        Return the minimum number of operations required to make the array K-increasing for the given k.\n        Example 1:\n        Input: arr = [5,4,3,2,1], k = 1\n        Output: 4\n        Explanation:\n        For k = 1, the resultant array has to be non-decreasing.\n        Some 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.\n        It is suboptimal to change the array to, for example, [6,7,8,9,10] because it would take 5 operations.\n        It can be shown that we cannot make the array K-increasing in less than 4 operations.\n        Example 2:\n        Input: arr = [4,1,5,2,6,2], k = 2\n        Output: 0\n        Explanation:\n        This is the same example as the one in the problem description.\n        Here, for every index i where 2 <= i <= 5, arr[i-2] <= arr[i].\n        Since the given array is already K-increasing, we do not need to perform any operations.\n        Example 3:\n        Input: arr = [4,1,5,2,6,2], k = 3\n        Output: 2\n        Explanation:\n        Indices 3 and 5 are the only ones not satisfying arr[i-3] <= arr[i] for 3 <= i <= 5.\n        One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.\n        The array will now be [4,1,5,4,6,5].\n        Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2129,
-        "title": "Capitalize the Title",
-        "question": "class Solution:\n    def capitalizeTitle(self, title: str) -> str:\n        \"\"\"\n        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:\n            If the length of the word is 1 or 2 letters, change all letters to lowercase.\n            Otherwise, change the first letter to uppercase and the remaining letters to lowercase.\n        Return the capitalized title.\n        Example 1:\n        Input: title = \"capiTalIze tHe titLe\"\n        Output: \"Capitalize The Title\"\n        Explanation:\n        Since all the words have a length of at least 3, the first letter of each word is uppercase, and the remaining letters are lowercase.\n        Example 2:\n        Input: title = \"First leTTeR of EACH Word\"\n        Output: \"First Letter of Each Word\"\n        Explanation:\n        The word \"of\" has length 2, so it is all lowercase.\n        The 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        Example 3:\n        Input: title = \"i lOve leetcode\"\n        Output: \"i Love Leetcode\"\n        Explanation:\n        The word \"i\" has length 1, so it is lowercase.\n        The 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        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2130,
-        "title": "Maximum Twin Sum of a Linked List",
-        "question": "class Solution:\n    def pairSum(self, head: Optional[ListNode]) -> int:\n        \"\"\"\n        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.\n            For 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.\n        The twin sum is defined as the sum of a node and its twin.\n        Given the head of a linked list with even length, return the maximum twin sum of the linked list.\n        Example 1:\n        Input: head = [5,4,2,1]\n        Output: 6\n        Explanation:\n        Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.\n        There are no other nodes with twins in the linked list.\n        Thus, the maximum twin sum of the linked list is 6. \n        Example 2:\n        Input: head = [4,2,2,3]\n        Output: 7\n        Explanation:\n        The 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.\n        Thus, the maximum twin sum of the linked list is max(7, 4) = 7. \n        Example 3:\n        Input: head = [1,100000]\n        Output: 100001\n        Explanation:\n        There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2131,
-        "title": "Longest Palindrome by Concatenating Two Letter Words",
-        "question": "class Solution:\n    def longestPalindrome(self, words: List[str]) -> int:\n        \"\"\"\n        You are given an array of strings words. Each element of words consists of two lowercase English letters.\n        Create the longest possible palindrome by selecting some elements from words and concatenating them in any order. Each element can be selected at most once.\n        Return the length of the longest palindrome that you can create. If it is impossible to create any palindrome, return 0.\n        A palindrome is a string that reads the same forward and backward.\n        Example 1:\n        Input: words = [\"lc\",\"cl\",\"gg\"]\n        Output: 6\n        Explanation: One longest palindrome is \"lc\" + \"gg\" + \"cl\" = \"lcggcl\", of length 6.\n        Note that \"clgglc\" is another longest palindrome that can be created.\n        Example 2:\n        Input: words = [\"ab\",\"ty\",\"yt\",\"lc\",\"cl\",\"ab\"]\n        Output: 8\n        Explanation: One longest palindrome is \"ty\" + \"lc\" + \"cl\" + \"yt\" = \"tylcclyt\", of length 8.\n        Note that \"lcyttycl\" is another longest palindrome that can be created.\n        Example 3:\n        Input: words = [\"cc\",\"ll\",\"xx\"]\n        Output: 2\n        Explanation: One longest palindrome is \"cc\", of length 2.\n        Note that \"ll\" is another longest palindrome that can be created, and so is \"xx\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2119,
-        "title": "A Number After a Double Reversal",
-        "question": "class Solution:\n    def isSameAfterReversals(self, num: int) -> bool:\n        \"\"\"\n        Reversing an integer means to reverse all its digits.\n            For example, reversing 2021 gives 1202. Reversing 12300 gives 321 as the leading zeros are not retained.\n        Given 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:\n        Input: num = 526\n        Output: true\n        Explanation: Reverse num to get 625, then reverse 625 to get 526, which equals num.\n        Example 2:\n        Input: num = 1800\n        Output: false\n        Explanation: Reverse num to get 81, then reverse 81 to get 18, which does not equal num.\n        Example 3:\n        Input: num = 0\n        Output: true\n        Explanation: Reverse num to get 0, then reverse 0 to get 0, which equals num.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2120,
-        "title": "Execution of All Suffix Instructions Staying in a Grid",
-        "question": "class Solution:\n    def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:\n        \"\"\"\n        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).\n        You 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).\n        The 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:\n            The next instruction will move the robot off the grid.\n            There are no more instructions left to execute.\n        Return 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:\n        Input: n = 3, startPos = [0,1], s = \"RRDDLU\"\n        Output: [1,5,4,3,1,0]\n        Explanation: 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.\n        Example 2:\n        Input: n = 2, startPos = [1,1], s = \"LURD\"\n        Output: [4,1,0,0]\n        Explanation:\n        - 0th: \"LURD\".\n        - 1st:  \"URD\".\n        - 2nd:   \"RD\".\n        - 3rd:    \"D\".\n        Example 3:\n        Input: n = 1, startPos = [0,0], s = \"LRUD\"\n        Output: [0,0,0,0]\n        Explanation: No matter which instruction the robot begins execution from, it would move off the grid.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2121,
-        "title": "Intervals Between Identical Elements",
-        "question": "class Solution:\n    def getDistances(self, arr: List[int]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed array of n integers arr.\n        The 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|.\n        Return 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].\n        Note: |x| is the absolute value of x.\n        Example 1:\n        Input: arr = [2,1,3,1,2,3,3]\n        Output: [4,2,7,2,4,4,5]\n        Explanation:\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\n        Example 2:\n        Input: arr = [10,5,10,10]\n        Output: [5,0,3,4]\n        Explanation:\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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2122,
-        "title": "Recover the Original Array",
-        "question": "class Solution:\n    def recoverArray(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        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:\n            lower[i] = arr[i] - k, for every index i where 0 <= i < n\n            higher[i] = arr[i] + k, for every index i where 0 <= i < n\n        Unfortunately, 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.\n        Given 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.\n        Note: The test cases are generated such that there exists at least one valid array arr.\n        Example 1:\n        Input: nums = [2,10,6,4,8,12]\n        Output: [3,7,11]\n        Explanation:\n        If arr = [3,7,11] and k = 1, we get lower = [2,6,10] and higher = [4,8,12].\n        Combining lower and higher gives us [2,6,10,4,8,12], which is a permutation of nums.\n        Another valid possibility is that arr = [5,7,9] and k = 3. In that case, lower = [2,4,6] and higher = [8,10,12]. \n        Example 2:\n        Input: nums = [1,1,3,3]\n        Output: [2,2]\n        Explanation:\n        If arr = [2,2] and k = 1, we get lower = [1,1] and higher = [3,3].\n        Combining lower and higher gives us [1,1,3,3], which is equal to nums.\n        Note that arr cannot be [1,3] because in that case, the only possible way to obtain [1,1,3,3] is with k = 0.\n        This is invalid since k must be positive.\n        Example 3:\n        Input: nums = [5,435]\n        Output: [220]\n        Explanation:\n        The only possible combination is arr = [220] and k = 215. Using them, we get lower = [5] and higher = [435].\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2124,
-        "title": "Check if All A\"s Appears Before All B\"s",
-        "question": "class Solution:\n    def checkString(self, s: str) -> bool:\n        \"\"\"\n        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:\n        Input: s = \"aaabbb\"\n        Output: true\n        Explanation:\n        The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.\n        Hence, every 'a' appears before every 'b' and we return true.\n        Example 2:\n        Input: s = \"abab\"\n        Output: false\n        Explanation:\n        There is an 'a' at index 2 and a 'b' at index 1.\n        Hence, not every 'a' appears before every 'b' and we return false.\n        Example 3:\n        Input: s = \"bbb\"\n        Output: true\n        Explanation:\n        There are no 'a's, hence, every 'a' appears before every 'b' and we return true.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2125,
-        "title": "Number of Laser Beams in a Bank",
-        "question": "class Solution:\n    def numberOfBeams(self, bank: List[str]) -> int:\n        \"\"\"\n        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.\n        There is one laser beam between any two security devices if both conditions are met:\n            The two devices are located on two different rows: r1 and r2, where r1 < r2.\n            For each row i where r1 < i < r2, there are no security devices in the ith row.\n        Laser beams are independent, i.e., one beam does not interfere nor join with another.\n        Return the total number of laser beams in the bank.\n        Example 1:\n        Input: bank = [\"011001\",\"000000\",\"010100\",\"001000\"]\n        Output: 8\n        Explanation: 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]\n        Note that there is no beam between any device on the 0th row with any on the 3rd row.\n        This is because the 2nd row contains security devices, which breaks the second condition.\n        Example 2:\n        Input: bank = [\"000\",\"111\",\"000\"]\n        Output: 0\n        Explanation: There does not exist two devices located on two different rows.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2126,
-        "title": "Destroying Asteroids",
-        "question": "class Solution:\n    def asteroidsDestroyed(self, mass: int, asteroids: List[int]) -> bool:\n        \"\"\"\n        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.\n        You 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.\n        Return true if all asteroids can be destroyed. Otherwise, return false.\n        Example 1:\n        Input: mass = 10, asteroids = [3,9,19,5,21]\n        Output: true\n        Explanation: 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\n        All asteroids are destroyed.\n        Example 2:\n        Input: mass = 5, asteroids = [4,9,23,4]\n        Output: false\n        Explanation: \n        The planet cannot ever gain enough mass to destroy the asteroid with a mass of 23.\n        After the planet destroys the other asteroids, it will have a mass of 5 + 4 + 9 + 4 = 22.\n        This is less than 23, so a collision would not destroy the last asteroid.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2127,
-        "title": "Maximum Employees to Be Invited to a Meeting",
-        "question": "class Solution:\n    def maximumInvitations(self, favorite: List[int]) -> int:\n        \"\"\"\n        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.\n        The 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.\n        Given 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:\n        Input: favorite = [2,2,1,2]\n        Output: 3\n        Explanation:\n        The above figure shows how the company can invite employees 0, 1, and 2, and seat them at the round table.\n        All employees cannot be invited because employee 2 cannot sit beside employees 0, 1, and 3, simultaneously.\n        Note that the company can also invite employees 1, 2, and 3, and give them their desired seats.\n        The maximum number of employees that can be invited to the meeting is 3. \n        Example 2:\n        Input: favorite = [1,2,0]\n        Output: 3\n        Explanation: \n        Each 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.\n        The 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.\n        The maximum number of employees that can be invited to the meeting is 3.\n        Example 3:\n        Input: favorite = [3,0,1,4,1]\n        Output: 4\n        Explanation:\n        The above figure shows how the company will invite employees 0, 1, 3, and 4, and seat them at the round table.\n        Employee 2 cannot be invited because the two spots next to their favorite employee 1 are taken.\n        So the company leaves them out of the meeting.\n        The maximum number of employees that can be invited to the meeting is 4.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2144,
-        "title": "Minimum Cost of Buying Candies With Discount",
-        "question": "class Solution:\n    def minimumCost(self, cost: List[int]) -> int:\n        \"\"\"\n        A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.\n        The 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.\n            For 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.\n        Given 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:\n        Input: cost = [1,2,3]\n        Output: 5\n        Explanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.\n        The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.\n        Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.\n        The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.\n        Example 2:\n        Input: cost = [6,5,7,9,2,2]\n        Output: 23\n        Explanation: 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\n        Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.\n        Example 3:\n        Input: cost = [5,5]\n        Output: 10\n        Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.\n        Hence, the minimum cost to buy all candies is 5 + 5 = 10.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2145,
-        "title": "Count the Hidden Sequences",
-        "question": "class Solution:\n    def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:\n        \"\"\"\n        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].\n        You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain.\n            For 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.\n        Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.\n        Example 1:\n        Input: differences = [1,-3,4], lower = 1, upper = 6\n        Output: 2\n        Explanation: The possible hidden sequences are:\n        - [3, 4, 1, 5]\n        - [4, 5, 2, 6]\n        Thus, we return 2.\n        Example 2:\n        Input: differences = [3,-4,5,1,-2], lower = -4, upper = 5\n        Output: 4\n        Explanation: 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]\n        Thus, we return 4.\n        Example 3:\n        Input: differences = [4,-7,2], lower = 3, upper = 6\n        Output: 0\n        Explanation: There are no possible hidden sequences. Thus, we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2146,
-        "title": "K Highest Ranked Items Within a Price Range",
-        "question": "class Solution:\n    def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]:\n        \"\"\"\n        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:\n            0 represents a wall that you cannot pass through.\n            1 represents an empty cell that you can freely move to and from.\n            All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.\n        It takes 1 step to travel between adjacent grid cells.\n        You 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.\n        You 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:\n            Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank).\n            Price (lower price has a higher rank, but it must be in the price range).\n            The row number (smaller row number has a higher rank).\n            The column number (smaller column number has a higher rank).\n        Return 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:\n        Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3\n        Output: [[0,1],[1,1],[2,1]]\n        Explanation: You start at (0,0).\n        With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).\n        The 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\n        Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).\n        Example 2:\n        Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2\n        Output: [[2,1],[1,2]]\n        Explanation: You start at (2,3).\n        With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).\n        The 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\n        Thus, the 2 highest ranked items in the price range are (2,1) and (1,2).\n        Example 3:\n        Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3\n        Output: [[2,1],[2,0]]\n        Explanation: You start at (0,0).\n        With a price range of [2,3], we can take items from (2,0) and (2,1). \n        The ranks of these items are: \n        - (2,1) with distance 5\n        - (2,0) with distance 6\n        Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). \n        Note that k = 3 but there are only 2 reachable items within the price range.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2147,
-        "title": "Number of Ways to Divide a Long Corridor",
-        "question": "class Solution:\n    def numberOfWays(self, corridor: str) -> int:\n        \"\"\"\n        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.\n        One 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.\n        Divide 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.\n        Return 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:\n        Input: corridor = \"SSPPSPS\"\n        Output: 3\n        Explanation: There are 3 different ways to divide the corridor.\n        The black bars in the above image indicate the two room dividers already installed.\n        Note that in each of the ways, each section has exactly two seats.\n        Example 2:\n        Input: corridor = \"PPSPSP\"\n        Output: 1\n        Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers.\n        Installing any would create some section that does not have exactly two seats.\n        Example 3:\n        Input: corridor = \"S\"\n        Output: 0\n        Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2133,
-        "title": "Check if Every Row and Column Contains All Numbers",
-        "question": "class Solution:\n    def checkValid(self, matrix: List[List[int]]) -> bool:\n        \"\"\"\n        An n x n matrix is valid if every row and every column contains all the integers from 1 to n (inclusive).\n        Given an n x n integer matrix matrix, return true if the matrix is valid. Otherwise, return false.\n        Example 1:\n        Input: matrix = [[1,2,3],[3,1,2],[2,3,1]]\n        Output: true\n        Explanation: In this case, n = 3, and every row and column contains the numbers 1, 2, and 3.\n        Hence, we return true.\n        Example 2:\n        Input: matrix = [[1,1,1],[1,2,3],[1,2,3]]\n        Output: false\n        Explanation: In this case, n = 3, but the first row and the first column do not contain the numbers 2 or 3.\n        Hence, we return false.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2134,
-        "title": "Minimum Swaps to Group All 1\"s Together II",
-        "question": "class Solution:\n    def minSwaps(self, nums: List[int]) -> int:\n        \"\"\"\n        A swap is defined as taking two distinct positions in an array and swapping the values in them.\n        A circular array is defined as an array where we consider the first element and the last element to be adjacent.\n        Given 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:\n        Input: nums = [0,1,0,1,1,0,0]\n        Output: 1\n        Explanation: 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).\n        There is no way to group all 1's together with 0 swaps.\n        Thus, the minimum number of swaps required is 1.\n        Example 2:\n        Input: nums = [0,1,1,1,0,0,1,1,0]\n        Output: 2\n        Explanation: 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.\n        There is no way to group all 1's together with 0 or 1 swaps.\n        Thus, the minimum number of swaps required is 2.\n        Example 3:\n        Input: nums = [1,1,0,0,1]\n        Output: 0\n        Explanation: All the 1's are already grouped together due to the circular property of the array.\n        Thus, the minimum number of swaps required is 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2135,
-        "title": "Count Words Obtained After Adding a Letter",
-        "question": "class Solution:\n    def wordCount(self, startWords: List[str], targetWords: List[str]) -> int:\n        \"\"\"\n        You are given two 0-indexed arrays of strings startWords and targetWords. Each string consists of lowercase English letters only.\n        For 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.\n        The conversion operation is described in the following two steps:\n            Append any lowercase letter that is not present in the string to its end.\n                For 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\".\n            Rearrange the letters of the new string in any arbitrary order.\n                For example, \"abcd\" can be rearranged to \"acbd\", \"bacd\", \"cbda\", and so on. Note that it can also be rearranged to \"abcd\" itself.\n        Return the number of strings in targetWords that can be obtained by performing the operations on any string of startWords.\n        Note 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:\n        Input: startWords = [\"ant\",\"act\",\"tack\"], targetWords = [\"tack\",\"act\",\"acti\"]\n        Output: 2\n        Explanation:\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.\n        Example 2:\n        Input: startWords = [\"ab\",\"a\"], targetWords = [\"abc\",\"abcd\"]\n        Output: 1\n        Explanation:\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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2136,
-        "title": "Earliest Possible Day of Full Bloom",
-        "question": "class Solution:\n    def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:\n        \"\"\"\n        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:\n            plantTime[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.\n            growTime[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.\n        From the beginning of day 0, you can plant the seeds in any order.\n        Return the earliest possible day where all seeds are blooming.\n        Example 1:\n        Input: plantTime = [1,4,3], growTime = [2,3,1]\n        Output: 9\n        Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\n        One optimal way is:\n        On day 0, plant the 0th seed. The seed grows for 2 full days and blooms on day 3.\n        On days 1, 2, 3, and 4, plant the 1st seed. The seed grows for 3 full days and blooms on day 8.\n        On days 5, 6, and 7, plant the 2nd seed. The seed grows for 1 full day and blooms on day 9.\n        Thus, on day 9, all the seeds are blooming.\n        Example 2:\n        Input: plantTime = [1,2,3,2], growTime = [2,1,2,1]\n        Output: 9\n        Explanation: The grayed out pots represent planting days, colored pots represent growing days, and the flower represents the day it blooms.\n        One optimal way is:\n        On day 1, plant the 0th seed. The seed grows for 2 full days and blooms on day 4.\n        On days 0 and 3, plant the 1st seed. The seed grows for 1 full day and blooms on day 5.\n        On days 2, 4, and 5, plant the 2nd seed. The seed grows for 2 full days and blooms on day 8.\n        On days 6 and 7, plant the 3rd seed. The seed grows for 1 full day and blooms on day 9.\n        Thus, on day 9, all the seeds are blooming.\n        Example 3:\n        Input: plantTime = [1], growTime = [1]\n        Output: 2\n        Explanation: On day 0, plant the 0th seed. The seed grows for 1 full day and blooms on day 2.\n        Thus, on day 2, all the seeds are blooming.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2138,
-        "title": "Divide a String Into Groups of Size k",
-        "question": "class Solution:\n    def divideString(self, s: str, k: int, fill: str) -> List[str]:\n        \"\"\"\n        A string s can be partitioned into groups of size k using the following procedure:\n            The 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.\n            For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.\n        Note 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.\n        Given 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:\n        Input: s = \"abcdefghi\", k = 3, fill = \"x\"\n        Output: [\"abc\",\"def\",\"ghi\"]\n        Explanation:\n        The first 3 characters \"abc\" form the first group.\n        The next 3 characters \"def\" form the second group.\n        The last 3 characters \"ghi\" form the third group.\n        Since all groups can be completely filled by characters from the string, we do not need to use fill.\n        Thus, the groups formed are \"abc\", \"def\", and \"ghi\".\n        Example 2:\n        Input: s = \"abcdefghij\", k = 3, fill = \"x\"\n        Output: [\"abc\",\"def\",\"ghi\",\"jxx\"]\n        Explanation:\n        Similar to the previous example, we are forming the first three groups \"abc\", \"def\", and \"ghi\".\n        For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.\n        Thus, the 4 groups formed are \"abc\", \"def\", \"ghi\", and \"jxx\".\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2155,
-        "title": "All Divisions With the Highest Score of a Binary Array",
-        "question": "class Solution:\n    def maxScoreIndices(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        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:\n            numsleft 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).\n            If i == 0, numsleft is empty, while numsright has all the elements of nums.\n            If i == n, numsleft has all the elements of nums, while numsright is empty.\n        The 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.\n        Return all distinct indices that have the highest possible division score. You may return the answer in any order.\n        Example 1:\n        Input: nums = [0,0,1,0]\n        Output: [2,4]\n        Explanation: 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.\n        Indices 2 and 4 both have the highest possible division score 3.\n        Note the answer [4,2] would also be accepted.\n        Example 2:\n        Input: nums = [0,0,0]\n        Output: [3]\n        Explanation: 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.\n        Only index 3 has the highest possible division score 3.\n        Example 3:\n        Input: nums = [1,1]\n        Output: [0]\n        Explanation: 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.\n        Only index 0 has the highest possible division score 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2140,
-        "title": "Solving Questions With Brainpower",
-        "question": "class Solution:\n    def mostPoints(self, questions: List[List[int]]) -> int:\n        \"\"\"\n        You are given a 0-indexed 2D integer array questions where questions[i] = [pointsi, brainpoweri].\n        The 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.\n            For example, given questions = [[3, 2], [4, 3], [4, 4], [2, 5]]:\n                If question 0 is solved, you will earn 3 points but you will be unable to solve questions 1 and 2.\n                If 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.\n        Return the maximum points you can earn for the exam.\n        Example 1:\n        Input: questions = [[3,2],[4,3],[4,4],[2,5]]\n        Output: 5\n        Explanation: 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\n        Total points earned: 3 + 2 = 5. There is no other way to earn 5 or more points.\n        Example 2:\n        Input: questions = [[1,1],[2,2],[3,3],[4,4],[5,5]]\n        Output: 7\n        Explanation: 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\n        Total points earned: 2 + 5 = 7. There is no other way to earn 7 or more points.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2141,
-        "title": "Maximum Running Time of N Computers",
-        "question": "class Solution:\n    def maxRunTime(self, n: int, batteries: List[int]) -> int:\n        \"\"\"\n        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.\n        Initially, 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.\n        Note that the batteries cannot be recharged.\n        Return the maximum number of minutes you can run all the n computers simultaneously.\n        Example 1:\n        Input: n = 2, batteries = [3,3,3]\n        Output: 4\n        Explanation: \n        Initially, insert battery 0 into the first computer and battery 1 into the second computer.\n        After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.\n        At 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.\n        By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.\n        We can run the two computers simultaneously for at most 4 minutes, so we return 4.\n        Example 2:\n        Input: n = 2, batteries = [1,1,1,1]\n        Output: 2\n        Explanation: \n        Initially, insert battery 0 into the first computer and battery 2 into the second computer. \n        After 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. \n        After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.\n        We can run the two computers simultaneously for at most 2 minutes, so we return 2.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2160,
-        "title": "Minimum Sum of Four Digit Number After Splitting Digits",
-        "question": "class Solution:\n    def minimumSum(self, num: int) -> int:\n        \"\"\"\n        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.\n            For 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].\n        Return the minimum possible sum of new1 and new2.\n        Example 1:\n        Input: num = 2932\n        Output: 52\n        Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.\n        The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.\n        Example 2:\n        Input: num = 4009\n        Output: 13\n        Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. \n        The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2161,
-        "title": "Partition Array According to Given Pivot",
-        "question": "class Solution:\n    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied:\n            Every element less than pivot appears before every element greater than pivot.\n            Every element equal to pivot appears in between the elements less than and greater than pivot.\n            The relative order of the elements less than pivot and the elements greater than pivot is maintained.\n                More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj.\n        Return nums after the rearrangement.\n        Example 1:\n        Input: nums = [9,12,5,10,14,3,10], pivot = 10\n        Output: [9,5,3,10,10,12,14]\n        Explanation: \n        The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.\n        The elements 12 and 14 are greater than the pivot so they are on the right side of the array.\n        The relative ordering of the elements less than and greater than pivot is also maintained. [9, 5, 3] and [12, 14] are the respective orderings.\n        Example 2:\n        Input: nums = [-3,4,3,2], pivot = 2\n        Output: [-3,2,4,3]\n        Explanation: \n        The element -3 is less than the pivot so it is on the left side of the array.\n        The elements 4 and 3 are greater than the pivot so they are on the right side of the array.\n        The relative ordering of the elements less than and greater than pivot is also maintained. [-3] and [4, 3] are the respective orderings.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2162,
-        "title": "Minimum Cost to Set Cooking Time",
-        "question": "class Solution:\n    def minCostSetTime(self, startAt: int, moveCost: int, pushCost: int, targetSeconds: int) -> int:\n        \"\"\"\n        A generic microwave supports cooking times for:\n            at least 1 second.\n            at most 99 minutes and 99 seconds.\n        To 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,\n            You push 9 5 4 (three digits). It is normalized as 0954 and interpreted as 9 minutes and 54 seconds.\n            You push 0 0 0 8 (four digits). It is interpreted as 0 minutes and 8 seconds.\n            You push 8 0 9 0. It is interpreted as 80 minutes and 90 seconds.\n            You push 8 1 3 0. It is interpreted as 81 minutes and 30 seconds.\n        You 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.\n        There can be multiple ways to set the microwave to cook for targetSeconds seconds but you are interested in the way with the minimum cost.\n        Return the minimum cost to set targetSeconds seconds of cooking time.\n        Remember that one minute consists of 60 seconds.\n        Example 1:\n        Input: startAt = 1, moveCost = 2, pushCost = 1, targetSeconds = 600\n        Output: 6\n        Explanation: 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.\n        Example 2:\n        Input: startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76\n        Output: 6\n        Explanation: The optimal way is to push two digits: 7 6, interpreted as 76 seconds.\n        The 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\n        Note other possible ways are 0076, 076, 0116, and 116, but none of them produces the minimum cost.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2163,
-        "title": "Minimum Difference in Sums After Removal of Elements",
-        "question": "class Solution:\n    def minimumDifference(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums consisting of 3 * n elements.\n        You 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:\n            The first n elements belonging to the first part and their sum is sumfirst.\n            The next n elements belonging to the second part and their sum is sumsecond.\n        The difference in sums of the two parts is denoted as sumfirst - sumsecond.\n            For example, if sumfirst = 3 and sumsecond = 2, their difference is 1.\n            Similarly, if sumfirst = 2 and sumsecond = 3, their difference is -1.\n        Return the minimum difference possible between the sums of the two parts after the removal of n elements.\n        Example 1:\n        Input: nums = [3,1,2]\n        Output: -1\n        Explanation: Here, nums has 3 elements, so n = 1. \n        Thus 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.\n        The minimum difference between sums of the two parts is min(-1,1,2) = -1. \n        Example 2:\n        Input: nums = [7,9,5,8,1,3]\n        Output: 1\n        Explanation: Here n = 2. So we must remove 2 elements and divide the remaining array into two parts containing two elements each.\n        If 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.\n        To 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.\n        It can be shown that it is not possible to obtain a difference smaller than 1.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2148,
-        "title": "Count Elements With Strictly Smaller and Greater Elements ",
-        "question": "class Solution:\n    def countElements(self, nums: List[int]) -> int:\n        \"\"\"\n        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:\n        Input: nums = [11,7,2,15]\n        Output: 2\n        Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.\n        Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it.\n        In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.\n        Example 2:\n        Input: nums = [-3,3,3,90]\n        Output: 2\n        Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.\n        Since 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        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2150,
-        "title": "Find All Lonely Numbers in the Array",
-        "question": "class Solution:\n    def findLonely(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        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.\n        Return all lonely numbers in nums. You may return the answer in any order.\n        Example 1:\n        Input: nums = [10,6,5,8]\n        Output: [10,8]\n        Explanation: \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.\n        Hence, the lonely numbers in nums are [10, 8].\n        Note that [8, 10] may also be returned.\n        Example 2:\n        Input: nums = [1,3,5,3]\n        Output: [1,5]\n        Explanation: \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.\n        Hence, the lonely numbers in nums are [1, 5].\n        Note that [5, 1] may also be returned.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2149,
-        "title": "Rearrange Array Elements by Sign",
-        "question": "class Solution:\n    def rearrangeArray(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers.\n        You should rearrange the elements of nums such that the modified array follows the given conditions:\n            Every consecutive pair of integers have opposite signs.\n            For all integers with the same sign, the order in which they were present in nums is preserved.\n            The rearranged array begins with a positive integer.\n        Return the modified array after rearranging the elements to satisfy the aforementioned conditions.\n        Example 1:\n        Input: nums = [3,1,-2,-5,2,-4]\n        Output: [3,-2,1,-5,2,-4]\n        Explanation:\n        The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].\n        The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].\n        Other 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.  \n        Example 2:\n        Input: nums = [-1,1]\n        Output: [1,-1]\n        Explanation:\n        1 is the only positive integer and -1 the only negative integer in nums.\n        So nums is rearranged to [1,-1].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2151,
-        "title": "Maximum Good People Based on Statements",
-        "question": "class Solution:\n    def maximumGood(self, statements: List[List[int]]) -> int:\n        \"\"\"\n        There are two types of persons:\n            The good person: The person who always tells the truth.\n            The bad person: The person who might tell the truth and might lie.\n        You 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:\n            0 which represents a statement made by person i that person j is a bad person.\n            1 which represents a statement made by person i that person j is a good person.\n            2 represents that no statement is made by person i about person j.\n        Additionally, no person ever makes a statement about themselves. Formally, we have that statements[i][i] = 2 for all 0 <= i < n.\n        Return the maximum number of people who can be good based on the statements made by the n people.\n        Example 1:\n        Input: statements = [[2,1,2],[1,2,2],[2,0,2]]\n        Output: 2\n        Explanation: 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.\n        Let'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.\n        We can see that at most 2 persons are good in the best case, so we return 2.\n        Note that there is more than one way to arrive at this conclusion.\n        Example 2:\n        Input: statements = [[2,0],[0,2]]\n        Output: 1\n        Explanation: Each person makes a single statement.\n        - Person 0 states that person 1 is bad.\n        - Person 1 states that person 0 is bad.\n        Let'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.\n        We can see that at most, one person is good in the best case, so we return 1.\n        Note that there is more than one way to arrive at this conclusion.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2154,
-        "title": "Keep Multiplying Found Values by Two",
-        "question": "class Solution:\n    def findFinalValue(self, nums: List[int], original: int) -> int:\n        \"\"\"\n        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.\n        You then do the following steps:\n            If original is found in nums, multiply it by two (i.e., set original = 2 * original).\n            Otherwise, stop the process.\n            Repeat this process with the new number as long as you keep finding the number.\n        Return the final value of original.\n        Example 1:\n        Input: nums = [5,3,6,1,12], original = 3\n        Output: 24\n        Explanation: \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.\n        Example 2:\n        Input: nums = [2,7,9], original = 4\n        Output: 4\n        Explanation:\n        - 4 is not found in nums. Thus, 4 is returned.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2156,
-        "title": "Find Substring With Given Hash Value",
-        "question": "class Solution:\n    def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:\n        \"\"\"\n        The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:\n            hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.\n        Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.\n        You 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.\n        The test cases will be generated such that an answer always exists.\n        A substring is a contiguous non-empty sequence of characters within a string.\n        Example 1:\n        Input: s = \"leetcode\", power = 7, modulo = 20, k = 2, hashValue = 0\n        Output: \"ee\"\n        Explanation: 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\".\n        Example 2:\n        Input: s = \"fbxzaad\", power = 31, modulo = 100, k = 3, hashValue = 32\n        Output: \"fbx\"\n        Explanation: 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. \n        The 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\".\n        Note that \"bxz\" also has a hash of 32 but it appears later than \"fbx\".\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2157,
-        "title": "Groups of Strings",
-        "question": "class Solution:\n    def groupStrings(self, words: List[str]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed array of strings words. Each string consists of lowercase English letters only. No letter occurs more than once in any string of words.\n        Two strings s1 and s2 are said to be connected if the set of letters of s2 can be obtained from the set of letters of s1 by any one of the following operations:\n            Adding exactly one letter to the set of the letters of s1.\n            Deleting exactly one letter from the set of the letters of s1.\n            Replacing exactly one letter from the set of the letters of s1 with any letter, including itself.\n        The array words can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true:\n            It is connected to at least one other string of the group.\n            It is the only string present in the group.\n        Note that the strings in words should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique.\n        Return an array ans of size 2 where:\n            ans[0] is the maximum number of groups words can be divided into, and\n            ans[1] is the size of the largest group.\n        Example 1:\n        Input: words = [\"a\",\"b\",\"ab\",\"cde\"]\n        Output: [2,3]\n        Explanation:\n        - words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].\n        - words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].\n        - words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].\n        - words[3] is not connected to any string in words.\n        Thus, words can be divided into 2 groups [\"a\",\"b\",\"ab\"] and [\"cde\"]. The size of the largest group is 3.  \n        Example 2:\n        Input: words = [\"a\",\"ab\",\"abc\"]\n        Output: [1,3]\n        Explanation:\n        - words[0] is connected to words[1].\n        - words[1] is connected to words[0] and words[2].\n        - words[2] is connected to words[1].\n        Since all strings are connected to each other, they should be grouped together.\n        Thus, the size of the largest group is 3.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2176,
-        "title": "Count Equal and Divisible Pairs in an Array",
-        "question": "class Solution:\n    def countPairs(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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:\n        Input: nums = [3,1,2,2,2,1,3], k = 2\n        Output: 4\n        Explanation:\n        There 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.\n        Example 2:\n        Input: nums = [1,2,3,4], k = 1\n        Output: 0\n        Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2177,
-        "title": "Find Three Consecutive Integers That Sum to a Given Number",
-        "question": "class Solution:\n    def sumOfThree(self, num: int) -> List[int]:\n        \"\"\"\n        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:\n        Input: num = 33\n        Output: [10,11,12]\n        Explanation: 33 can be expressed as 10 + 11 + 12 = 33.\n        10, 11, 12 are 3 consecutive integers, so we return [10, 11, 12].\n        Example 2:\n        Input: num = 4\n        Output: []\n        Explanation: There is no way to express 4 as the sum of 3 consecutive integers.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2178,
-        "title": "Maximum Split of Positive Even Integers",
-        "question": "class Solution:\n    def maximumEvenSplit(self, finalSum: int) -> List[int]:\n        \"\"\"\n        You are given an integer finalSum. Split it into a sum of a maximum number of unique positive even integers.\n            For example, given finalSum = 12, the following splits are valid (unique positive even integers summing up to finalSum): (12), (2 + 10), (2 + 4 + 6), and (4 + 8). Among them, (2 + 4 + 6) contains the maximum number of integers. Note that finalSum cannot be split into (2 + 2 + 4 + 4) as all the numbers should be unique.\n        Return a list of integers that represent a valid split containing a maximum number of integers. If no valid split exists for finalSum, return an empty list. You may return the integers in any order.\n        Example 1:\n        Input: finalSum = 12\n        Output: [2,4,6]\n        Explanation: The following are valid splits: (12), (2 + 10), (2 + 4 + 6), and (4 + 8).\n        (2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].\n        Note that [2,6,4], [6,2,4], etc. are also accepted.\n        Example 2:\n        Input: finalSum = 7\n        Output: []\n        Explanation: There are no valid splits for the given finalSum.\n        Thus, we return an empty array.\n        Example 3:\n        Input: finalSum = 28\n        Output: [6,8,2,12]\n        Explanation: The following are valid splits: (2 + 26), (6 + 8 + 2 + 12), and (4 + 24). \n        (6 + 8 + 2 + 12) has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].\n        Note that [10,2,4,12], [6,2,4,16], etc. are also accepted.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2179,
-        "title": "Count Good Triplets in an Array",
-        "question": "class Solution:\n    def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n        \"\"\"\n        You are given two 0-indexed arrays nums1 and nums2 of length n, both of which are permutations of [0, 1, ..., n - 1].\n        A 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.\n        Return the total number of good triplets.\n        Example 1:\n        Input: nums1 = [2,0,1,3], nums2 = [0,1,2,3]\n        Output: 1\n        Explanation: \n        There 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). \n        Out of those triplets, only the triplet (0,1,3) satisfies pos2x < pos2y < pos2z. Hence, there is only 1 good triplet.\n        Example 2:\n        Input: nums1 = [4,0,1,3,2], nums2 = [4,1,0,2,3]\n        Output: 4\n        Explanation: The 4 good triplets are (4,0,3), (4,0,2), (4,1,3), and (4,1,2).\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2164,
-        "title": "Sort Even and Odd Indices Independently",
-        "question": "class Solution:\n    def sortEvenOdd(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules:\n            Sort the values at odd indices of nums in non-increasing order.\n                For 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.\n            Sort the values at even indices of nums in non-decreasing order.\n                For 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.\n        Return the array formed after rearranging the values of nums.\n        Example 1:\n        Input: nums = [4,1,2,3]\n        Output: [2,3,4,1]\n        Explanation: \n        First, we sort the values present at odd indices (1 and 3) in non-increasing order.\n        So, nums changes from [4,1,2,3] to [4,3,2,1].\n        Next, we sort the values present at even indices (0 and 2) in non-decreasing order.\n        So, nums changes from [4,1,2,3] to [2,3,4,1].\n        Thus, the array formed after rearranging the values is [2,3,4,1].\n        Example 2:\n        Input: nums = [2,1]\n        Output: [2,1]\n        Explanation: \n        Since there is exactly one odd index and one even index, no rearrangement of values takes place.\n        The resultant array formed is [2,1], which is the same as the initial array. \n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2165,
-        "title": "Smallest Value of the Rearranged Number",
-        "question": "class Solution:\n    def smallestNumber(self, num: int) -> int:\n        \"\"\"\n        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.\n        Return the rearranged number with minimal value.\n        Note that the sign of the number does not change after rearranging the digits.\n        Example 1:\n        Input: num = 310\n        Output: 103\n        Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. \n        The arrangement with the smallest value that does not contain any leading zeros is 103.\n        Example 2:\n        Input: num = -7605\n        Output: -7650\n        Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567.\n        The arrangement with the smallest value that does not contain any leading zeros is -7650.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2166,
-        "title": "Design Bitset",
-        "question": "class Bitset:\n    def __init__(self, size: int):\n    def fix(self, idx: int) -> None:\n    def unfix(self, idx: int) -> None:\n    def flip(self) -> None:\n    def all(self) -> bool:\n    def one(self) -> bool:\n    def count(self) -> int:\n    def toString(self) -> str:\n        \"\"\"\n        A Bitset is a data structure that compactly stores bits.\n        Implement the Bitset class:\n            Bitset(int size) Initializes the Bitset with size bits, all of which are 0.\n            void fix(int idx) Updates the value of the bit at the index idx to 1. If the value was already 1, no change occurs.\n            void unfix(int idx) Updates the value of the bit at the index idx to 0. If the value was already 0, no change occurs.\n            void flip() Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.\n            boolean all() Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise.\n            boolean one() Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise.\n            int count() Returns the total number of bits in the Bitset which have value 1.\n            String toString() Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.\n        Example 1:\n        Input\n        [\"Bitset\", \"fix\", \"fix\", \"flip\", \"all\", \"unfix\", \"flip\", \"one\", \"unfix\", \"count\", \"toString\"]\n        [[5], [3], [1], [], [], [0], [], [], [0], [], []]\n        Output\n        [null, null, null, null, false, null, null, true, null, 2, \"01010\"]\n        Explanation\n        Bitset bs = new Bitset(5); // bitset = \"00000\".\n        bs.fix(3);     // the value at idx = 3 is updated to 1, so bitset = \"00010\".\n        bs.fix(1);     // the value at idx = 1 is updated to 1, so bitset = \"01010\". \n        bs.flip();     // the value of each bit is flipped, so bitset = \"10101\". \n        bs.all();      // return False, as not all values of the bitset are 1.\n        bs.unfix(0);   // the value at idx = 0 is updated to 0, so bitset = \"00101\".\n        bs.flip();     // the value of each bit is flipped, so bitset = \"11010\". \n        bs.one();      // return True, as there is at least 1 index with value 1.\n        bs.unfix(0);   // the value at idx = 0 is updated to 0, so bitset = \"01010\".\n        bs.count();    // return 2, as there are 2 bits with value 1.\n        bs.toString(); // return \"01010\", which is the composition of bitset.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2167,
-        "title": "Minimum Time to Remove All Cars Containing Illegal Goods",
-        "question": "class Solution:\n    def minimumTime(self, s: str) -> int:\n        \"\"\"\n        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.\n        As 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:\n            Remove a train car from the left end (i.e., remove s[0]) which takes 1 unit of time.\n            Remove a train car from the right end (i.e., remove s[s.length - 1]) which takes 1 unit of time.\n            Remove a train car from anywhere in the sequence which takes 2 units of time.\n        Return the minimum time to remove all the cars containing illegal goods.\n        Note that an empty sequence of cars is considered to have no cars containing illegal goods.\n        Example 1:\n        Input: s = \"1100101\"\n        Output: 5\n        Explanation: \n        One 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.\n        This obtains a total time of 2 + 1 + 2 = 5. \n        An 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.\n        This also obtains a total time of 2 + 3 = 5.\n        5 is the minimum time taken to remove all the cars containing illegal goods. \n        There are no other ways to remove them with less time.\n        Example 2:\n        Input: s = \"0010\"\n        Output: 2\n        Explanation:\n        One 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.\n        This obtains a total time of 3.\n        Another 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.\n        This obtains a total time of 2.\n        Another 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. \n        This obtains a total time of 2.\n        2 is the minimum time taken to remove all the cars containing illegal goods. \n        There are no other ways to remove them with less time.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2169,
-        "title": "Count Operations to Obtain Zero",
-        "question": "class Solution:\n    def countOperations(self, num1: int, num2: int) -> int:\n        \"\"\"\n        You are given two non-negative integers num1 and num2.\n        In one operation, if num1 >= num2, you must subtract num2 from num1, otherwise subtract num1 from num2.\n            For 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.\n        Return the number of operations required to make either num1 = 0 or num2 = 0.\n        Example 1:\n        Input: num1 = 2, num2 = 3\n        Output: 3\n        Explanation: \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.\n        Now num1 = 0 and num2 = 1. Since num1 == 0, we do not need to perform any further operations.\n        So the total number of operations required is 3.\n        Example 2:\n        Input: num1 = 10, num2 = 10\n        Output: 1\n        Explanation: \n        - Operation 1: num1 = 10, num2 = 10. Since num1 == num2, we subtract num2 from num1 and get num1 = 10 - 10 = 0.\n        Now num1 = 0 and num2 = 10. Since num1 == 0, we are done.\n        So the total number of operations required is 1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2170,
-        "title": "Minimum Operations to Make the Array Alternating",
-        "question": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed array nums consisting of n positive integers.\n        The array nums is called alternating if:\n            nums[i - 2] == nums[i], where 2 <= i <= n - 1.\n            nums[i - 1] != nums[i], where 1 <= i <= n - 1.\n        In one operation, you can choose an index i and change nums[i] into any positive integer.\n        Return the minimum number of operations required to make the array alternating.\n        Example 1:\n        Input: nums = [3,1,3,2,4,3]\n        Output: 3\n        Explanation:\n        One way to make the array alternating is by converting it to [3,1,3,1,3,1].\n        The number of operations required in this case is 3.\n        It can be proven that it is not possible to make the array alternating in less than 3 operations. \n        Example 2:\n        Input: nums = [1,2,2,2,2]\n        Output: 2\n        Explanation:\n        One way to make the array alternating is by converting it to [1,2,1,2,1].\n        The number of operations required in this case is 2.\n        Note 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2171,
-        "title": "Removing Minimum Number of Magic Beans",
-        "question": "class Solution:\n    def minimumRemoval(self, beans: List[int]) -> int:\n        \"\"\"\n        You are given an array of positive integers beans, where each integer represents the number of magic beans found in a particular magic bag.\n        Remove 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.\n        Return the minimum number of magic beans that you have to remove.\n        Example 1:\n        Input: beans = [4,1,6,5]\n        Output: 4\n        Explanation: \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]\n        We removed a total of 1 + 2 + 1 = 4 beans to make the remaining non-empty bags have an equal number of beans.\n        There are no other solutions that remove 4 beans or fewer.\n        Example 2:\n        Input: beans = [2,10,3,2]\n        Output: 7\n        Explanation:\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]\n        We removed a total of 2 + 2 + 3 = 7 beans to make the remaining non-empty bags have an equal number of beans.\n        There are no other solutions that removes 7 beans or fewer.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2172,
-        "title": "Maximum AND Sum of Array",
-        "question": "class Solution:\n    def maximumANDSum(self, nums: List[int], numSlots: int) -> int:\n        \"\"\"\n        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.\n        You 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.\n            For 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.\n        Return the maximum possible AND sum of nums given numSlots slots.\n        Example 1:\n        Input: nums = [1,2,3,4,5,6], numSlots = 3\n        Output: 9\n        Explanation: One possible placement is [1, 4] into slot 1, [2, 6] into slot 2, and [3, 5] into slot 3. \n        This 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.\n        Example 2:\n        Input: nums = [1,3,10,4,7,1], numSlots = 9\n        Output: 24\n        Explanation: 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.\n        This 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.\n        Note that slots 2, 5, 6, and 8 are empty which is permitted.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2185,
-        "title": "Counting Words With a Given Prefix",
-        "question": "class Solution:\n    def prefixCount(self, words: List[str], pref: str) -> int:\n        \"\"\"\n        You are given an array of strings words and a string pref.\n        Return the number of strings in words that contain pref as a prefix.\n        A prefix of a string s is any leading contiguous substring of s.\n        Example 1:\n        Input: words = [\"pay\",\"attention\",\"practice\",\"attend\"], pref = \"at\"\n        Output: 2\n        Explanation: The 2 strings that contain \"at\" as a prefix are: \"attention\" and \"attend\".\n        Example 2:\n        Input: words = [\"leetcode\",\"win\",\"loops\",\"success\"], pref = \"code\"\n        Output: 0\n        Explanation: There are no strings that contain \"code\" as a prefix.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2186,
-        "title": "Minimum Number of Steps to Make Two Strings Anagram II",
-        "question": "class Solution:\n    def minSteps(self, s: str, t: str) -> int:\n        \"\"\"\n        You are given two strings s and t. In one step, you can append any character to either s or t.\n        Return the minimum number of steps to make s and t anagrams of each other.\n        An anagram of a string is a string that contains the same characters with a different (or the same) ordering.\n        Example 1:\n        Input: s = \"leetcode\", t = \"coats\"\n        Output: 7\n        Explanation: \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.\n        We used a total of 2 + 5 = 7 steps.\n        It can be shown that there is no way to make them anagrams of each other with less than 7 steps.\n        Example 2:\n        Input: s = \"night\", t = \"thing\"\n        Output: 0\n        Explanation: The given strings are already anagrams of each other. Thus, we do not need any further steps.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2187,
-        "title": "Minimum Time to Complete Trips",
-        "question": "class Solution:\n    def minimumTime(self, time: List[int], totalTrips: int) -> int:\n        \"\"\"\n        You are given an array time where time[i] denotes the time taken by the ith bus to complete one trip.\n        Each 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.\n        You 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:\n        Input: time = [1,2,3], totalTrips = 5\n        Output: 3\n        Explanation:\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.\n        So the minimum time needed for all buses to complete at least 5 trips is 3.\n        Example 2:\n        Input: time = [2], totalTrips = 1\n        Output: 2\n        Explanation:\n        There is only one bus, and it will complete its first trip at t = 2.\n        So the minimum time needed to complete 1 trip is 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2188,
-        "title": "Minimum Time to Finish the Race",
-        "question": "class Solution:\n    def minimumFinishTime(self, tires: List[List[int]], changeTime: int, numLaps: int) -> int:\n        \"\"\"\n        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.\n            For 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.\n        You are also given an integer changeTime and an integer numLaps.\n        The 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.\n        Return the minimum time to finish the race.\n        Example 1:\n        Input: tires = [[2,3],[3,4]], changeTime = 5, numLaps = 4\n        Output: 21\n        Explanation: \n        Lap 1: Start with tire 0 and finish the lap in 2 seconds.\n        Lap 2: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\n        Lap 3: Change tires to a new tire 0 for 5 seconds and then finish the lap in another 2 seconds.\n        Lap 4: Continue with tire 0 and finish the lap in 2 * 3 = 6 seconds.\n        Total time = 2 + 6 + 5 + 2 + 6 = 21 seconds.\n        The minimum time to complete the race is 21 seconds.\n        Example 2:\n        Input: tires = [[1,10],[2,2],[3,4]], changeTime = 6, numLaps = 5\n        Output: 25\n        Explanation: \n        Lap 1: Start with tire 1 and finish the lap in 2 seconds.\n        Lap 2: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\n        Lap 3: Change tires to a new tire 1 for 6 seconds and then finish the lap in another 2 seconds.\n        Lap 4: Continue with tire 1 and finish the lap in 2 * 2 = 4 seconds.\n        Lap 5: Change tires to tire 0 for 6 seconds then finish the lap in another 1 second.\n        Total time = 2 + 4 + 6 + 2 + 4 + 6 + 1 = 25 seconds.\n        The minimum time to complete the race is 25 seconds. \n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2180,
-        "title": "Count Integers With Even Digit Sum",
-        "question": "class Solution:\n    def countEven(self, num: int) -> int:\n        \"\"\"\n        Given a positive integer num, return the number of positive integers less than or equal to num whose digit sums are even.\n        The digit sum of a positive integer is the sum of all its digits.\n        Example 1:\n        Input: num = 4\n        Output: 2\n        Explanation:\n        The only integers less than or equal to 4 whose digit sums are even are 2 and 4.    \n        Example 2:\n        Input: num = 30\n        Output: 14\n        Explanation:\n        The 14 integers less than or equal to 30 whose digit sums are even are\n        2, 4, 6, 8, 11, 13, 15, 17, 19, 20, 22, 24, 26, and 28.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2181,
-        "title": "Merge Nodes in Between Zeros",
-        "question": "class Solution:\n    def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        \"\"\"\n        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.\n        For 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.\n        Return the head of the modified linked list.\n        Example 1:\n        Input: head = [0,3,1,0,4,5,2,0]\n        Output: [4,11]\n        Explanation: \n        The 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.\n        Example 2:\n        Input: head = [0,1,0,3,0,2,2,0]\n        Output: [1,3,4]\n        Explanation: \n        The 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2182,
-        "title": "Construct String With Repeat Limit",
-        "question": "class Solution:\n    def repeatLimitedString(self, s: str, repeatLimit: int) -> str:\n        \"\"\"\n        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.\n        Return the lexicographically largest repeatLimitedString possible.\n        A 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:\n        Input: s = \"cczazcc\", repeatLimit = 3\n        Output: \"zzcccac\"\n        Explanation: We use all of the characters from s to construct the repeatLimitedString \"zzcccac\".\n        The letter 'a' appears at most 1 time in a row.\n        The letter 'c' appears at most 3 times in a row.\n        The letter 'z' appears at most 2 times in a row.\n        Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\n        The string is the lexicographically largest repeatLimitedString possible so we return \"zzcccac\".\n        Note 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.\n        Example 2:\n        Input: s = \"aababab\", repeatLimit = 2\n        Output: \"bbabaa\"\n        Explanation: We use only some of the characters from s to construct the repeatLimitedString \"bbabaa\". \n        The letter 'a' appears at most 2 times in a row.\n        The letter 'b' appears at most 2 times in a row.\n        Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.\n        The string is the lexicographically largest repeatLimitedString possible so we return \"bbabaa\".\n        Note 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2183,
-        "title": "Count Array Pairs Divisible by K",
-        "question": "class Solution:\n    def countPairs(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        Given a 0-indexed integer array nums of length n and an integer k, return the number of pairs (i, j) such that:\n            0 <= i < j <= n - 1 and\n            nums[i] * nums[j] is divisible by k.\n        Example 1:\n        Input: nums = [1,2,3,4,5], k = 2\n        Output: 7\n        Explanation: \n        The 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).\n        Their products are 2, 4, 6, 8, 10, 12, and 20 respectively.\n        Other pairs such as (0, 2) and (2, 4) have products 3 and 15 respectively, which are not divisible by 2.    \n        Example 2:\n        Input: nums = [1,2,3,4], k = 5\n        Output: 0\n        Explanation: There does not exist any pair of indices whose corresponding product is divisible by 5.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2194,
-        "title": "Cells in a Range on an Excel Sheet",
-        "question": "class Solution:\n    def cellsInRange(self, s: str) -> List[str]:\n        \"\"\"\n        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.\n                For 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.\n        You 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.\n        Return 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:\n        Input: s = \"K1:L2\"\n        Output: [\"K1\",\"K2\",\"L1\",\"L2\"]\n        Explanation:\n        The above diagram shows the cells which should be present in the list.\n        The red arrows denote the order in which the cells should be presented.\n        Example 2:\n        Input: s = \"A1:F1\"\n        Output: [\"A1\",\"B1\",\"C1\",\"D1\",\"E1\",\"F1\"]\n        Explanation:\n        The above diagram shows the cells which should be present in the list.\n        The red arrow denotes the order in which the cells should be presented.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2195,
-        "title": "Append K Integers With Minimal Sum",
-        "question": "class Solution:\n    def minimalKSum(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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.\n        Return the sum of the k integers appended to nums.\n        Example 1:\n        Input: nums = [1,4,25,10,25], k = 2\n        Output: 5\n        Explanation: The two unique positive integers that do not appear in nums which we append are 2 and 3.\n        The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.\n        The sum of the two integers appended is 2 + 3 = 5, so we return 5.\n        Example 2:\n        Input: nums = [5,6], k = 6\n        Output: 25\n        Explanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.\n        The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. \n        The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2196,
-        "title": "Create Binary Tree From Descriptions",
-        "question": "class Solution:\n    def createBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]:\n        \"\"\"\n        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,\n            If isLefti == 1, then childi is the left child of parenti.\n            If isLefti == 0, then childi is the right child of parenti.\n        Construct the binary tree described by descriptions and return its root.\n        The test cases will be generated such that the binary tree is valid.\n        Example 1:\n        Input: descriptions = [[20,15,1],[20,17,0],[50,20,1],[50,80,0],[80,19,1]]\n        Output: [50,20,80,15,17,19]\n        Explanation: The root node is the node with value 50 since it has no parent.\n        The resulting binary tree is shown in the diagram.\n        Example 2:\n        Input: descriptions = [[1,2,1],[2,3,0],[3,4,1]]\n        Output: [1,2,null,null,3,4]\n        Explanation: The root node is the node with value 1 since it has no parent.\n        The resulting binary tree is shown in the diagram.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2197,
-        "title": "Replace Non-Coprime Numbers in Array",
-        "question": "class Solution:\n    def replaceNonCoprimes(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        You are given an array of integers nums. Perform the following steps:\n            Find any two adjacent numbers in nums that are non-coprime.\n            If no such numbers are found, stop the process.\n            Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).\n            Repeat this process as long as you keep finding two adjacent non-coprime numbers.\n        Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.\n        The test cases are generated such that the values in the final array are less than or equal to 108.\n        Two 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:\n        Input: nums = [6,4,3,2,7,6,2]\n        Output: [12,7,6]\n        Explanation: \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].\n        There are no more adjacent non-coprime numbers in nums.\n        Thus, the final modified array is [12,7,6].\n        Note that there are other ways to obtain the same resultant array.\n        Example 2:\n        Input: nums = [2,2,1,1,3,3,3]\n        Output: [2,1,1,3]\n        Explanation: \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].\n        There are no more adjacent non-coprime numbers in nums.\n        Thus, the final modified array is [2,1,1,3].\n        Note that there are other ways to obtain the same resultant array.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2206,
-        "title": "Divide Array Into Equal Pairs",
-        "question": "class Solution:\n    def divideArray(self, nums: List[int]) -> bool:\n        \"\"\"\n        You are given an integer array nums consisting of 2 * n integers.\n        You need to divide nums into n pairs such that:\n            Each element belongs to exactly one pair.\n            The elements present in a pair are equal.\n        Return true if nums can be divided into n pairs, otherwise return false.\n        Example 1:\n        Input: nums = [3,2,3,2,2,2]\n        Output: true\n        Explanation: \n        There are 6 elements in nums, so they should be divided into 6 / 2 = 3 pairs.\n        If nums is divided into the pairs (2, 2), (3, 3), and (2, 2), it will satisfy all the conditions.\n        Example 2:\n        Input: nums = [1,2,3,4]\n        Output: false\n        Explanation: \n        There is no way to divide nums into 4 / 2 = 2 pairs such that the pairs satisfy every condition.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2207,
-        "title": "Maximize Number of Subsequences in a String",
-        "question": "class Solution:\n    def maximumSubsequenceCount(self, text: str, pattern: str) -> int:\n        \"\"\"\n        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.\n        You 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.\n        Return the maximum number of times pattern can occur as a subsequence of the modified text.\n        A 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:\n        Input: text = \"abdcdbc\", pattern = \"ac\"\n        Output: 4\n        Explanation:\n        If 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.\n        Some other strings which have 4 subsequences \"ac\" after adding a character to text are \"aabdcdbc\" and \"abdacdbc\".\n        However, strings such as \"abdcadbc\", \"abdccdbc\", and \"abdcdbcc\", although obtainable, have only 3 subsequences \"ac\" and are thus suboptimal.\n        It can be shown that it is not possible to get more than 4 subsequences \"ac\" by adding only one character.\n        Example 2:\n        Input: text = \"aabb\", pattern = \"ab\"\n        Output: 6\n        Explanation:\n        Some of the strings which can be obtained from text and have 6 subsequences \"ab\" are \"aaabb\", \"aaabb\", and \"aabbb\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2208,
-        "title": "Minimum Operations to Halve Array Sum",
-        "question": "class Solution:\n    def halveArray(self, nums: List[int]) -> int:\n        \"\"\"\n        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.)\n        Return the minimum number of operations to reduce the sum of nums by at least half.\n        Example 1:\n        Input: nums = [5,19,8,1]\n        Output: 3\n        Explanation: The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.\n        The following is one of the ways to reduce the sum by at least half:\n        Pick the number 19 and reduce it to 9.5.\n        Pick the number 9.5 and reduce it to 4.75.\n        Pick the number 8 and reduce it to 4.\n        The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. \n        The 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.\n        Overall, 3 operations were used so we return 3.\n        It can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n        Example 2:\n        Input: nums = [3,8,20]\n        Output: 3\n        Explanation: The initial sum of nums is equal to 3 + 8 + 20 = 31.\n        The following is one of the ways to reduce the sum by at least half:\n        Pick the number 20 and reduce it to 10.\n        Pick the number 10 and reduce it to 5.\n        Pick the number 3 and reduce it to 1.5.\n        The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. \n        The 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.\n        Overall, 3 operations were used so we return 3.\n        It can be shown that we cannot reduce the sum by at least half in less than 3 operations.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2209,
-        "title": "Minimum White Tiles After Covering With Carpets",
-        "question": "class Solution:\n    def minimumWhiteTiles(self, floor: str, numCarpets: int, carpetLen: int) -> int:\n        \"\"\"\n        You are given a 0-indexed binary string floor, which represents the colors of tiles on a floor:\n            floor[i] = '0' denotes that the ith tile of the floor is colored black.\n            On the other hand, floor[i] = '1' denotes that the ith tile of the floor is colored white.\n        You 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.\n        Return the minimum number of white tiles still visible.\n        Example 1:\n        Input: floor = \"10110101\", numCarpets = 2, carpetLen = 2\n        Output: 2\n        Explanation: \n        The figure above shows one way of covering the tiles with the carpets such that only 2 white tiles are visible.\n        No other way of covering the tiles with the carpets can leave less than 2 white tiles visible.\n        Example 2:\n        Input: floor = \"11111\", numCarpets = 2, carpetLen = 3\n        Output: 0\n        Explanation: \n        The figure above shows one way of covering the tiles with the carpets such that no white tiles are visible.\n        Note that the carpets are able to overlap one another.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2190,
-        "title": "Most Frequent Number Following Key In an Array",
-        "question": "class Solution:\n    def mostFrequent(self, nums: List[int], key: int) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums. You are also given an integer key, which is present in nums.\n        For 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:\n            0 <= i <= nums.length - 2,\n            nums[i] == key and,\n            nums[i + 1] == target.\n        Return the target with the maximum count. The test cases will be generated such that the target with maximum count is unique.\n        Example 1:\n        Input: nums = [1,100,200,1,100], key = 1\n        Output: 100\n        Explanation: For target = 100, there are 2 occurrences at indices 1 and 4 which follow an occurrence of key.\n        No other integers follow an occurrence of key, so we return 100.\n        Example 2:\n        Input: nums = [2,2,2,2,3], key = 2\n        Output: 2\n        Explanation: For target = 2, there are 3 occurrences at indices 1, 2, and 3 which follow an occurrence of key.\n        For target = 3, there is only one occurrence at index 4 which follows an occurrence of key.\n        target = 2 has the maximum number of occurrences following an occurrence of key, so we return 2.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2210,
-        "title": "Count Hills and Valleys in an Array",
-        "question": "class Solution:\n    def countHillValley(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i]. Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].\n        Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.\n        Return the number of hills and valleys in nums.\n        Example 1:\n        Input: nums = [2,4,1,1,6,5]\n        Output: 3\n        Explanation:\n        At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.\n        At index 1: The closest non-equal neighbors of 4 are 2 and 1. Since 4 > 2 and 4 > 1, index 1 is a hill. \n        At index 2: The closest non-equal neighbors of 1 are 4 and 6. Since 1 < 4 and 1 < 6, index 2 is a valley.\n        At 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.\n        At index 4: The closest non-equal neighbors of 6 are 1 and 5. Since 6 > 1 and 6 > 5, index 4 is a hill.\n        At index 5: There is no non-equal neighbor of 5 on the right, so index 5 is neither a hill nor a valley. \n        There are 3 hills and valleys so we return 3.\n        Example 2:\n        Input: nums = [6,6,5,5,4,1]\n        Output: 0\n        Explanation:\n        At index 0: There is no non-equal neighbor of 6 on the left, so index 0 is neither a hill nor a valley.\n        At index 1: There is no non-equal neighbor of 6 on the left, so index 1 is neither a hill nor a valley.\n        At 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.\n        At 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.\n        At 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.\n        At index 5: There is no non-equal neighbor of 1 on the right, so index 5 is neither a hill nor a valley.\n        There are 0 hills and valleys so we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2211,
-        "title": "Count Collisions on a Road",
-        "question": "class Solution:\n    def countCollisions(self, directions: str) -> int:\n        \"\"\"\n        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.\n        You 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.\n        The number of collisions can be calculated as follows:\n            When two cars moving in opposite directions collide with each other, the number of collisions increases by 2.\n            When a moving car collides with a stationary car, the number of collisions increases by 1.\n        After 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.\n        Return the total number of collisions that will happen on the road.\n        Example 1:\n        Input: directions = \"RLRSLL\"\n        Output: 5\n        Explanation:\n        The 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.\n        Thus, the total number of collisions that will happen on the road is 5. \n        Example 2:\n        Input: directions = \"LLRR\"\n        Output: 0\n        Explanation:\n        No cars will collide with each other. Thus, the total number of collisions that will happen on the road is 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2212,
-        "title": "Maximum Points in an Archery Competition",
-        "question": "class Solution:\n    def maximumBobPoints(self, numArrows: int, aliceArrows: List[int]) -> List[int]:\n        \"\"\"\n        Alice and Bob are opponents in an archery competition. The competition has set the following rules:\n            Alice first shoots numArrows arrows and then Bob shoots numArrows arrows.\n            The points are then calculated as follows:\n                The target has integer scoring sections ranging from 0 to 11 inclusive.\n                For 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.\n                However, if ak == bk == 0, then nobody takes k points.\n            For 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.\n        You 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.\n        Return 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.\n        If there are multiple ways for Bob to earn the maximum total points, return any one of them.\n        Example 1:\n        Input: numArrows = 9, aliceArrows = [1,1,0,1,0,0,2,1,0,1,2,0]\n        Output: [0,0,0,0,1,1,0,0,1,2,3,1]\n        Explanation: The table above shows how the competition is scored. \n        Bob earns a total point of 4 + 5 + 8 + 9 + 10 + 11 = 47.\n        It can be shown that Bob cannot obtain a score higher than 47 points.\n        Example 2:\n        Input: numArrows = 3, aliceArrows = [0,0,1,0,0,0,0,0,0,0,0,2]\n        Output: [0,0,0,0,0,0,0,0,1,1,1,0]\n        Explanation: The table above shows how the competition is scored.\n        Bob earns a total point of 8 + 9 + 10 = 27.\n        It can be shown that Bob cannot obtain a score higher than 27 points.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2213,
-        "title": "Longest Substring of One Repeating Character",
-        "question": "class Solution:\n    def longestRepeating(self, s: str, queryCharacters: str, queryIndices: List[int]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed string s. You are also given a 0-indexed string queryCharacters of length k and a 0-indexed array of integer indices queryIndices of length k, both of which are used to describe k queries.\n        The ith query updates the character in s at index queryIndices[i] to the character queryCharacters[i].\n        Return an array lengths of length k where lengths[i] is the length of the longest substring of s consisting of only one repeating character after the ith query is performed.\n        Example 1:\n        Input: s = \"babacc\", queryCharacters = \"bcb\", queryIndices = [1,3,3]\n        Output: [3,3,4]\n        Explanation: \n        - 1st query updates s = \"bbbacc\". The longest substring consisting of one repeating character is \"bbb\" with length 3.\n        - 2nd query updates s = \"bbbccc\". \n          The longest substring consisting of one repeating character can be \"bbb\" or \"ccc\" with length 3.\n        - 3rd query updates s = \"bbbbcc\". The longest substring consisting of one repeating character is \"bbbb\" with length 4.\n        Thus, we return [3,3,4].\n        Example 2:\n        Input: s = \"abyzz\", queryCharacters = \"aa\", queryIndices = [2,1]\n        Output: [2,3]\n        Explanation:\n        - 1st query updates s = \"abazz\". The longest substring consisting of one repeating character is \"zz\" with length 2.\n        - 2nd query updates s = \"aaazz\". The longest substring consisting of one repeating character is \"aaa\" with length 3.\n        Thus, we return [2,3].\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2200,
-        "title": "Find All K-Distant Indices in an Array",
-        "question": "class Solution:\n    def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:\n        \"\"\"\n        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.\n        Return a list of all k-distant indices sorted in increasing order.\n        Example 1:\n        Input: nums = [3,4,9,1,3,9,5], key = 9, k = 1\n        Output: [1,2,3,4,5,6]\n        Explanation: 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.\n        Thus, we return [1,2,3,4,5,6] which is sorted in increasing order. \n        Example 2:\n        Input: nums = [2,2,2,2,2], key = 2, k = 2\n        Output: [0,1,2,3,4]\n        Explanation: 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. \n        Hence, we return [0,1,2,3,4].\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2203,
-        "title": "Minimum Weighted Subgraph With the Required Paths",
-        "question": "class Solution:\n    def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int:\n        \"\"\"\n        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.\n        You 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.\n        Lastly, you are given three distinct integers src1, src2, and dest denoting three distinct nodes of the graph.\n        Return 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.\n        A 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:\n        Input: 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\n        Output: 9\n        Explanation:\n        The above figure represents the input graph.\n        The blue edges represent one of the subgraphs that yield the optimal answer.\n        Note 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.\n        Example 2:\n        Input: n = 3, edges = [[0,1,1],[2,1,1]], src1 = 0, src2 = 1, dest = 2\n        Output: -1\n        Explanation:\n        The above figure represents the input graph.\n        It 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        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2220,
-        "title": "Minimum Bit Flips to Convert Number",
-        "question": "class Solution:\n    def minBitFlips(self, start: int, goal: int) -> int:\n        \"\"\"\n        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.\n            For 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.\n        Given two integers start and goal, return the minimum number of bit flips to convert start to goal.\n        Example 1:\n        Input: start = 10, goal = 7\n        Output: 3\n        Explanation: 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.\n        It can be shown we cannot convert 10 to 7 in less than 3 steps. Hence, we return 3.\n        Example 2:\n        Input: start = 3, goal = 4\n        Output: 3\n        Explanation: 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.\n        It can be shown we cannot convert 3 to 4 in less than 3 steps. Hence, we return 3.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2221,
-        "title": "Find Triangular Sum of an Array",
-        "question": "class Solution:\n    def triangularSum(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums, where nums[i] is a digit between 0 and 9 (inclusive).\n        The triangular sum of nums is the value of the only element present in nums after the following process terminates:\n            Let nums comprise of n elements. If n == 1, end the process. Otherwise, create a new 0-indexed integer array newNums of length n - 1.\n            For 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.\n            Replace the array nums with newNums.\n            Repeat the entire process starting from step 1.\n        Return the triangular sum of nums.\n        Example 1:\n        Input: nums = [1,2,3,4,5]\n        Output: 8\n        Explanation:\n        The above diagram depicts the process from which we obtain the triangular sum of the array.\n        Example 2:\n        Input: nums = [5]\n        Output: 5\n        Explanation:\n        Since there is only one element in nums, the triangular sum is the value of that element itself.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2222,
-        "title": "Number of Ways to Select Buildings",
-        "question": "class Solution:\n    def numberOfWays(self, s: str) -> int:\n        \"\"\"\n        You are given a 0-indexed binary string s which represents the types of buildings along a street where:\n            s[i] = '0' denotes that the ith building is an office and\n            s[i] = '1' denotes that the ith building is a restaurant.\n        As 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.\n            For 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.\n        Return the number of valid ways to select 3 buildings.\n        Example 1:\n        Input: s = \"001101\"\n        Output: 6\n        Explanation: \n        The 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\"\n        No other selection is valid. Thus, there are 6 total ways.\n        Example 2:\n        Input: s = \"11100\"\n        Output: 0\n        Explanation: It can be shown that there are no valid selections.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2223,
-        "title": "Sum of Scores of Built Strings",
-        "question": "class Solution:\n    def sumScores(self, s: str) -> int:\n        \"\"\"\n        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.\n            For example, for s = \"abaca\", s1 == \"a\", s2 == \"ca\", s3 == \"aca\", etc.\n        The score of si is the length of the longest common prefix between si and sn (Note that s == sn).\n        Given the final string s, return the sum of the score of every si.\n        Example 1:\n        Input: s = \"babab\"\n        Output: 9\n        Explanation:\n        For s1 == \"b\", the longest common prefix is \"b\" which has a score of 1.\n        For s2 == \"ab\", there is no common prefix so the score is 0.\n        For s3 == \"bab\", the longest common prefix is \"bab\" which has a score of 3.\n        For s4 == \"abab\", there is no common prefix so the score is 0.\n        For s5 == \"babab\", the longest common prefix is \"babab\" which has a score of 5.\n        The sum of the scores is 1 + 0 + 3 + 0 + 5 = 9, so we return 9.\n        Example 2:\n        Input: s = \"azbazbzaz\"\n        Output: 14\n        Explanation: \n        For s2 == \"az\", the longest common prefix is \"az\" which has a score of 2.\n        For s6 == \"azbzaz\", the longest common prefix is \"azb\" which has a score of 3.\n        For s9 == \"azbazbzaz\", the longest common prefix is \"azbazbzaz\" which has a score of 9.\n        For all other si, the score is 0.\n        The sum of the scores is 2 + 3 + 9 = 14, so we return 14.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2231,
-        "title": "Largest Number After Digit Swaps by Parity",
-        "question": "class Solution:\n    def largestInteger(self, num: int) -> int:\n        \"\"\"\n        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).\n        Return the largest possible value of num after any number of swaps.\n        Example 1:\n        Input: num = 1234\n        Output: 3412\n        Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.\n        Swap the digit 2 with the digit 4, this results in the number 3412.\n        Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.\n        Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.\n        Example 2:\n        Input: num = 65875\n        Output: 87655\n        Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.\n        Swap the first digit 5 with the digit 7, this results in the number 87655.\n        Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2232,
-        "title": "Minimize Result by Adding Parentheses to Expression",
-        "question": "class Solution:\n    def minimizeResult(self, expression: str) -> str:\n        \"\"\"\n        You are given a 0-indexed string expression of the form \"+\" where  and  represent positive integers.\n        Add 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 '+'.\n        Return 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.\n        The 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:\n        Input: expression = \"247+38\"\n        Output: \"2(47+38)\"\n        Explanation: The expression evaluates to 2 * (47 + 38) = 2 * 85 = 170.\n        Note that \"2(4)7+38\" is invalid because the right parenthesis must be to the right of the '+'.\n        It can be shown that 170 is the smallest possible value.\n        Example 2:\n        Input: expression = \"12+34\"\n        Output: \"1(2+3)4\"\n        Explanation: The expression evaluates to 1 * (2 + 3) * 4 = 1 * 5 * 4 = 20.\n        Example 3:\n        Input: expression = \"999+999\"\n        Output: \"(999+999)\"\n        Explanation: The expression evaluates to 999 + 999 = 1998.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2233,
-        "title": "Maximum Product After K Increments",
-        "question": "class Solution:\n    def maximumProduct(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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.\n        Return 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:\n        Input: nums = [0,4], k = 5\n        Output: 20\n        Explanation: Increment the first number 5 times.\n        Now nums = [5, 4], with a product of 5 * 4 = 20.\n        It can be shown that 20 is maximum product possible, so we return 20.\n        Note that there may be other ways to increment nums to have the maximum product.\n        Example 2:\n        Input: nums = [6,3,3,2], k = 2\n        Output: 216\n        Explanation: Increment the second number 1 time and increment the fourth number 1 time.\n        Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.\n        It can be shown that 216 is maximum product possible, so we return 216.\n        Note that there may be other ways to increment nums to have the maximum product.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2234,
-        "title": "Maximum Total Beauty of the Gardens",
-        "question": "class Solution:\n    def maximumBeauty(self, flowers: List[int], newFlowers: int, target: int, full: int, partial: int) -> int:\n        \"\"\"\n        Alice is a caretaker of n gardens and she wants to plant flowers to maximize the total beauty of all her gardens.\n        You 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.\n        A 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:\n            The number of complete gardens multiplied by full.\n            The 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.\n        Return the maximum total beauty that Alice can obtain after planting at most newFlowers flowers.\n        Example 1:\n        Input: flowers = [1,3,1,1], newFlowers = 7, target = 6, full = 12, partial = 1\n        Output: 14\n        Explanation: 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\n        The gardens will then be [3,6,2,2]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.\n        There is 1 garden that is complete.\n        The minimum number of flowers in the incomplete gardens is 2.\n        Thus, the total beauty is 1 * 12 + 2 * 1 = 12 + 2 = 14.\n        No other way of planting flowers can obtain a total beauty higher than 14.\n        Example 2:\n        Input: flowers = [2,4,5,3], newFlowers = 10, target = 5, full = 2, partial = 6\n        Output: 30\n        Explanation: 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\n        The gardens will then be [5,4,5,5]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.\n        There are 3 gardens that are complete.\n        The minimum number of flowers in the incomplete gardens is 4.\n        Thus, the total beauty is 3 * 2 + 4 * 6 = 6 + 24 = 30.\n        No other way of planting flowers can obtain a total beauty higher than 30.\n        Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2248,
-        "title": "Intersection of Multiple Arrays",
-        "question": "class Solution:\n    def intersection(self, nums: List[List[int]]) -> List[int]:\n        \"\"\"\n        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:\n        Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]\n        Output: [3,4]\n        Explanation: \n        The 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].\n        Example 2:\n        Input: nums = [[1,2,3],[4,5,6]]\n        Output: []\n        Explanation: \n        There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2249,
-        "title": "Count Lattice Points Inside a Circle",
-        "question": "class Solution:\n    def countLatticePoints(self, circles: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        Note:\n            A lattice point is a point with integer coordinates.\n            Points that lie on the circumference of a circle are also considered to be inside it.\n        Example 1:\n        Input: circles = [[2,2,1]]\n        Output: 5\n        Explanation:\n        The figure above shows the given circle.\n        The lattice points present inside the circle are (1, 2), (2, 1), (2, 2), (2, 3), and (3, 2) and are shown in green.\n        Other points such as (1, 1) and (1, 3), which are shown in red, are not considered inside the circle.\n        Hence, the number of lattice points present inside at least one circle is 5.\n        Example 2:\n        Input: circles = [[2,2,2],[3,4,1]]\n        Output: 16\n        Explanation:\n        The figure above shows the given circles.\n        There are exactly 16 lattice points which are present inside at least one circle. \n        Some of them are (0, 2), (2, 0), (2, 4), (3, 2), and (4, 4).\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2250,
-        "title": "Count Number of Rectangles Containing Each Point",
-        "question": "class Solution:\n    def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n        \"\"\"\n        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).\n        The ith rectangle has its bottom-left corner point at the coordinates (0, 0) and its top-right corner point at (li, hi).\n        Return an integer array count of length points.length where count[j] is the number of rectangles that contain the jth point.\n        The 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:\n        Input: rectangles = [[1,2],[2,3],[2,5]], points = [[2,1],[1,4]]\n        Output: [2,1]\n        Explanation: \n        The first rectangle contains no points.\n        The second rectangle contains only the point (2, 1).\n        The third rectangle contains the points (2, 1) and (1, 4).\n        The number of rectangles that contain the point (2, 1) is 2.\n        The number of rectangles that contain the point (1, 4) is 1.\n        Therefore, we return [2, 1].\n        Example 2:\n        Input: rectangles = [[1,1],[2,2],[3,3]], points = [[1,3],[1,1]]\n        Output: [1,3]\n        Explanation:\n        The first rectangle contains only the point (1, 1).\n        The second rectangle contains only the point (1, 1).\n        The third rectangle contains the points (1, 3) and (1, 1).\n        The number of rectangles that contain the point (1, 3) is 1.\n        The number of rectangles that contain the point (1, 1) is 3.\n        Therefore, we return [1, 3].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2251,
-        "title": "Number of Flowers in Full Bloom",
-        "question": "class Solution:\n    def fullBloomFlowers(self, flowers: List[List[int]], persons: List[int]) -> List[int]:\n        \"\"\"\n        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 persons of size n, where persons[i] is the time that the ith person will arrive to see the flowers.\n        Return 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:\n        Input: flowers = [[1,6],[3,7],[9,12],[4,13]], persons = [2,3,7,11]\n        Output: [1,2,2,2]\n        Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\n        For each person, we return the number of flowers in full bloom during their arrival.\n        Example 2:\n        Input: flowers = [[1,10],[3,3]], persons = [3,3,2]\n        Output: [2,2,1]\n        Explanation: The figure above shows the times when the flowers are in full bloom and when the people arrive.\n        For each person, we return the number of flowers in full bloom during their arrival.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2259,
-        "title": "Remove Digit From Number to Maximize Result",
-        "question": "class Solution:\n    def removeDigit(self, number: str, digit: str) -> str:\n        \"\"\"\n        You are given a string number representing a positive integer and a character digit.\n        Return 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:\n        Input: number = \"123\", digit = \"3\"\n        Output: \"12\"\n        Explanation: There is only one '3' in \"123\". After removing '3', the result is \"12\".\n        Example 2:\n        Input: number = \"1231\", digit = \"1\"\n        Output: \"231\"\n        Explanation: We can remove the first '1' to get \"231\" or remove the second '1' to get \"123\".\n        Since 231 > 123, we return \"231\".\n        Example 3:\n        Input: number = \"551\", digit = \"5\"\n        Output: \"51\"\n        Explanation: We can remove either the first or second '5' from \"551\".\n        Both result in the string \"51\".\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2260,
-        "title": "Minimum Consecutive Cards to Pick Up",
-        "question": "class Solution:\n    def minimumCardPickup(self, cards: List[int]) -> int:\n        \"\"\"\n        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.\n        Return 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:\n        Input: cards = [3,4,2,3,4,7]\n        Output: 4\n        Explanation: 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.\n        Example 2:\n        Input: cards = [1,0,5,3]\n        Output: -1\n        Explanation: There is no way to pick up a set of consecutive cards that contain a pair of matching cards.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2261,
-        "title": "K Divisible Elements Subarrays",
-        "question": "class Solution:\n    def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n        \"\"\"\n        Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p.\n        Two arrays nums1 and nums2 are said to be distinct if:\n            They are of different lengths, or\n            There exists at least one index i where nums1[i] != nums2[i].\n        A subarray is defined as a non-empty contiguous sequence of elements in an array.\n        Example 1:\n        Input: nums = [2,3,3,2,2], k = 2, p = 2\n        Output: 11\n        Explanation:\n        The elements at indices 0, 3, and 4 are divisible by p = 2.\n        The 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].\n        Note that the subarrays [2] and [3] occur more than once in nums, but they should each be counted only once.\n        The subarray [2,3,3,2,2] should not be counted because it has 3 elements that are divisible by 2.\n        Example 2:\n        Input: nums = [1,2,3,4], k = 4, p = 1\n        Output: 10\n        Explanation:\n        All element of nums are divisible by p = 1.\n        Also, every subarray of nums will have at most 4 elements that are divisible by 1.\n        Since all subarrays are distinct, the total number of subarrays satisfying all the constraints is 10.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2262,
-        "title": "Total Appeal of A String",
-        "question": "class Solution:\n    def appealSum(self, s: str) -> int:\n        \"\"\"\n        The appeal of a string is the number of distinct characters found in the string.\n            For example, the appeal of \"abbca\" is 3 because it has 3 distinct characters: 'a', 'b', and 'c'.\n        Given a string s, return the total appeal of all of its substrings.\n        A substring is a contiguous sequence of characters within a string.\n        Example 1:\n        Input: s = \"abbca\"\n        Output: 28\n        Explanation: 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.\n        The total sum is 5 + 7 + 7 + 6 + 3 = 28.\n        Example 2:\n        Input: s = \"code\"\n        Output: 20\n        Explanation: 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.\n        The total sum is 4 + 6 + 6 + 4 = 20.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2255,
-        "title": "Count Prefixes of a Given String",
-        "question": "class Solution:\n    def countPrefixes(self, words: List[str], s: str) -> int:\n        \"\"\"\n        You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.\n        Return the number of strings in words that are a prefix of s.\n        A 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:\n        Input: words = [\"a\",\"b\",\"c\",\"ab\",\"bc\",\"abc\"], s = \"abc\"\n        Output: 3\n        Explanation:\n        The strings in words which are a prefix of s = \"abc\" are:\n        \"a\", \"ab\", and \"abc\".\n        Thus the number of strings in words which are a prefix of s is 3.\n        Example 2:\n        Input: words = [\"a\",\"a\"], s = \"aa\"\n        Output: 2\n        Explanation:\n        Both of the strings are a prefix of s. \n        Note that the same string can occur multiple times in words, and it should be counted each time.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2256,
-        "title": "Minimum Average Difference",
-        "question": "class Solution:\n    def minimumAverageDifference(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums of length n.\n        The average difference of the index i is the absolute difference between the average of the first i + 1 elements of nums and the average of the last n - i - 1 elements. Both averages should be rounded down to the nearest integer.\n        Return the index with the minimum average difference. If there are multiple such indices, return the smallest one.\n        Note:\n            The absolute difference of two numbers is the absolute value of their difference.\n            The average of n elements is the sum of the n elements divided (integer division) by n.\n            The average of 0 elements is considered to be 0.\n        Example 1:\n        Input: nums = [2,5,3,9,5,3]\n        Output: 3\n        Explanation:\n        - The average difference of index 0 is: |2 / 1 - (5 + 3 + 9 + 5 + 3) / 5| = |2 / 1 - 25 / 5| = |2 - 5| = 3.\n        - The average difference of index 1 is: |(2 + 5) / 2 - (3 + 9 + 5 + 3) / 4| = |7 / 2 - 20 / 4| = |3 - 5| = 2.\n        - The average difference of index 2 is: |(2 + 5 + 3) / 3 - (9 + 5 + 3) / 3| = |10 / 3 - 17 / 3| = |3 - 5| = 2.\n        - The average difference of index 3 is: |(2 + 5 + 3 + 9) / 4 - (5 + 3) / 2| = |19 / 4 - 8 / 2| = |4 - 4| = 0.\n        - The average difference of index 4 is: |(2 + 5 + 3 + 9 + 5) / 5 - 3 / 1| = |24 / 5 - 3 / 1| = |4 - 3| = 1.\n        - The average difference of index 5 is: |(2 + 5 + 3 + 9 + 5 + 3) / 6 - 0| = |27 / 6 - 0| = |4 - 0| = 4.\n        The average difference of index 3 is the minimum average difference so return 3.\n        Example 2:\n        Input: nums = [0]\n        Output: 0\n        Explanation:\n        The only index is 0 so return 0.\n        The average difference of index 0 is: |0 / 1 - 0| = |0 - 0| = 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2257,
-        "title": "Count Unguarded Cells in the Grid",
-        "question": "class Solution:\n    def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        A 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.\n        Return the number of unoccupied cells that are not guarded.\n        Example 1:\n        Input: m = 4, n = 6, guards = [[0,0],[1,1],[2,3]], walls = [[0,1],[2,2],[1,4]]\n        Output: 7\n        Explanation: The guarded and unguarded cells are shown in red and green respectively in the above diagram.\n        There are a total of 7 unguarded cells, so we return 7.\n        Example 2:\n        Input: m = 3, n = 3, guards = [[1,1]], walls = [[0,1],[1,0],[2,1],[1,2]]\n        Output: 4\n        Explanation: The unguarded cells are shown in green in the above diagram.\n        There are a total of 4 unguarded cells, so we return 4.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2258,
-        "title": "Escape the Spreading Fire",
-        "question": "class Solution:\n    def maximumMinutes(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        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:\n            0 represents grass,\n            1 represents fire,\n            2 represents a wall that you and fire cannot pass through.\n        You 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.\n        Return 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.\n        Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse.\n        A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).\n        Example 1:\n        Input: 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]]\n        Output: 3\n        Explanation: The figure above shows the scenario where you stay in the initial position for 3 minutes.\n        You will still be able to safely reach the safehouse.\n        Staying for more than 3 minutes will not allow you to safely reach the safehouse.\n        Example 2:\n        Input: grid = [[0,0,0,0],[0,1,2,0],[0,2,0,0]]\n        Output: -1\n        Explanation: The figure above shows the scenario where you immediately move towards the safehouse.\n        Fire will spread to any cell you move towards and it is impossible to safely reach the safehouse.\n        Thus, -1 is returned.\n        Example 3:\n        Input: grid = [[0,0,0],[2,2,0],[1,2,0]]\n        Output: 1000000000\n        Explanation: The figure above shows the initial grid.\n        Notice that the fire is contained by walls and you will always be able to safely reach the safehouse.\n        Thus, 109 is returned.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2224,
-        "title": "Minimum Number of Operations to Convert Time",
-        "question": "class Solution:\n    def convertTime(self, current: str, correct: str) -> int:\n        \"\"\"\n        You are given two strings current and correct representing two 24-hour times.\n        24-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.\n        In one operation you can increase the time current by 1, 5, 15, or 60 minutes. You can perform this operation any number of times.\n        Return the minimum number of operations needed to convert current to correct.\n        Example 1:\n        Input: current = \"02:30\", correct = \"04:35\"\n        Output: 3\n        Explanation:\n        We 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\".\n        It can be proven that it is not possible to convert current to correct in fewer than 3 operations.\n        Example 2:\n        Input: current = \"11:00\", correct = \"11:01\"\n        Output: 1\n        Explanation: We only have to add one minute to current, so the minimum number of operations needed is 1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2264,
-        "title": "Largest 3-Same-Digit Number in String",
-        "question": "class Solution:\n    def largestGoodInteger(self, num: str) -> str:\n        \"\"\"\n        You are given a string num representing a large integer. An integer is good if it meets the following conditions:\n            It is a substring of num with length 3.\n            It consists of only one unique digit.\n        Return the maximum good integer as a string or an empty string \"\" if no such integer exists.\n        Note:\n            A substring is a contiguous sequence of characters within a string.\n            There may be leading zeroes in num or a good integer.\n        Example 1:\n        Input: num = \"6777133339\"\n        Output: \"777\"\n        Explanation: There are two distinct good integers: \"777\" and \"333\".\n        \"777\" is the largest, so we return \"777\".\n        Example 2:\n        Input: num = \"2300019\"\n        Output: \"000\"\n        Explanation: \"000\" is the only good integer.\n        Example 3:\n        Input: num = \"42352338\"\n        Output: \"\"\n        Explanation: No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2265,
-        "title": "Count Nodes Equal to Average of Subtree",
-        "question": "class Solution:\n    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:\n        \"\"\"\n        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.\n        Note:\n            The average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.\n            A subtree of root is a tree consisting of root and all of its descendants.\n        Example 1:\n        Input: root = [4,8,5,0,1,null,6]\n        Output: 5\n        Explanation: \n        For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.\n        For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.\n        For the node with value 0: The average of its subtree is 0 / 1 = 0.\n        For the node with value 1: The average of its subtree is 1 / 1 = 1.\n        For the node with value 6: The average of its subtree is 6 / 1 = 6.\n        Example 2:\n        Input: root = [1]\n        Output: 1\n        Explanation: For the node with value 1: The average of its subtree is 1 / 1 = 1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2266,
-        "title": "Count Number of Texts",
-        "question": "class Solution:\n    def countTexts(self, pressedKeys: str) -> int:\n        \"\"\"\n        Alice is texting Bob using her phone. The mapping of digits to letters is shown in the figure below.\n        In 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.\n            For 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.\n            Note that the digits '0' and '1' do not map to any letters, so Alice does not use them.\n        However, due to an error in transmission, Bob did not receive Alice's text message but received a string of pressed keys instead.\n            For example, when Alice sent the message \"bob\", Bob received the string \"2266622\".\n        Given a string pressedKeys representing the string received by Bob, return the total number of possible text messages Alice could have sent.\n        Since the answer may be very large, return it modulo 109 + 7.\n        Example 1:\n        Input: pressedKeys = \"22233\"\n        Output: 8\n        Explanation:\n        The possible text messages Alice could have sent are:\n        \"aaadd\", \"abdd\", \"badd\", \"cdd\", \"aaae\", \"abe\", \"bae\", and \"ce\".\n        Since there are 8 possible messages, we return 8.\n        Example 2:\n        Input: pressedKeys = \"222222222222222222222222222222222222\"\n        Output: 82876089\n        Explanation:\n        There are 2082876103 possible text messages Alice could have sent.\n        Since we need to return the answer modulo 109 + 7, we return 2082876103 % (109 + 7) = 82876089.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2267,
-        "title": " Check if There Is a Valid Parentheses String Path",
-        "question": "class Solution:\n    def hasValidPath(self, grid: List[List[str]]) -> bool:\n        \"\"\"\n        A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:\n            It is ().\n            It can be written as AB (A concatenated with B), where A and B are valid parentheses strings.\n            It can be written as (A), where A is a valid parentheses string.\n        You 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:\n            The path starts from the upper left cell (0, 0).\n            The path ends at the bottom-right cell (m - 1, n - 1).\n            The path only ever moves down or right.\n            The resulting parentheses string formed by the path is valid.\n        Return true if there exists a valid parentheses string path in the grid. Otherwise, return false.\n        Example 1:\n        Input: grid = [[\"(\",\"(\",\"(\"],[\")\",\"(\",\")\"],[\"(\",\"(\",\")\"],[\"(\",\"(\",\")\"]]\n        Output: true\n        Explanation: The above diagram shows two possible paths that form valid parentheses strings.\n        The first path shown results in the valid parentheses string \"()(())\".\n        The second path shown results in the valid parentheses string \"((()))\".\n        Note that there may be other valid parentheses string paths.\n        Example 2:\n        Input: grid = [[\")\",\")\"],[\"(\",\"(\"]]\n        Output: false\n        Explanation: The two possible paths form the parentheses strings \"))(\" and \")((\". Since neither of them are valid parentheses strings, we return false.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2239,
-        "title": "Find Closest Number to Zero",
-        "question": "class Solution:\n    def findClosestNumber(self, nums: List[int]) -> int:\n        \"\"\"\n        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:\n        Input: nums = [-4,-2,1,4,8]\n        Output: 1\n        Explanation:\n        The distance from -4 to 0 is |-4| = 4.\n        The distance from -2 to 0 is |-2| = 2.\n        The distance from 1 to 0 is |1| = 1.\n        The distance from 4 to 0 is |4| = 4.\n        The distance from 8 to 0 is |8| = 8.\n        Thus, the closest number to 0 in the array is 1.\n        Example 2:\n        Input: nums = [2,-1,1]\n        Output: 1\n        Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2240,
-        "title": "Number of Ways to Buy Pens and Pencils",
-        "question": "class Solution:\n    def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:\n        \"\"\"\n        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.\n        Return the number of distinct ways you can buy some number of pens and pencils.\n        Example 1:\n        Input: total = 20, cost1 = 10, cost2 = 5\n        Output: 9\n        Explanation: 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.\n        The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.\n        Example 2:\n        Input: total = 5, cost1 = 10, cost2 = 10\n        Output: 1\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2241,
-        "title": "Design an ATM Machine",
-        "question": "class ATM:\n    def __init__(self):\n    def deposit(self, banknotesCount: List[int]) -> None:\n    def withdraw(self, amount: int) -> List[int]:\n        \"\"\"\n        There is an ATM machine that stores banknotes of 5 denominations: 20, 50, 100, 200, and 500 dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.\n        When withdrawing, the machine prioritizes using banknotes of larger values.\n            For example, if you want to withdraw $300 and there are 2 $50 banknotes, 1 $100 banknote, and 1 $200 banknote, then the machine will use the $100 and $200 banknotes.\n            However, if you try to withdraw $600 and there are 3 $200 banknotes and 1 $500 banknote, then the withdraw request will be rejected because the machine will first try to use the $500 banknote and then be unable to use banknotes to complete the remaining $100. Note that the machine is not allowed to use the $200 banknotes instead of the $500 banknote.\n        Implement the ATM class:\n            ATM() Initializes the ATM object.\n            void deposit(int[] banknotesCount) Deposits new banknotes in the order $20, $50, $100, $200, and $500.\n            int[] withdraw(int amount) Returns an array of length 5 of the number of banknotes that will be handed to the user in the order $20, $50, $100, $200, and $500, and update the number of banknotes in the ATM after withdrawing. Returns [-1] if it is not possible (do not withdraw any banknotes in this case).\n        Example 1:\n        Input\n        [\"ATM\", \"deposit\", \"withdraw\", \"deposit\", \"withdraw\", \"withdraw\"]\n        [[], [[0,0,1,2,1]], [600], [[0,1,0,1,1]], [600], [550]]\n        Output\n        [null, null, [0,0,1,0,1], null, [-1], [0,1,0,0,1]]\n        Explanation\n        ATM atm = new ATM();\n        atm.deposit([0,0,1,2,1]); // Deposits 1 $100 banknote, 2 $200 banknotes,\n                                  // and 1 $500 banknote.\n        atm.withdraw(600);        // Returns [0,0,1,0,1]. The machine uses 1 $100 banknote\n                                  // and 1 $500 banknote. The banknotes left over in the\n                                  // machine are [0,0,0,2,0].\n        atm.deposit([0,1,0,1,1]); // Deposits 1 $50, $200, and $500 banknote.\n                                  // The banknotes in the machine are now [0,1,0,3,1].\n        atm.withdraw(600);        // Returns [-1]. The machine will try to use a $500 banknote\n                                  // and then be unable to complete the remaining $100,\n                                  // so the withdraw request will be rejected.\n                                  // Since the request is rejected, the number of banknotes\n                                  // in the machine is not modified.\n        atm.withdraw(550);        // Returns [0,1,0,0,1]. The machine uses 1 $50 banknote\n                                  // and 1 $500 banknote.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2242,
-        "title": "Maximum Score of a Node Sequence",
-        "question": "class Solution:\n    def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:\n        \"\"\"\n        There is an undirected graph with n nodes, numbered from 0 to n - 1.\n        You 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.\n        A node sequence is valid if it meets the following conditions:\n            There is an edge connecting every pair of adjacent nodes in the sequence.\n            No node appears more than once in the sequence.\n        The score of a node sequence is defined as the sum of the scores of the nodes in the sequence.\n        Return the maximum score of a valid node sequence with a length of 4. If no such sequence exists, return -1.\n        Example 1:\n        Input: scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\n        Output: 24\n        Explanation: The figure above shows the graph and the chosen node sequence [0,1,2,3].\n        The score of the node sequence is 5 + 2 + 9 + 8 = 24.\n        It can be shown that no other node sequence has a score of more than 24.\n        Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.\n        The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.\n        Example 2:\n        Input: scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]\n        Output: -1\n        Explanation: The figure above shows the graph.\n        There are no valid node sequences of length 4, so we return -1.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2274,
-        "title": "Maximum Consecutive Floors Without Special Floors",
-        "question": "class Solution:\n    def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:\n        \"\"\"\n        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.\n        You 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.\n        Return the maximum number of consecutive floors without a special floor.\n        Example 1:\n        Input: bottom = 2, top = 9, special = [4,6]\n        Output: 3\n        Explanation: 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.\n        Therefore, we return the maximum number which is 3 floors.\n        Example 2:\n        Input: bottom = 6, top = 8, special = [7,6,8]\n        Output: 0\n        Explanation: Every floor rented is a special floor, so we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2275,
-        "title": "Largest Combination With Bitwise AND Greater Than Zero",
-        "question": "class Solution:\n    def largestCombination(self, candidates: List[int]) -> int:\n        \"\"\"\n        The bitwise AND of an array nums is the bitwise AND of all integers in nums.\n            For example, for nums = [1, 5, 3], the bitwise AND is equal to 1 & 5 & 3 = 1.\n            Also, for nums = [7], the bitwise AND is 7.\n        You 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.\n        Return the size of the largest combination of candidates with a bitwise AND greater than 0.\n        Example 1:\n        Input: candidates = [16,17,71,62,12,24,14]\n        Output: 4\n        Explanation: The combination [16,17,62,24] has a bitwise AND of 16 & 17 & 62 & 24 = 16 > 0.\n        The size of the combination is 4.\n        It can be shown that no combination with a size greater than 4 has a bitwise AND greater than 0.\n        Note that more than one combination may have the largest size.\n        For example, the combination [62,12,24,14] has a bitwise AND of 62 & 12 & 24 & 14 = 8 > 0.\n        Example 2:\n        Input: candidates = [8,8]\n        Output: 2\n        Explanation: The largest combination [8,8] has a bitwise AND of 8 & 8 = 8 > 0.\n        The size of the combination is 2, so we return 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2276,
-        "title": "Count Integers in Intervals",
-        "question": "class CountIntervals:\n    def __init__(self):\n    def add(self, left: int, right: int) -> None:\n    def count(self) -> int:\n        \"\"\"\n        Given an empty set of intervals, implement a data structure that can:\n            Add an interval to the set of intervals.\n            Count the number of integers that are present in at least one interval.\n        Implement the CountIntervals class:\n            CountIntervals() Initializes the object with an empty set of intervals.\n            void add(int left, int right) Adds the interval [left, right] to the set of intervals.\n            int count() Returns the number of integers that are present in at least one interval.\n        Note that an interval [left, right] denotes all the integers x where left <= x <= right.\n        Example 1:\n        Input\n        [\"CountIntervals\", \"add\", \"add\", \"count\", \"add\", \"count\"]\n        [[], [2, 3], [7, 10], [], [5, 8], []]\n        Output\n        [null, null, null, 6, null, 8]\n        Explanation\n        CountIntervals countIntervals = new CountIntervals(); // initialize the object with an empty set of intervals. \n        countIntervals.add(2, 3);  // add [2, 3] to the set of intervals.\n        countIntervals.add(7, 10); // add [7, 10] to the set of intervals.\n        countIntervals.count();    // return 6\n                                   // the integers 2 and 3 are present in the interval [2, 3].\n                                   // the integers 7, 8, 9, and 10 are present in the interval [7, 10].\n        countIntervals.add(5, 8);  // add [5, 8] to the set of intervals.\n        countIntervals.count();    // return 8\n                                   // the integers 2 and 3 are present in the interval [2, 3].\n                                   // the integers 5 and 6 are present in the interval [5, 8].\n                                   // the integers 7 and 8 are present in the intervals [5, 8] and [7, 10].\n                                   // the integers 9 and 10 are present in the interval [7, 10].\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2270,
-        "title": "Number of Ways to Split Array",
-        "question": "class Solution:\n    def waysToSplitArray(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums of length n.\n        nums contains a valid split at index i if the following are true:\n            The sum of the first i + 1 elements is greater than or equal to the sum of the last n - i - 1 elements.\n            There is at least one element to the right of i. That is, 0 <= i < n - 1.\n        Return the number of valid splits in nums.\n        Example 1:\n        Input: nums = [10,4,-8,7]\n        Output: 2\n        Explanation: \n        There 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.\n        Thus, the number of valid splits in nums is 2.\n        Example 2:\n        Input: nums = [2,3,1,0]\n        Output: 2\n        Explanation: \n        There 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2271,
-        "title": "Maximum White Tiles Covered by a Carpet",
-        "question": "class Solution:\n    def maximumWhiteTiles(self, tiles: List[List[int]], carpetLen: int) -> int:\n        \"\"\"\n        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.\n        You are also given an integer carpetLen, the length of a single carpet that can be placed anywhere.\n        Return the maximum number of white tiles that can be covered by the carpet.\n        Example 1:\n        Input: tiles = [[1,5],[10,11],[12,18],[20,25],[30,32]], carpetLen = 10\n        Output: 9\n        Explanation: Place the carpet starting on tile 10. \n        It covers 9 white tiles, so we return 9.\n        Note that there may be other places where the carpet covers 9 white tiles.\n        It can be shown that the carpet cannot cover more than 9 white tiles.\n        Example 2:\n        Input: tiles = [[10,11],[1,1]], carpetLen = 2\n        Output: 2\n        Explanation: Place the carpet starting on tile 10. \n        It covers 2 white tiles, so we return 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2272,
-        "title": "Substring With Largest Variance",
-        "question": "class Solution:\n    def largestVariance(self, s: str) -> int:\n        \"\"\"\n        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.\n        Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s.\n        A substring is a contiguous sequence of characters within a string.\n        Example 1:\n        Input: s = \"aababbb\"\n        Output: 3\n        Explanation:\n        All 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\".\n        Since the largest possible variance is 3, we return it.\n        Example 2:\n        Input: s = \"abcde\"\n        Output: 0\n        Explanation:\n        No letter occurs more than once in s, so the variance of every substring is 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2243,
-        "title": "Calculate Digit Sum of a String",
-        "question": "class Solution:\n    def digitSum(self, s: str, k: int) -> str:\n        \"\"\"\n        You are given a string s consisting of digits and an integer k.\n        A round can be completed if the length of s is greater than k. In one round, do the following:\n            Divide 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.\n            Replace 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.\n            Merge consecutive groups together to form a new string. If the length of the string is greater than k, repeat from step 1.\n        Return s after all rounds have been completed.\n        Example 1:\n        Input: s = \"11111222223\", k = 3\n        Output: \"135\"\n        Explanation: \n        - For the first round, we divide s into groups of size 3: \"111\", \"112\", \"222\", and \"23\".\n          \u200b\u200b\u200b\u200b\u200bThen 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. \n        Now, s.length <= k, so we return \"135\" as the answer.\n        Example 2:\n        Input: s = \"00000000\", k = 3\n        Output: \"000\"\n        Explanation: \n        We divide s into \"000\", \"000\", and \"00\".\n        Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0. \n        s becomes \"0\" + \"0\" + \"0\" = \"000\", whose length is equal to k, so we return \"000\".\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2244,
-        "title": "Minimum Rounds to Complete All Tasks",
-        "question": "class Solution:\n    def minimumRounds(self, tasks: List[int]) -> int:\n        \"\"\"\n        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.\n        Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.\n        Example 1:\n        Input: tasks = [2,2,3,3,2,4,4,4,4,4]\n        Output: 4\n        Explanation: 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.  \n        It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.\n        Example 2:\n        Input: tasks = [2,3,3]\n        Output: -1\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2245,
-        "title": "Maximum Trailing Zeros in a Cornered Path",
-        "question": "class Solution:\n    def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.\n        A 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.\n        The product of a path is defined as the product of all the values in the path.\n        Return the maximum number of trailing zeros in the product of a cornered path found in grid.\n        Note:\n            Horizontal movement means moving in either the left or right direction.\n            Vertical movement means moving in either the up or down direction.\n        Example 1:\n        Input: 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]]\n        Output: 3\n        Explanation: The grid on the left shows a valid cornered path.\n        It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.\n        It can be shown that this is the maximum trailing zeros in the product of a cornered path.\n        The grid in the middle is not a cornered path as it has more than one turn.\n        The grid on the right is not a cornered path as it requires a return to a previously visited cell.\n        Example 2:\n        Input: grid = [[4,3,2],[7,6,1],[8,8,8]]\n        Output: 0\n        Explanation: The grid is shown in the figure above.\n        There are no cornered paths in the grid that result in a product with a trailing zero.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2246,
-        "title": "Longest Path With Different Adjacent Characters",
-        "question": "class Solution:\n    def longestPath(self, parent: List[int], s: str) -> int:\n        \"\"\"\n        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.\n        You are also given a string s of length n, where s[i] is the character assigned to node i.\n        Return 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:\n        Input: parent = [-1,0,0,1,1,2], s = \"abacbe\"\n        Output: 3\n        Explanation: 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.\n        It can be proven that there is no longer path that satisfies the conditions. \n        Example 2:\n        Input: parent = [-1,0,0,0], s = \"aabc\"\n        Output: 3\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2278,
-        "title": "Percentage of Letter in String",
-        "question": "class Solution:\n    def percentageLetter(self, s: str, letter: str) -> int:\n        \"\"\"\n        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:\n        Input: s = \"foobar\", letter = \"o\"\n        Output: 33\n        Explanation:\n        The percentage of characters in s that equal the letter 'o' is 2 / 6 * 100% = 33% when rounded down, so we return 33.\n        Example 2:\n        Input: s = \"jjjj\", letter = \"k\"\n        Output: 0\n        Explanation:\n        The percentage of characters in s that equal the letter 'k' is 0%, so we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2279,
-        "title": "Maximum Bags With Full Capacity of Rocks",
-        "question": "class Solution:\n    def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:\n        \"\"\"\n        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.\n        Return the maximum number of bags that could have full capacity after placing the additional rocks in some bags.\n        Example 1:\n        Input: capacity = [2,3,4,5], rocks = [1,2,4,4], additionalRocks = 2\n        Output: 3\n        Explanation:\n        Place 1 rock in bag 0 and 1 rock in bag 1.\n        The number of rocks in each bag are now [2,3,4,4].\n        Bags 0, 1, and 2 have full capacity.\n        There are 3 bags at full capacity, so we return 3.\n        It can be shown that it is not possible to have more than 3 bags at full capacity.\n        Note that there may be other ways of placing the rocks that result in an answer of 3.\n        Example 2:\n        Input: capacity = [10,2,2], rocks = [2,2,0], additionalRocks = 100\n        Output: 3\n        Explanation:\n        Place 8 rocks in bag 0 and 2 rocks in bag 2.\n        The number of rocks in each bag are now [10,2,2].\n        Bags 0, 1, and 2 have full capacity.\n        There are 3 bags at full capacity, so we return 3.\n        It can be shown that it is not possible to have more than 3 bags at full capacity.\n        Note that we did not use all of the additional rocks.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2280,
-        "title": "Minimum Lines to Represent a Line Chart",
-        "question": "class Solution:\n    def minimumLines(self, stockPrices: List[List[int]]) -> int:\n        \"\"\"\n        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:\n        Return the minimum number of lines needed to represent the line chart.\n        Example 1:\n        Input: stockPrices = [[1,7],[2,6],[3,5],[4,4],[5,4],[6,3],[7,2],[8,1]]\n        Output: 3\n        Explanation:\n        The diagram above represents the input, with the X-axis representing the day and Y-axis representing the price.\n        The 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).\n        It can be shown that it is not possible to represent the line chart using less than 3 lines.\n        Example 2:\n        Input: stockPrices = [[3,4],[1,2],[7,8],[2,3]]\n        Output: 1\n        Explanation:\n        As shown in the diagram above, the line chart can be represented with a single line.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2281,
-        "title": "Sum of Total Strength of Wizards",
-        "question": "class Solution:\n    def totalStrength(self, strength: List[int]) -> int:\n        \"\"\"\n        As the ruler of a kingdom, you have an army of wizards at your command.\n        You 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:\n            The strength of the weakest wizard in the group.\n            The total of all the individual strengths of the wizards in the group.\n        Return the sum of the total strengths of all contiguous groups of wizards. Since the answer may be very large, return it modulo 109 + 7.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: strength = [1,3,1,2]\n        Output: 44\n        Explanation: 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\n        The sum of all the total strengths is 1 + 9 + 1 + 4 + 4 + 4 + 3 + 5 + 6 + 7 = 44.\n        Example 2:\n        Input: strength = [5,4,6]\n        Output: 213\n        Explanation: 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\n        The sum of all the total strengths is 25 + 16 + 36 + 36 + 40 + 60 = 213.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2287,
-        "title": "Rearrange Characters to Make Target String",
-        "question": "class Solution:\n    def rearrangeCharacters(self, s: str, target: str) -> int:\n        \"\"\"\n        You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.\n        Return the maximum number of copies of target that can be formed by taking letters from s and rearranging them.\n        Example 1:\n        Input: s = \"ilovecodingonleetcode\", target = \"code\"\n        Output: 2\n        Explanation:\n        For the first copy of \"code\", take the letters at indices 4, 5, 6, and 7.\n        For the second copy of \"code\", take the letters at indices 17, 18, 19, and 20.\n        The strings that are formed are \"ecod\" and \"code\" which can both be rearranged into \"code\".\n        We can make at most two copies of \"code\", so we return 2.\n        Example 2:\n        Input: s = \"abcba\", target = \"abc\"\n        Output: 1\n        Explanation:\n        We can make one copy of \"abc\" by taking the letters at indices 0, 1, and 2.\n        We can make at most one copy of \"abc\", so we return 1.\n        Note 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\".\n        Example 3:\n        Input: s = \"abbaccaddaeea\", target = \"aaaaa\"\n        Output: 1\n        Explanation:\n        We can make one copy of \"aaaaa\" by taking the letters at indices 0, 3, 6, 9, and 12.\n        We can make at most one copy of \"aaaaa\", so we return 1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2288,
-        "title": "Apply Discount to Prices",
-        "question": "class Solution:\n    def discountPrices(self, sentence: str, discount: int) -> str:\n        \"\"\"\n        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.\n            For example, \"$100\", \"$23\", and \"$6\" represent prices while \"100\", \"$\", and \"$1e5\" do not.\n        You 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.\n        Return a string representing the modified sentence.\n        Note that all prices will contain at most 10 digits.\n        Example 1:\n        Input: sentence = \"there are $1 $2 and 5$ candies in the shop\", discount = 50\n        Output: \"there are $0.50 $1.00 and 5$ candies in the shop\"\n        Explanation: \n        The 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\".\n        Example 2:\n        Input: sentence = \"1 2 $3 4 $5 $6 7 8$ $9 $10$\", discount = 100\n        Output: \"1 2 $0.00 4 $0.00 $0.00 7 8$ $0.00 $10$\"\n        Explanation: \n        Applying a 100% discount on any price will result in 0.\n        The words representing prices are \"$3\", \"$5\", \"$6\", and \"$9\".\n        Each of them is replaced by \"$0.00\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2289,
-        "title": "Steps to Make Array Non-decreasing",
-        "question": "class Solution:\n    def totalSteps(self, nums: List[int]) -> int:\n        \"\"\"\n        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.\n        Return the number of steps performed until nums becomes a non-decreasing array.\n        Example 1:\n        Input: nums = [5,3,4,4,7,3,6,11,8,5,11]\n        Output: 3\n        Explanation: 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.\n        Example 2:\n        Input: nums = [4,5,7,7,13]\n        Output: 0\n        Explanation: nums is already a non-decreasing array. Therefore, we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2290,
-        "title": "Minimum Obstacle Removal to Reach Corner",
-        "question": "class Solution:\n    def minimumObstacles(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        You are given a 0-indexed 2D integer array grid of size m x n. Each cell has one of two values:\n            0 represents an empty cell,\n            1 represents an obstacle that may be removed.\n        You can move up, down, left, or right from and to an empty cell.\n        Return 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:\n        Input: grid = [[0,1,1],[1,1,0],[1,1,0]]\n        Output: 2\n        Explanation: We can remove the obstacles at (0, 1) and (0, 2) to create a path from (0, 0) to (2, 2).\n        It can be shown that we need to remove at least 2 obstacles, so we return 2.\n        Note that there may be other ways to remove 2 obstacles to create a path.\n        Example 2:\n        Input: grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]]\n        Output: 0\n        Explanation: We can move from (0, 0) to (2, 4) without removing any obstacles, so we return 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2283,
-        "title": "Check if Number Has Equal Digit Count and Digit Value",
-        "question": "class Solution:\n    def digitCount(self, num: str) -> bool:\n        \"\"\"\n        You are given a 0-indexed string num of length n consisting of digits.\n        Return 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:\n        Input: num = \"1210\"\n        Output: true\n        Explanation:\n        num[0] = '1'. The digit 0 occurs once in num.\n        num[1] = '2'. The digit 1 occurs twice in num.\n        num[2] = '1'. The digit 2 occurs once in num.\n        num[3] = '0'. The digit 3 occurs zero times in num.\n        The condition holds true for every index in \"1210\", so return true.\n        Example 2:\n        Input: num = \"030\"\n        Output: false\n        Explanation:\n        num[0] = '0'. The digit 0 should occur zero times, but actually occurs twice in num.\n        num[1] = '3'. The digit 1 should occur three times, but actually occurs zero times in num.\n        num[2] = '0'. The digit 2 occurs zero times in num.\n        The indices 0 and 1 both violate the condition, so return false.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2284,
-        "title": "Sender With Largest Word Count",
-        "question": "class Solution:\n    def largestWordCount(self, messages: List[str], senders: List[str]) -> str:\n        \"\"\"\n        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].\n        A 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.\n        Return 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.\n        Note:\n            Uppercase letters come before lowercase letters in lexicographical order.\n            \"Alice\" and \"alice\" are distinct.\n        Example 1:\n        Input: messages = [\"Hello userTwooo\",\"Hi userThree\",\"Wonderful day Alice\",\"Nice day userThree\"], senders = [\"Alice\",\"userTwo\",\"userThree\",\"Alice\"]\n        Output: \"Alice\"\n        Explanation: Alice sends a total of 2 + 3 = 5 words.\n        userTwo sends a total of 2 words.\n        userThree sends a total of 3 words.\n        Since Alice has the largest word count, we return \"Alice\".\n        Example 2:\n        Input: messages = [\"How is leetcode for everyone\",\"Leetcode is useful for practice\"], senders = [\"Bob\",\"Charlie\"]\n        Output: \"Charlie\"\n        Explanation: Bob sends a total of 5 words.\n        Charlie sends a total of 5 words.\n        Since there is a tie for the largest word count, we return the sender with the lexicographically larger name, Charlie.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2285,
-        "title": "Maximum Total Importance of Roads",
-        "question": "class Solution:\n    def maximumImportance(self, n: int, roads: List[List[int]]) -> int:\n        \"\"\"\n        You are given an integer n denoting the number of cities in a country. The cities are numbered from 0 to n - 1.\n        You 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.\n        You 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.\n        Return the maximum total importance of all roads possible after assigning the values optimally.\n        Example 1:\n        Input: n = 5, roads = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]\n        Output: 43\n        Explanation: 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.\n        The total importance of all roads is 6 + 9 + 8 + 7 + 7 + 6 = 43.\n        It can be shown that we cannot obtain a greater total importance than 43.\n        Example 2:\n        Input: n = 5, roads = [[0,3],[2,4],[1,3]]\n        Output: 20\n        Explanation: 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.\n        The total importance of all roads is 9 + 3 + 8 = 20.\n        It can be shown that we cannot obtain a greater total importance than 20.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2286,
-        "title": "Booking Concert Tickets in Groups",
-        "question": "class BookMyShow:\n    def __init__(self, n: int, m: int):\n    def gather(self, k: int, maxRow: int) -> List[int]:\n    def scatter(self, k: int, maxRow: int) -> bool:\n        \"\"\"\n        A concert hall has n rows numbered from 0 to n - 1, each with m seats, numbered from 0 to m - 1. You need to design a ticketing system that can allocate seats in the following cases:\n            If a group of k spectators can sit together in a row.\n            If every member of a group of k spectators can get a seat. They may or may not sit together.\n        Note that the spectators are very picky. Hence:\n            They will book seats only if each member of their group can get a seat with row number less than or equal to maxRow. maxRow can vary from group to group.\n            In case there are multiple rows to choose from, the row with the smallest number is chosen. If there are multiple seats to choose in the same row, the seat with the smallest number is chosen.\n        Implement the BookMyShow class:\n            BookMyShow(int n, int m) Initializes the object with n as number of rows and m as number of seats per row.\n            int[] gather(int k, int maxRow) Returns an array of length 2 denoting the row and seat number (respectively) of the first seat being allocated to the k members of the group, who must sit together. In other words, it returns the smallest possible r and c such that all [c, c + k - 1] seats are valid and empty in row r, and r <= maxRow. Returns [] in case it is not possible to allocate seats to the group.\n            boolean scatter(int k, int maxRow) Returns true if all k members of the group can be allocated seats in rows 0 to maxRow, who may or may not sit together. If the seats can be allocated, it allocates k seats to the group with the smallest row numbers, and the smallest possible seat numbers in each row. Otherwise, returns false.\n        Example 1:\n        Input\n        [\"BookMyShow\", \"gather\", \"gather\", \"scatter\", \"scatter\"]\n        [[2, 5], [4, 0], [2, 0], [5, 1], [5, 1]]\n        Output\n        [null, [0, 0], [], true, false]\n        Explanation\n        BookMyShow bms = new BookMyShow(2, 5); // There are 2 rows with 5 seats each \n        bms.gather(4, 0); // return [0, 0]\n                          // The group books seats [0, 3] of row 0. \n        bms.gather(2, 0); // return []\n                          // There is only 1 seat left in row 0,\n                          // so it is not possible to book 2 consecutive seats. \n        bms.scatter(5, 1); // return True\n                           // The group books seat 4 of row 0 and seats [0, 3] of row 1. \n        bms.scatter(5, 1); // return False\n                           // There is only one seat left in the hall.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2235,
-        "title": "Add Two Integers",
-        "question": "class Solution:\n    def sum(self, num1: int, num2: int) -> int:\n        \"\"\"\n        Given two integers num1 and num2, return the sum of the two integers.\n        Example 1:\n        Input: num1 = 12, num2 = 5\n        Output: 17\n        Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.\n        Example 2:\n        Input: num1 = -10, num2 = 4\n        Output: -6\n        Explanation: num1 + num2 = -6, so -6 is returned.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2236,
-        "title": "Root Equals Sum of Children",
-        "question": "class Solution:\n    def checkTree(self, root: Optional[TreeNode]) -> bool:\n        \"\"\"\n        You are given the root of a binary tree that consists of exactly 3 nodes: the root, its left child, and its right child.\n        Return 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:\n        Input: root = [10,4,6]\n        Output: true\n        Explanation: The values of the root, its left child, and its right child are 10, 4, and 6, respectively.\n        10 is equal to 4 + 6, so we return true.\n        Example 2:\n        Input: root = [5,3,1]\n        Output: false\n        Explanation: The values of the root, its left child, and its right child are 5, 3, and 1, respectively.\n        5 is not equal to 3 + 1, so we return false.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2293,
-        "title": "Min Max Game",
-        "question": "class Solution:\n    def minMaxGame(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums whose length is a power of 2.\n        Apply the following algorithm on nums:\n            Let 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.\n            For every even index i where 0 <= i < n / 2, assign the value of newNums[i] as min(nums[2 * i], nums[2 * i + 1]).\n            For every odd index i where 0 <= i < n / 2, assign the value of newNums[i] as max(nums[2 * i], nums[2 * i + 1]).\n            Replace the array nums with newNums.\n            Repeat the entire process starting from step 1.\n        Return the last number that remains in nums after applying the algorithm.\n        Example 1:\n        Input: nums = [1,3,5,2,4,8,2,2]\n        Output: 1\n        Explanation: The following arrays are the results of applying the algorithm repeatedly.\n        First: nums = [1,5,4,2]\n        Second: nums = [1,4]\n        Third: nums = [1]\n        1 is the last remaining number, so we return 1.\n        Example 2:\n        Input: nums = [3]\n        Output: 3\n        Explanation: 3 is already the last remaining number, so we return 3.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2294,
-        "title": "Partition Array Such That Maximum Difference Is K",
-        "question": "class Solution:\n    def partitionArray(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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.\n        Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.\n        A 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:\n        Input: nums = [3,6,1,2,5], k = 2\n        Output: 2\n        Explanation:\n        We can partition nums into the two subsequences [3,1,2] and [6,5].\n        The difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2.\n        The difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1.\n        Since two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed.\n        Example 2:\n        Input: nums = [1,2,3], k = 1\n        Output: 2\n        Explanation:\n        We can partition nums into the two subsequences [1,2] and [3].\n        The difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1.\n        The difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0.\n        Since two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3].\n        Example 3:\n        Input: nums = [2,2,4,5], k = 0\n        Output: 3\n        Explanation:\n        We can partition nums into the three subsequences [2,2], [4], and [5].\n        The difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0.\n        The difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0.\n        The difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0.\n        Since three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2295,
-        "title": "Replace Elements in an Array",
-        "question": "class Solution:\n    def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:\n        \"\"\"\n        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].\n        It is guaranteed that in the ith operation:\n            operations[i][0] exists in nums.\n            operations[i][1] does not exist in nums.\n        Return the array obtained after applying all the operations.\n        Example 1:\n        Input: nums = [1,2,4,6], operations = [[1,3],[4,7],[6,1]]\n        Output: [3,2,7,1]\n        Explanation: 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].\n        We return the final array [3,2,7,1].\n        Example 2:\n        Input: nums = [1,2], operations = [[1,3],[2,1],[3,2]]\n        Output: [2,1]\n        Explanation: 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].\n        We return the array [2,1].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2296,
-        "title": "Design a Text Editor",
-        "question": "class TextEditor:\n    def __init__(self):\n    def addText(self, text: str) -> None:\n    def deleteText(self, k: int) -> int:\n    def cursorLeft(self, k: int) -> str:\n    def cursorRight(self, k: int) -> str:\n        \"\"\"\n        Design a text editor with a cursor that can do the following:\n            Add text to where the cursor is.\n            Delete text from where the cursor is (simulating the backspace key).\n            Move the cursor either left or right.\n        When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.\n        Implement the TextEditor class:\n            TextEditor() Initializes the object with empty text.\n            void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.\n            int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.\n            string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.\n            string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.\n        Example 1:\n        Input\n        [\"TextEditor\", \"addText\", \"deleteText\", \"addText\", \"cursorRight\", \"cursorLeft\", \"deleteText\", \"cursorLeft\", \"cursorRight\"]\n        [[], [\"leetcode\"], [4], [\"practice\"], [3], [8], [10], [2], [6]]\n        Output\n        [null, null, 4, null, \"etpractice\", \"leet\", 4, \"\", \"practi\"]\n        Explanation\n        TextEditor textEditor = new TextEditor(); // The current text is \"|\". (The '|' character represents the cursor)\n        textEditor.addText(\"leetcode\"); // The current text is \"leetcode|\".\n        textEditor.deleteText(4); // return 4\n                                  // The current text is \"leet|\". \n                                  // 4 characters were deleted.\n        textEditor.addText(\"practice\"); // The current text is \"leetpractice|\". \n        textEditor.cursorRight(3); // return \"etpractice\"\n                                   // The current text is \"leetpractice|\". \n                                   // The cursor cannot be moved beyond the actual text and thus did not move.\n                                   // \"etpractice\" is the last 10 characters to the left of the cursor.\n        textEditor.cursorLeft(8); // return \"leet\"\n                                  // The current text is \"leet|practice\".\n                                  // \"leet\" is the last min(10, 4) = 4 characters to the left of the cursor.\n        textEditor.deleteText(10); // return 4\n                                   // The current text is \"|practice\".\n                                   // Only 4 characters were deleted.\n        textEditor.cursorLeft(2); // return \"\"\n                                  // The current text is \"|practice\".\n                                  // The cursor cannot be moved beyond the actual text and thus did not move. \n                                  // \"\" is the last min(10, 0) = 0 characters to the left of the cursor.\n        textEditor.cursorRight(6); // return \"practi\"\n                                   // The current text is \"practi|ce\".\n                                   // \"practi\" is the last min(10, 6) = 6 characters to the left of the cursor.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2306,
-        "title": "Naming a Company",
-        "question": "class Solution:\n    def distinctNames(self, ideas: List[str]) -> int:\n        \"\"\"\n        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:\n            Choose 2 distinct names from ideas, call them ideaA and ideaB.\n            Swap the first letters of ideaA and ideaB with each other.\n            If 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.\n            Otherwise, it is not a valid name.\n        Return the number of distinct valid names for the company.\n        Example 1:\n        Input: ideas = [\"coffee\",\"donuts\",\"time\",\"toffee\"]\n        Output: 6\n        Explanation: 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\".\n        Therefore, there are a total of 6 distinct company names.\n        The 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.\n        Example 2:\n        Input: ideas = [\"lack\",\"back\"]\n        Output: 0\n        Explanation: There are no valid selections. Therefore, 0 is returned.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2299,
-        "title": "Strong Password Checker II",
-        "question": "class Solution:\n    def strongPasswordCheckerII(self, password: str) -> bool:\n        \"\"\"\n        A password is said to be strong if it satisfies all the following criteria:\n            It has at least 8 characters.\n            It contains at least one lowercase letter.\n            It contains at least one uppercase letter.\n            It contains at least one digit.\n            It contains at least one special character. The special characters are the characters in the following string: \"!@#$%^&*()-+\".\n            It does not contain 2 of the same character in adjacent positions (i.e., \"aab\" violates this condition, but \"aba\" does not).\n        Given a string password, return true if it is a strong password. Otherwise, return false.\n        Example 1:\n        Input: password = \"IloveLe3tcode!\"\n        Output: true\n        Explanation: The password meets all the requirements. Therefore, we return true.\n        Example 2:\n        Input: password = \"Me+You--IsMyDream\"\n        Output: false\n        Explanation: The password does not contain a digit and also contains 2 of the same character in adjacent positions. Therefore, we return false.\n        Example 3:\n        Input: password = \"1aB!\"\n        Output: false\n        Explanation: The password does not meet the length requirement. Therefore, we return false.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2300,
-        "title": "Successful Pairs of Spells and Potions",
-        "question": "class Solution:\n    def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]:\n        \"\"\"\n        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.\n        You are also given an integer success. A spell and potion pair is considered successful if the product of their strengths is at least success.\n        Return 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:\n        Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7\n        Output: [4,0,3]\n        Explanation:\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.\n        Thus, [4,0,3] is returned.\n        Example 2:\n        Input: spells = [3,1,2], potions = [8,5,8], success = 16\n        Output: [2,0,2]\n        Explanation:\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. \n        Thus, [2,0,2] is returned.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2301,
-        "title": "Match Substring After Replacement",
-        "question": "class Solution:\n    def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:\n        \"\"\"\n        You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times:\n            Replace a character oldi of sub with newi.\n        Each character in sub cannot be replaced more than once.\n        Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false.\n        A substring is a contiguous non-empty sequence of characters within a string.\n        Example 1:\n        Input: s = \"fool3e7bar\", sub = \"leet\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"]]\n        Output: true\n        Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'.\n        Now sub = \"l3e7\" is a substring of s, so we return true.\n        Example 2:\n        Input: s = \"fooleetbar\", sub = \"f00l\", mappings = [[\"o\",\"0\"]]\n        Output: false\n        Explanation: The string \"f00l\" is not a substring of s and no replacements can be made.\n        Note that we cannot replace '0' with 'o'.\n        Example 3:\n        Input: s = \"Fool33tbaR\", sub = \"leetd\", mappings = [[\"e\",\"3\"],[\"t\",\"7\"],[\"t\",\"8\"],[\"d\",\"b\"],[\"p\",\"b\"]]\n        Output: true\n        Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.\n        Now sub = \"l33tb\" is a substring of s, so we return true.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2302,
-        "title": "Count Subarrays With Score Less Than K",
-        "question": "class Solution:\n    def countSubarrays(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        The score of an array is defined as the product of its sum and its length.\n            For example, the score of [1, 2, 3, 4, 5] is (1 + 2 + 3 + 4 + 5) * 5 = 75.\n        Given 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.\n        A subarray is a contiguous sequence of elements within an array.\n        Example 1:\n        Input: nums = [2,1,4,3,5], k = 10\n        Output: 6\n        Explanation:\n        The 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.\n        Note 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.\n        Example 2:\n        Input: nums = [1,1,1], k = 5\n        Output: 5\n        Explanation:\n        Every 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.\n        Thus, there are 5 subarrays having scores less than 5.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2311,
-        "title": "Longest Binary Subsequence Less Than or Equal to K",
-        "question": "class Solution:\n    def longestSubsequence(self, s: str, k: int) -> int:\n        \"\"\"\n        You are given a binary string s and a positive integer k.\n        Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.\n        Note:\n            The subsequence can contain leading zeroes.\n            The empty string is considered to be equal to 0.\n            A 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:\n        Input: s = \"1001010\", k = 5\n        Output: 5\n        Explanation: 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.\n        Note that \"00100\" and \"00101\" are also possible, which are equal to 4 and 5 in decimal, respectively.\n        The length of this subsequence is 5, so 5 is returned.\n        Example 2:\n        Input: s = \"00101001\", k = 1\n        Output: 6\n        Explanation: \"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.\n        The length of this subsequence is 6, so 6 is returned.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2320,
-        "title": "Count Number of Ways to Place Houses",
-        "question": "class Solution:\n    def countHousePlacements(self, n: int) -> int:\n        \"\"\"\n        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.\n        Return 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.\n        Note 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:\n        Input: n = 1\n        Output: 4\n        Explanation: \n        Possible arrangements:\n        1. All plots are empty.\n        2. A house is placed on one side of the street.\n        3. A house is placed on the other side of the street.\n        4. Two houses are placed, one on each side of the street.\n        Example 2:\n        Input: n = 2\n        Output: 9\n        Explanation: The 9 possible arrangements are shown in the diagram above.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2319,
-        "title": "Check if Matrix Is X-Matrix",
-        "question": "class Solution:\n    def checkXMatrix(self, grid: List[List[int]]) -> bool:\n        \"\"\"\n        A square matrix is said to be an X-Matrix if both of the following conditions hold:\n            All the elements in the diagonals of the matrix are non-zero.\n            All other elements are 0.\n        Given 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:\n        Input: grid = [[2,0,0,1],[0,3,1,0],[0,5,2,0],[4,0,0,2]]\n        Output: true\n        Explanation: Refer to the diagram above. \n        An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\n        Thus, grid is an X-Matrix.\n        Example 2:\n        Input: grid = [[5,7,0],[0,3,1],[0,5,0]]\n        Output: false\n        Explanation: Refer to the diagram above.\n        An X-Matrix should have the green elements (diagonals) be non-zero and the red elements be 0.\n        Thus, grid is not an X-Matrix.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2322,
-        "title": "Minimum Score After Removals on a Tree",
-        "question": "class Solution:\n    def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:\n        \"\"\"\n        There is an undirected connected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n        You 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.\n        Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined:\n            Get the XOR of all the values of the nodes for each of the three components respectively.\n            The difference between the largest XOR value and the smallest XOR value is the score of the pair.\n            For example, say the three components have the node values: [4,5,7], [1,9], and [3,3,3]. The three XOR values are 4 ^ 5 ^ 7 = 6, 1 ^ 9 = 8, and 3 ^ 3 ^ 3 = 3. The largest XOR value is 8 and the smallest XOR value is 3. The score is then 8 - 3 = 5.\n        Return the minimum score of any possible pair of edge removals on the given tree.\n        Example 1:\n        Input: nums = [1,5,5,4,11], edges = [[0,1],[1,2],[1,3],[3,4]]\n        Output: 9\n        Explanation: 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.\n        The score is the difference between the largest and smallest XOR value which is 10 - 1 = 9.\n        It can be shown that no other pair of removals will obtain a smaller score than 9.\n        Example 2:\n        Input: nums = [5,5,2,4,4,2], edges = [[0,1],[1,2],[5,2],[4,3],[1,3]]\n        Output: 0\n        Explanation: 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.\n        The score is the difference between the largest and smallest XOR value which is 0 - 0 = 0.\n        We cannot obtain a smaller score than 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2315,
-        "title": "Count Asterisks",
-        "question": "class Solution:\n    def countAsterisks(self, s: str) -> int:\n        \"\"\"\n        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.\n        Return the number of '*' in s, excluding the '*' between each pair of '|'.\n        Note that each '|' will belong to exactly one pair.\n        Example 1:\n        Input: s = \"l|*e*et|c**o|*de|\"\n        Output: 2\n        Explanation: The considered characters are underlined: \"l|*e*et|c**o|*de|\".\n        The characters between the first and second '|' are excluded from the answer.\n        Also, the characters between the third and fourth '|' are excluded from the answer.\n        There are 2 asterisks considered. Therefore, we return 2.\n        Example 2:\n        Input: s = \"iamprogrammer\"\n        Output: 0\n        Explanation: In this example, there are no asterisks in s. Therefore, we return 0.\n        Example 3:\n        Input: s = \"yo|uar|e**|b|e***au|tifu|l\"\n        Output: 5\n        Explanation: The considered characters are underlined: \"yo|uar|e**|b|e***au|tifu|l\". There are 5 asterisks considered. Therefore, we return 5.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2317,
-        "title": "Maximum XOR After Operations ",
-        "question": "class Solution:\n    def maximumXOR(self, nums: List[int]) -> int:\n        \"\"\"\n        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).\n        Note that AND is the bitwise AND operation and XOR is the bitwise XOR operation.\n        Return the maximum possible bitwise XOR of all elements of nums after applying the operation any number of times.\n        Example 1:\n        Input: nums = [3,2,4,6]\n        Output: 7\n        Explanation: Apply the operation with x = 4 and i = 3, num[3] = 6 AND (6 XOR 4) = 6 AND 2 = 2.\n        Now, nums = [3, 2, 4, 2] and the bitwise XOR of all the elements = 3 XOR 2 XOR 4 XOR 2 = 7.\n        It can be shown that 7 is the maximum possible bitwise XOR.\n        Note that other operations may be used to achieve a bitwise XOR of 7.\n        Example 2:\n        Input: nums = [1,2,3,9,2]\n        Output: 11\n        Explanation: Apply the operation zero times.\n        The bitwise XOR of all the elements = 1 XOR 2 XOR 3 XOR 9 XOR 2 = 11.\n        It can be shown that 11 is the maximum possible bitwise XOR.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2316,
-        "title": "Count Unreachable Pairs of Nodes in an Undirected Graph",
-        "question": "class Solution:\n    def countPairs(self, n: int, edges: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        Return the number of pairs of different nodes that are unreachable from each other.\n        Example 1:\n        Input: n = 3, edges = [[0,1],[0,2],[1,2]]\n        Output: 0\n        Explanation: There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.\n        Example 2:\n        Input: n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]\n        Output: 14\n        Explanation: 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]].\n        Therefore, we return 14.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2318,
-        "title": "Number of Distinct Roll Sequences",
-        "question": "class Solution:\n    def distinctSequences(self, n: int) -> int:\n        \"\"\"\n        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:\n            The greatest common divisor of any adjacent values in the sequence is equal to 1.\n            There 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.\n        Return the total number of distinct sequences possible. Since the answer may be very large, return it modulo 109 + 7.\n        Two sequences are considered distinct if at least one element is different.\n        Example 1:\n        Input: n = 4\n        Output: 184\n        Explanation: Some of the possible sequences are (1, 2, 3, 4), (6, 1, 2, 3), (1, 2, 3, 1), etc.\n        Some 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.\n        There are a total of 184 distinct sequences possible, so we return 184.\n        Example 2:\n        Input: n = 2\n        Output: 22\n        Explanation: Some of the possible sequences are (1, 2), (2, 1), (3, 2).\n        Some invalid sequences are (3, 6), (2, 4) since the greatest common divisor is not equal to 1.\n        There are a total of 22 distinct sequences possible, so we return 22.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2325,
-        "title": "Decode the Message",
-        "question": "class Solution:\n    def decodeMessage(self, key: str, message: str) -> str:\n        \"\"\"\n        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:\n            Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table.\n            Align the substitution table with the regular English alphabet.\n            Each letter in message is then substituted using the table.\n            Spaces ' ' are transformed to themselves.\n            For 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').\n        Return the decoded message.\n        Example 1:\n        Input: key = \"the quick brown fox jumps over the lazy dog\", message = \"vkbs bs t suepuv\"\n        Output: \"this is a secret\"\n        Explanation: The diagram above shows the substitution table.\n        It is obtained by taking the first appearance of each letter in \"the quick brown fox jumps over the lazy dog\".\n        Example 2:\n        Input: key = \"eljuxhpwnyrdgtqkviszcfmabo\", message = \"zwx hnfx lqantp mnoeius ycgk vcnjrdb\"\n        Output: \"the five boxing wizards jump quickly\"\n        Explanation: The diagram above shows the substitution table.\n        It is obtained by taking the first appearance of each letter in \"eljuxhpwnyrdgtqkviszcfmabo\".\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2327,
-        "title": "Number of People Aware of a Secret",
-        "question": "class Solution:\n    def peopleAwareOfSecret(self, n: int, delay: int, forget: int) -> int:\n        \"\"\"\n        On day 1, one person discovers a secret.\n        You 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.\n        Given 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:\n        Input: n = 6, delay = 2, forget = 4\n        Output: 5\n        Explanation:\n        Day 1: Suppose the first person is named A. (1 person)\n        Day 2: A is the only person who knows the secret. (1 person)\n        Day 3: A shares the secret with a new person, B. (2 people)\n        Day 4: A shares the secret with a new person, C. (3 people)\n        Day 5: A forgets the secret, and B shares the secret with a new person, D. (3 people)\n        Day 6: B shares the secret with E, and C shares the secret with F. (5 people)\n        Example 2:\n        Input: n = 4, delay = 1, forget = 3\n        Output: 6\n        Explanation:\n        Day 1: The first person is named A. (1 person)\n        Day 2: A shares the secret with B. (2 people)\n        Day 3: A and B share the secret with 2 new people, C and D. (4 people)\n        Day 4: A forgets the secret. B, C, and D share the secret with 3 new people. (6 people)\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2328,
-        "title": "Number of Increasing Paths in a Grid",
-        "question": "class Solution:\n    def countPaths(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        Return 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.\n        Two paths are considered different if they do not have exactly the same sequence of visited cells.\n        Example 1:\n        Input: grid = [[1,1],[3,4]]\n        Output: 8\n        Explanation: 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].\n        The total number of paths is 4 + 3 + 1 = 8.\n        Example 2:\n        Input: grid = [[1],[2]]\n        Output: 3\n        Explanation: The strictly increasing paths are:\n        - Paths with length 1: [1], [2].\n        - Paths with length 2: [1 -> 2].\n        The total number of paths is 2 + 1 = 3.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2326,
-        "title": "Spiral Matrix IV",
-        "question": "class Solution:\n    def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:\n        \"\"\"\n        You are given two integers m and n, which represent the dimensions of a matrix.\n        You are also given the head of a linked list of integers.\n        Generate 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.\n        Return the generated matrix.\n        Example 1:\n        Input: m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]\n        Output: [[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]\n        Explanation: The diagram above shows how the values are printed in the matrix.\n        Note that the remaining spaces in the matrix are filled with -1.\n        Example 2:\n        Input: m = 1, n = 4, head = [0,1,2]\n        Output: [[0,1,2,-1]]\n        Explanation: The diagram above shows how the values are printed from left to right in the matrix.\n        The last space in the matrix is set to -1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2335,
-        "title": "Minimum Amount of Time to Fill Cups",
-        "question": "class Solution:\n    def fillCups(self, amount: List[int]) -> int:\n        \"\"\"\n        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.\n        You 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:\n        Input: amount = [1,4,2]\n        Output: 4\n        Explanation: One way to fill up the cups is:\n        Second 1: Fill up a cold cup and a warm cup.\n        Second 2: Fill up a warm cup and a hot cup.\n        Second 3: Fill up a warm cup and a hot cup.\n        Second 4: Fill up a warm cup.\n        It can be proven that 4 is the minimum number of seconds needed.\n        Example 2:\n        Input: amount = [5,4,4]\n        Output: 7\n        Explanation: One way to fill up the cups is:\n        Second 1: Fill up a cold cup, and a hot cup.\n        Second 2: Fill up a cold cup, and a warm cup.\n        Second 3: Fill up a cold cup, and a warm cup.\n        Second 4: Fill up a warm cup, and a hot cup.\n        Second 5: Fill up a cold cup, and a hot cup.\n        Second 6: Fill up a cold cup, and a warm cup.\n        Second 7: Fill up a hot cup.\n        Example 3:\n        Input: amount = [5,0,0]\n        Output: 5\n        Explanation: Every second, we fill up a cold cup.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2336,
-        "title": "Smallest Number in Infinite Set",
-        "question": "class SmallestInfiniteSet:\n    def __init__(self):\n    def popSmallest(self) -> int:\n    def addBack(self, num: int) -> None:\n        \"\"\"\n        You have a set which contains all positive integers [1, 2, 3, 4, 5, ...].\n        Implement the SmallestInfiniteSet class:\n            SmallestInfiniteSet() Initializes the SmallestInfiniteSet object to contain all positive integers.\n            int popSmallest() Removes and returns the smallest integer contained in the infinite set.\n            void addBack(int num) Adds a positive integer num back into the infinite set, if it is not already in the infinite set.\n        Example 1:\n        Input\n        [\"SmallestInfiniteSet\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\", \"addBack\", \"popSmallest\", \"popSmallest\", \"popSmallest\"]\n        [[], [2], [], [], [], [1], [], [], []]\n        Output\n        [null, null, 1, 2, 3, null, 1, 4, 5]\n        Explanation\n        SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();\n        smallestInfiniteSet.addBack(2);    // 2 is already in the set, so no change is made.\n        smallestInfiniteSet.popSmallest(); // return 1, since 1 is the smallest number, and remove it from the set.\n        smallestInfiniteSet.popSmallest(); // return 2, and remove it from the set.\n        smallestInfiniteSet.popSmallest(); // return 3, and remove it from the set.\n        smallestInfiniteSet.addBack(1);    // 1 is added back to the set.\n        smallestInfiniteSet.popSmallest(); // return 1, since 1 was added back to the set and\n                                           // is the smallest number, and remove it from the set.\n        smallestInfiniteSet.popSmallest(); // return 4, and remove it from the set.\n        smallestInfiniteSet.popSmallest(); // return 5, and remove it from the set.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2337,
-        "title": "Move Pieces to Obtain a String",
-        "question": "class Solution:\n    def canChange(self, start: str, target: str) -> bool:\n        \"\"\"\n        You are given two strings start and target, both of length n. Each string consists only of the characters 'L', 'R', and '_' where:\n            The characters 'L' and 'R' represent pieces, where a piece 'L' can move to the left only if there is a blank space directly to its left, and a piece 'R' can move to the right only if there is a blank space directly to its right.\n            The character '_' represents a blank space that can be occupied by any of the 'L' or 'R' pieces.\n        Return 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:\n        Input: start = \"_L__R__R_\", target = \"L______RR\"\n        Output: true\n        Explanation: 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\".\n        Since it is possible to get the string target from start, we return true.\n        Example 2:\n        Input: start = \"R_L_\", target = \"__LR\"\n        Output: false\n        Explanation: The 'R' piece in the string start can move one step to the right to obtain \"_RL_\".\n        After that, no pieces can move anymore, so it is impossible to obtain the string target from start.\n        Example 3:\n        Input: start = \"_R\", target = \"R_\"\n        Output: false\n        Explanation: The piece in the string start can move only to the right, so it is impossible to obtain the string target from start.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2338,
-        "title": "Count the Number of Ideal Arrays",
-        "question": "class Solution:\n    def idealArrays(self, n: int, maxValue: int) -> int:\n        \"\"\"\n        You are given two integers n and maxValue, which are used to describe an ideal array.\n        A 0-indexed integer array arr of length n is considered ideal if the following conditions hold:\n            Every arr[i] is a value from 1 to maxValue, for 0 <= i < n.\n            Every arr[i] is divisible by arr[i - 1], for 0 < i < n.\n        Return the number of distinct ideal arrays of length n. Since the answer may be very large, return it modulo 109 + 7.\n        Example 1:\n        Input: n = 2, maxValue = 5\n        Output: 10\n        Explanation: 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]\n        There are a total of 5 + 2 + 1 + 1 + 1 = 10 distinct ideal arrays.\n        Example 2:\n        Input: n = 5, maxValue = 3\n        Output: 11\n        Explanation: 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]\n        There are a total of 9 + 1 + 1 = 11 distinct ideal arrays.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2331,
-        "title": "Evaluate Boolean Binary Tree",
-        "question": "class Solution:\n    def evaluateTree(self, root: Optional[TreeNode]) -> bool:\n        \"\"\"\n        You are given the root of a full binary tree with the following properties:\n            Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True.\n            Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND.\n        The evaluation of a node is as follows:\n            If the node is a leaf node, the evaluation is the value of the node, i.e. True or False.\n            Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations.\n        Return the boolean result of evaluating the root node.\n        A full binary tree is a binary tree where each node has either 0 or 2 children.\n        A leaf node is a node that has zero children.\n        Example 1:\n        Input: root = [2,1,3,null,null,0,1]\n        Output: true\n        Explanation: The above diagram illustrates the evaluation process.\n        The AND node evaluates to False AND True = False.\n        The OR node evaluates to True OR False = True.\n        The root node evaluates to True, so we return true.\n        Example 2:\n        Input: root = [0]\n        Output: false\n        Explanation: The root node is a leaf node and it evaluates to false, so we return false.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2332,
-        "title": "The Latest Time to Catch a Bus",
-        "question": "class Solution:\n    def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int:\n        \"\"\"\n        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.\n        You are given an integer capacity, which represents the maximum number of passengers that can get on each bus.\n        When 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.\n        More formally when a bus arrives, either:\n            If capacity or fewer passengers are waiting for a bus, they will all get on the bus, or\n            The capacity passengers with the earliest arrival times will get on the bus.\n        Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger.\n        Note: The arrays buses and passengers are not necessarily sorted.\n        Example 1:\n        Input: buses = [10,20], passengers = [2,17,18,19], capacity = 2\n        Output: 16\n        Explanation: Suppose you arrive at time 16.\n        At time 10, the first bus departs with the 0th passenger. \n        At time 20, the second bus departs with you and the 1st passenger.\n        Note 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.\n        Example 2:\n        Input: buses = [20,30,10], passengers = [19,13,26,4,25,11,21], capacity = 2\n        Output: 20\n        Explanation: Suppose you arrive at time 20.\n        At time 10, the first bus departs with the 3rd passenger. \n        At time 20, the second bus departs with the 5th and 1st passengers.\n        At time 30, the third bus departs with the 0th passenger and you.\n        Notice if you had arrived any later, then the 6th passenger would have taken your seat on the third bus.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2333,
-        "title": "Minimum Sum of Squared Difference",
-        "question": "class Solution:\n    def minSumSquareDiff(self, nums1: List[int], nums2: List[int], k1: int, k2: int) -> int:\n        \"\"\"\n        You are given two positive 0-indexed integer arrays nums1 and nums2, both of length n.\n        The 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.\n        You 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.\n        Return the minimum sum of squared difference after modifying array nums1 at most k1 times and modifying array nums2 at most k2 times.\n        Note: You are allowed to modify the array elements to become negative integers.\n        Example 1:\n        Input: nums1 = [1,2,3,4], nums2 = [2,10,20,19], k1 = 0, k2 = 0\n        Output: 579\n        Explanation: The elements in nums1 and nums2 cannot be modified because k1 = 0 and k2 = 0. \n        The sum of square difference will be: (1 - 2)2 + (2 - 10)2 + (3 - 20)2 + (4 - 19)2 = 579.\n        Example 2:\n        Input: nums1 = [1,4,10,12], nums2 = [5,8,6,9], k1 = 1, k2 = 1\n        Output: 43\n        Explanation: One way to obtain the minimum sum of square difference is: \n        - Increase nums1[0] once.\n        - Increase nums2[2] once.\n        The minimum of the sum of square difference will be: \n        (2 - 5)2 + (4 - 8)2 + (10 - 7)2 + (12 - 9)2 = 43.\n        Note 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2334,
-        "title": "Subarray With Elements Greater Than Varying Threshold",
-        "question": "class Solution:\n    def validSubarraySize(self, nums: List[int], threshold: int) -> int:\n        \"\"\"\n        You are given an integer array nums and an integer threshold.\n        Find any subarray of nums of length k such that every element in the subarray is greater than threshold / k.\n        Return the size of any such subarray. If there is no such subarray, return -1.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,3,4,3,1], threshold = 6\n        Output: 3\n        Explanation: The subarray [3,4,3] has a size of 3, and every element is greater than 6 / 3 = 2.\n        Note that this is the only valid subarray.\n        Example 2:\n        Input: nums = [6,5,6,5,8], threshold = 7\n        Output: 1\n        Explanation: The subarray [8] has a size of 1, and 8 > 7 / 1 = 7. So 1 is returned.\n        Note that the subarray [6,5] has a size of 2, and every element is greater than 7 / 2 = 3.5. \n        Similarly, the subarrays [6,5,6], [6,5,6,5], [6,5,6,5,8] also satisfy the given conditions.\n        Therefore, 2, 3, 4, or 5 may also be returned.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2341,
-        "title": "Maximum Number of Pairs in Array",
-        "question": "class Solution:\n    def numberOfPairs(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed integer array nums. In one operation, you may do the following:\n            Choose two integers in nums that are equal.\n            Remove both integers from nums, forming a pair.\n        The operation is done on nums as many times as possible.\n        Return 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:\n        Input: nums = [1,3,2,1,3,2,2]\n        Output: [3,1]\n        Explanation:\n        Form a pair with nums[0] and nums[3] and remove them from nums. Now, nums = [3,2,3,2,2].\n        Form a pair with nums[0] and nums[2] and remove them from nums. Now, nums = [2,2,2].\n        Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [2].\n        No more pairs can be formed. A total of 3 pairs have been formed, and there is 1 number leftover in nums.\n        Example 2:\n        Input: nums = [1,1]\n        Output: [1,0]\n        Explanation: Form a pair with nums[0] and nums[1] and remove them from nums. Now, nums = [].\n        No more pairs can be formed. A total of 1 pair has been formed, and there are 0 numbers leftover in nums.\n        Example 3:\n        Input: nums = [0]\n        Output: [0,1]\n        Explanation: No pairs can be formed, and there is 1 number leftover in nums.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2343,
-        "title": "Query Kth Smallest Trimmed Number",
-        "question": "class Solution:\n    def smallestTrimmedNumbers(self, nums: List[str], queries: List[List[int]]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed array of strings nums, where each string is of equal length and consists of only digits.\n        You are also given a 0-indexed 2D integer array queries where queries[i] = [ki, trimi]. For each queries[i], you need to:\n            Trim each number in nums to its rightmost trimi digits.\n            Determine 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.\n            Reset each number in nums to its original length.\n        Return an array answer of the same length as queries, where answer[i] is the answer to the ith query.\n        Note:\n            To trim to the rightmost x digits means to keep removing the leftmost digit, until only x digits remain.\n            Strings in nums may contain leading zeros.\n        Example 1:\n        Input: nums = [\"102\",\"473\",\"251\",\"814\"], queries = [[1,1],[2,3],[4,2],[1,2]]\n        Output: [2,2,1,0]\n        Explanation:\n        1. After trimming to the last digit, nums = [\"2\",\"3\",\"1\",\"4\"]. The smallest number is 1 at index 2.\n        2. Trimmed to the last 3 digits, nums is unchanged. The 2nd smallest number is 251 at index 2.\n        3. Trimmed to the last 2 digits, nums = [\"02\",\"73\",\"51\",\"14\"]. The 4th smallest number is 73.\n        4. 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.\n        Example 2:\n        Input: nums = [\"24\",\"37\",\"96\",\"04\"], queries = [[2,1],[2,2]]\n        Output: [3,0]\n        Explanation:\n        1. 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.\n        2. Trimmed to the last 2 digits, nums is unchanged. The 2nd smallest number is 24.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2344,
-        "title": "Minimum Deletions to Make Array Divisible",
-        "question": "class Solution:\n    def minOperations(self, nums: List[int], numsDivide: List[int]) -> int:\n        \"\"\"\n        You are given two positive integer arrays nums and numsDivide. You can delete any number of elements from nums.\n        Return 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.\n        Note that an integer x divides y if y % x == 0.\n        Example 1:\n        Input: nums = [2,3,2,4,3], numsDivide = [9,6,9,3,15]\n        Output: 2\n        Explanation: \n        The smallest element in [2,3,2,4,3] is 2, which does not divide all the elements of numsDivide.\n        We use 2 deletions to delete the elements in nums that are equal to 2 which makes nums = [3,4,3].\n        The smallest element in [3,4,3] is 3, which divides all the elements of numsDivide.\n        It can be shown that 2 is the minimum number of deletions needed.\n        Example 2:\n        Input: nums = [4,3,6], numsDivide = [8,2,6,10]\n        Output: -1\n        Explanation: \n        We want the smallest element in nums to divide all the elements of numsDivide.\n        There is no way to delete elements from nums to allow this.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2351,
-        "title": "First Letter to Appear Twice",
-        "question": "class Solution:\n    def repeatedCharacter(self, s: str) -> str:\n        \"\"\"\n        Given a string s consisting of lowercase English letters, return the first letter to appear twice.\n        Note:\n            A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.\n            s will contain at least one letter that appears twice.\n        Example 1:\n        Input: s = \"abccbaacz\"\n        Output: \"c\"\n        Explanation:\n        The letter 'a' appears on the indexes 0, 5 and 6.\n        The letter 'b' appears on the indexes 1 and 4.\n        The letter 'c' appears on the indexes 2, 3 and 7.\n        The letter 'z' appears on the index 8.\n        The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.\n        Example 2:\n        Input: s = \"abcdd\"\n        Output: \"d\"\n        Explanation:\n        The only letter that appears twice is 'd' so we return 'd'.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2352,
-        "title": "Equal Row and Column Pairs",
-        "question": "class Solution:\n    def equalPairs(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        A 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:\n        Input: grid = [[3,2,1],[1,7,6],[2,7,7]]\n        Output: 1\n        Explanation: There is 1 equal row and column pair:\n        - (Row 2, Column 1): [2,7,7]\n        Example 2:\n        Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]\n        Output: 3\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2353,
-        "title": "Design a Food Rating System",
-        "question": "class FoodRatings:\n    def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):\n    def changeRating(self, food: str, newRating: int) -> None:\n    def highestRated(self, cuisine: str) -> str:\n        \"\"\"\n        Design a food rating system that can do the following:\n            Modify the rating of a food item listed in the system.\n            Return the highest-rated food item for a type of cuisine in the system.\n        Implement the FoodRatings class:\n            FoodRatings(String[] foods, String[] cuisines, int[] ratings) Initializes the system. The food items are described by foods, cuisines and ratings, all of which have a length of n.\n                foods[i] is the name of the ith food,\n                cuisines[i] is the type of cuisine of the ith food, and\n                ratings[i] is the initial rating of the ith food.\n            void changeRating(String food, int newRating) Changes the rating of the food item with the name food.\n            String highestRated(String cuisine) Returns the name of the food item that has the highest rating for the given type of cuisine. If there is a tie, return the item with the lexicographically smaller name.\n        Note 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:\n        Input\n        [\"FoodRatings\", \"highestRated\", \"highestRated\", \"changeRating\", \"highestRated\", \"changeRating\", \"highestRated\"]\n        [[[\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]], [\"korean\"], [\"japanese\"], [\"sushi\", 16], [\"japanese\"], [\"ramen\", 16], [\"japanese\"]]\n        Output\n        [null, \"kimchi\", \"ramen\", null, \"sushi\", null, \"ramen\"]\n        Explanation\n        FoodRatings foodRatings = new FoodRatings([\"kimchi\", \"miso\", \"sushi\", \"moussaka\", \"ramen\", \"bulgogi\"], [\"korean\", \"japanese\", \"japanese\", \"greek\", \"japanese\", \"korean\"], [9, 12, 8, 15, 14, 7]);\n        foodRatings.highestRated(\"korean\"); // return \"kimchi\"\n                                            // \"kimchi\" is the highest rated korean food with a rating of 9.\n        foodRatings.highestRated(\"japanese\"); // return \"ramen\"\n                                              // \"ramen\" is the highest rated japanese food with a rating of 14.\n        foodRatings.changeRating(\"sushi\", 16); // \"sushi\" now has a rating of 16.\n        foodRatings.highestRated(\"japanese\"); // return \"sushi\"\n                                              // \"sushi\" is the highest rated japanese food with a rating of 16.\n        foodRatings.changeRating(\"ramen\", 16); // \"ramen\" now has a rating of 16.\n        foodRatings.highestRated(\"japanese\"); // return \"ramen\"\n                                              // Both \"sushi\" and \"ramen\" have a rating of 16.\n                                              // However, \"ramen\" is lexicographically smaller than \"sushi\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2354,
-        "title": "Number of Excellent Pairs",
-        "question": "class Solution:\n    def countExcellentPairs(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given a 0-indexed positive integer array nums and a positive integer k.\n        A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:\n            Both the numbers num1 and num2 exist in the array nums.\n            The 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.\n        Return the number of distinct excellent pairs.\n        Two 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.\n        Note 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:\n        Input: nums = [1,2,3,1], k = 3\n        Output: 5\n        Explanation: 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.\n        So the number of excellent pairs is 5.\n        Example 2:\n        Input: nums = [5,1,1], k = 10\n        Output: 0\n        Explanation: There are no excellent pairs for this array.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2348,
-        "title": "Number of Zero-Filled Subarrays",
-        "question": "class Solution:\n    def zeroFilledSubarray(self, nums: List[int]) -> int:\n        \"\"\"\n        Given an integer array nums, return the number of subarrays filled with 0.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,3,0,0,2,0,0,4]\n        Output: 6\n        Explanation: \n        There are 4 occurrences of [0] as a subarray.\n        There are 2 occurrences of [0,0] as a subarray.\n        There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.\n        Example 2:\n        Input: nums = [0,0,0,2,0,0]\n        Output: 9\n        Explanation:\n        There are 5 occurrences of [0] as a subarray.\n        There are 3 occurrences of [0,0] as a subarray.\n        There is 1 occurrence of [0,0,0] as a subarray.\n        There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.\n        Example 3:\n        Input: nums = [2,10,2019]\n        Output: 0\n        Explanation: There is no subarray filled with 0. Therefore, we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2347,
-        "title": "Best Poker Hand",
-        "question": "class Solution:\n    def bestHand(self, ranks: List[int], suits: List[str]) -> str:\n        \"\"\"\n        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].\n        The 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.\n        Return a string representing the best type of poker hand you can make with the given cards.\n        Note that the return values are case-sensitive.\n        Example 1:\n        Input: ranks = [13,2,3,1,9], suits = [\"a\",\"a\",\"a\",\"a\",\"a\"]\n        Output: \"Flush\"\n        Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a \"Flush\".\n        Example 2:\n        Input: ranks = [4,4,2,4,4], suits = [\"d\",\"a\",\"a\",\"b\",\"c\"]\n        Output: \"Three of a Kind\"\n        Explanation: 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\".\n        Note that we could also make a \"Pair\" hand but \"Three of a Kind\" is a better hand.\n        Also note that other cards could be used to make the \"Three of a Kind\" hand.\n        Example 3:\n        Input: ranks = [10,10,2,12,9], suits = [\"a\",\"b\",\"c\",\"a\",\"d\"]\n        Output: \"Pair\"\n        Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a \"Pair\".\n        Note that we cannot make a \"Flush\" or a \"Three of a Kind\".\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2349,
-        "title": "Design a Number Container System",
-        "question": "class NumberContainers:\n    def __init__(self):\n    def change(self, index: int, number: int) -> None:\n    def find(self, number: int) -> int:\n        \"\"\"\n        Design a number container system that can do the following:\n            Insert or Replace a number at the given index in the system.\n            Return the smallest index for the given number in the system.\n        Implement the NumberContainers class:\n            NumberContainers() Initializes the number container system.\n            void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it.\n            int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.\n        Example 1:\n        Input\n        [\"NumberContainers\", \"find\", \"change\", \"change\", \"change\", \"change\", \"find\", \"change\", \"find\"]\n        [[], [10], [2, 10], [1, 10], [3, 10], [5, 10], [10], [1, 20], [10]]\n        Output\n        [null, -1, null, null, null, null, 1, null, 2]\n        Explanation\n        NumberContainers nc = new NumberContainers();\n        nc.find(10); // There is no index that is filled with number 10. Therefore, we return -1.\n        nc.change(2, 10); // Your container at index 2 will be filled with number 10.\n        nc.change(1, 10); // Your container at index 1 will be filled with number 10.\n        nc.change(3, 10); // Your container at index 3 will be filled with number 10.\n        nc.change(5, 10); // Your container at index 5 will be filled with number 10.\n        nc.find(10); // Number 10 is at the indices 1, 2, 3, and 5. Since the smallest index that is filled with 10 is 1, we return 1.\n        nc.change(1, 20); // Your container at index 1 will be filled with number 20. Note that index 1 was filled with 10 and then replaced with 20. \n        nc.find(10); // Number 10 is at the indices 2, 3, and 5. The smallest index that is filled with 10 is 2. Therefore, we return 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2350,
-        "title": "Shortest Impossible Sequence of Rolls",
-        "question": "class Solution:\n    def shortestSequence(self, rolls: List[int], k: int) -> int:\n        \"\"\"\n        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].\n        Return the length of the shortest sequence of rolls that cannot be taken from rolls.\n        A sequence of rolls of length len is the result of rolling a k sided dice len times.\n        Note that the sequence taken does not have to be consecutive as long as it is in order.\n        Example 1:\n        Input: rolls = [4,2,1,2,3,3,2,4,1], k = 4\n        Output: 3\n        Explanation: Every sequence of rolls of length 1, [1], [2], [3], [4], can be taken from rolls.\n        Every sequence of rolls of length 2, [1, 1], [1, 2], ..., [4, 4], can be taken from rolls.\n        The sequence [1, 4, 2] cannot be taken from rolls, so we return 3.\n        Note that there are other sequences that cannot be taken from rolls.\n        Example 2:\n        Input: rolls = [1,1,2,2], k = 2\n        Output: 2\n        Explanation: Every sequence of rolls of length 1, [1], [2], can be taken from rolls.\n        The sequence [2, 1] cannot be taken from rolls, so we return 2.\n        Note that there are other sequences that cannot be taken from rolls but [2, 1] is the shortest.\n        Example 3:\n        Input: rolls = [1,1,3,2,2,2,3,3], k = 4\n        Output: 1\n        Explanation: The sequence [4] cannot be taken from rolls, so we return 1.\n        Note that there are other sequences that cannot be taken from rolls but [4] is the shortest.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2357,
-        "title": "Make Array Zero by Subtracting Equal Amounts",
-        "question": "class Solution:\n    def minimumOperations(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a non-negative integer array nums. In one operation, you must:\n            Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.\n            Subtract x from every positive element in nums.\n        Return the minimum number of operations to make every element in nums equal to 0.\n        Example 1:\n        Input: nums = [1,5,0,3,5]\n        Output: 3\n        Explanation:\n        In the first operation, choose x = 1. Now, nums = [0,4,0,2,4].\n        In the second operation, choose x = 2. Now, nums = [0,2,0,0,2].\n        In the third operation, choose x = 2. Now, nums = [0,0,0,0,0].\n        Example 2:\n        Input: nums = [0]\n        Output: 0\n        Explanation: Each element in nums is already 0 so no operations are needed.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2358,
-        "title": "Maximum Number of Groups Entering a Competition",
-        "question": "class Solution:\n    def maximumGroups(self, grades: List[int]) -> int:\n        \"\"\"\n        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:\n            The 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).\n            The 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).\n        Return the maximum number of groups that can be formed.\n        Example 1:\n        Input: grades = [10,6,12,7,3,5]\n        Output: 3\n        Explanation: 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\n        It can be shown that it is not possible to form more than 3 groups.\n        Example 2:\n        Input: grades = [8,8]\n        Output: 1\n        Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2359,
-        "title": "Find Closest Node to Given Two Nodes",
-        "question": "class Solution:\n    def closestMeetingNode(self, edges: List[int], node1: int, node2: int) -> int:\n        \"\"\"\n        You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.\n        The 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.\n        You are also given two integers node1 and node2.\n        Return 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.\n        Note that edges may contain cycles.\n        Example 1:\n        Input: edges = [2,2,3,-1], node1 = 0, node2 = 1\n        Output: 2\n        Explanation: The distance from node 0 to node 2 is 1, and the distance from node 1 to node 2 is 1.\n        The 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.\n        Example 2:\n        Input: edges = [1,2,-1], node1 = 0, node2 = 2\n        Output: 2\n        Explanation: The distance from node 0 to node 2 is 2, and the distance from node 2 to itself is 0.\n        The 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2360,
-        "title": "Longest Cycle in a Graph",
-        "question": "class Solution:\n    def longestCycle(self, edges: List[int]) -> int:\n        \"\"\"\n        You are given a directed graph of n nodes numbered from 0 to n - 1, where each node has at most one outgoing edge.\n        The 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.\n        Return the length of the longest cycle in the graph. If no cycle exists, return -1.\n        A cycle is a path that starts and ends at the same node.\n        Example 1:\n        Input: edges = [3,3,4,2,3]\n        Output: 3\n        Explanation: The longest cycle in the graph is the cycle: 2 -> 4 -> 3 -> 2.\n        The length of this cycle is 3, so 3 is returned.\n        Example 2:\n        Input: edges = [2,-1,3,1]\n        Output: -1\n        Explanation: There are no cycles in this graph.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2367,
-        "title": "Number of Arithmetic Triplets",
-        "question": "class Solution:\n    def arithmeticTriplets(self, nums: List[int], diff: int) -> int:\n        \"\"\"\n        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:\n            i < j < k,\n            nums[j] - nums[i] == diff, and\n            nums[k] - nums[j] == diff.\n        Return the number of unique arithmetic triplets.\n        Example 1:\n        Input: nums = [0,1,4,6,7,10], diff = 3\n        Output: 2\n        Explanation:\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. \n        Example 2:\n        Input: nums = [4,5,6,7,8,9], diff = 2\n        Output: 2\n        Explanation:\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        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2369,
-        "title": "Check if There is a Valid Partition For The Array",
-        "question": "class Solution:\n    def validPartition(self, nums: List[int]) -> bool:\n        \"\"\"\n        You are given a 0-indexed integer array nums. You have to partition the array into one or more contiguous subarrays.\n        We call a partition of the array valid if each of the obtained subarrays satisfies one of the following conditions:\n            The subarray consists of exactly 2 equal elements. For example, the subarray [2,2] is good.\n            The subarray consists of exactly 3 equal elements. For example, the subarray [4,4,4] is good.\n            The 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.\n        Return true if the array has at least one valid partition. Otherwise, return false.\n        Example 1:\n        Input: nums = [4,4,4,5,6]\n        Output: true\n        Explanation: The array can be partitioned into the subarrays [4,4] and [4,5,6].\n        This partition is valid, so we return true.\n        Example 2:\n        Input: nums = [1,1,1,2]\n        Output: false\n        Explanation: There is no valid partition for this array.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2370,
-        "title": "Longest Ideal Subsequence",
-        "question": "class Solution:\n    def longestIdealString(self, s: str, k: int) -> int:\n        \"\"\"\n        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:\n            t is a subsequence of the string s.\n            The absolute difference in the alphabet order of every two adjacent letters in t is less than or equal to k.\n        Return the length of the longest ideal string.\n        A 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        Note 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:\n        Input: s = \"acfgbd\", k = 2\n        Output: 4\n        Explanation: The longest ideal string is \"acbd\". The length of this string is 4, so 4 is returned.\n        Note that \"acfgbd\" is not ideal because 'c' and 'f' have a difference of 3 in alphabet order.\n        Example 2:\n        Input: s = \"abcd\", k = 3\n        Output: 4\n        Explanation: The longest ideal string is \"abcd\". The length of this string is 4, so 4 is returned.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2368,
-        "title": "Reachable Nodes With Restrictions",
-        "question": "class Solution:\n    def reachableNodes(self, n: int, edges: List[List[int]], restricted: List[int]) -> int:\n        \"\"\"\n        There is an undirected tree with n nodes labeled from 0 to n - 1 and n - 1 edges.\n        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. You are also given an integer array restricted which represents restricted nodes.\n        Return the maximum number of nodes you can reach from node 0 without visiting a restricted node.\n        Note that node 0 will not be a restricted node.\n        Example 1:\n        Input: n = 7, edges = [[0,1],[1,2],[3,1],[4,0],[0,5],[5,6]], restricted = [4,5]\n        Output: 4\n        Explanation: The diagram above shows the tree.\n        We have that [0,1,2,3] are the only nodes that can be reached from node 0 without visiting a restricted node.\n        Example 2:\n        Input: n = 7, edges = [[0,1],[0,2],[0,5],[0,4],[3,2],[6,5]], restricted = [4,2,1]\n        Output: 3\n        Explanation: The diagram above shows the tree.\n        We have that [0,5,6] are the only nodes that can be reached from node 0 without visiting a restricted node.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2363,
-        "title": "Merge Similar Items",
-        "question": "class Solution:\n    def mergeSimilarItems(self, items1: List[List[int]], items2: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given two 2D integer arrays, items1 and items2, representing two sets of items. Each array items has the following properties:\n            items[i] = [valuei, weighti] where valuei represents the value and weighti represents the weight of the ith item.\n            The value of each item in items is unique.\n        Return a 2D integer array ret where ret[i] = [valuei, weighti], with weighti being the sum of weights of all items with value valuei.\n        Note: ret should be returned in ascending order by value.\n        Example 1:\n        Input: items1 = [[1,1],[4,5],[3,8]], items2 = [[3,1],[1,5]]\n        Output: [[1,6],[3,9],[4,5]]\n        Explanation: \n        The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 5, total weight = 1 + 5 = 6.\n        The item with value = 3 occurs in items1 with weight = 8 and in items2 with weight = 1, total weight = 8 + 1 = 9.\n        The item with value = 4 occurs in items1 with weight = 5, total weight = 5.  \n        Therefore, we return [[1,6],[3,9],[4,5]].\n        Example 2:\n        Input: items1 = [[1,1],[3,2],[2,3]], items2 = [[2,1],[3,2],[1,3]]\n        Output: [[1,4],[2,4],[3,4]]\n        Explanation: \n        The item with value = 1 occurs in items1 with weight = 1 and in items2 with weight = 3, total weight = 1 + 3 = 4.\n        The item with value = 2 occurs in items1 with weight = 3 and in items2 with weight = 1, total weight = 3 + 1 = 4.\n        The item with value = 3 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4.\n        Therefore, we return [[1,4],[2,4],[3,4]].\n        Example 3:\n        Input: items1 = [[1,3],[2,2]], items2 = [[7,1],[2,2],[1,4]]\n        Output: [[1,7],[2,4],[7,1]]\n        Explanation:\n        The item with value = 1 occurs in items1 with weight = 3 and in items2 with weight = 4, total weight = 3 + 4 = 7. \n        The item with value = 2 occurs in items1 with weight = 2 and in items2 with weight = 2, total weight = 2 + 2 = 4. \n        The item with value = 7 occurs in items2 with weight = 1, total weight = 1.\n        Therefore, we return [[1,7],[2,4],[7,1]].\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2364,
-        "title": "Count Number of Bad Pairs",
-        "question": "class Solution:\n    def countBadPairs(self, nums: List[int]) -> int:\n        \"\"\"\n        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].\n        Return the total number of bad pairs in nums.\n        Example 1:\n        Input: nums = [4,1,3,3]\n        Output: 5\n        Explanation: The pair (0, 1) is a bad pair since 1 - 0 != 1 - 4.\n        The pair (0, 2) is a bad pair since 2 - 0 != 3 - 4, 2 != -1.\n        The pair (0, 3) is a bad pair since 3 - 0 != 3 - 4, 3 != -1.\n        The pair (1, 2) is a bad pair since 2 - 1 != 3 - 1, 1 != 2.\n        The pair (2, 3) is a bad pair since 3 - 2 != 3 - 3, 1 != 0.\n        There are a total of 5 bad pairs, so we return 5.\n        Example 2:\n        Input: nums = [1,2,3,4,5]\n        Output: 0\n        Explanation: There are no bad pairs.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2398,
-        "title": "Maximum Number of Robots Within Budget",
-        "question": "class Solution:\n    def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int:\n        \"\"\"\n        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.\n        The 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.\n        Return the maximum number of consecutive robots you can run such that the total cost does not exceed budget.\n        Example 1:\n        Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25\n        Output: 3\n        Explanation: \n        It is possible to run all individual and consecutive pairs of robots within budget.\n        To 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.\n        It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3.\n        Example 2:\n        Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19\n        Output: 0\n        Explanation: No robot can be run that does not exceed the budget, so we return 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2366,
-        "title": "Minimum Replacements to Sort the Array",
-        "question": "class Solution:\n    def minimumReplacement(self, nums: List[int]) -> int:\n        \"\"\"\n        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.\n            For 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].\n        Return the minimum number of operations to make an array that is sorted in non-decreasing order.\n        Example 1:\n        Input: nums = [3,9,3]\n        Output: 2\n        Explanation: 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]\n        There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.\n        Example 2:\n        Input: nums = [1,2,3,4,5]\n        Output: 0\n        Explanation: The array is already in non-decreasing order. Therefore, we return 0. \n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2373,
-        "title": "Largest Local Values in a Matrix",
-        "question": "class Solution:\n    def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given an n x n integer matrix grid.\n        Generate an integer matrix maxLocal of size (n - 2) x (n - 2) such that:\n            maxLocal[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.\n        In other words, we want to find the largest value in every contiguous 3 x 3 matrix in grid.\n        Return the generated matrix.\n        Example 1:\n        Input: grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]\n        Output: [[9,9],[8,6]]\n        Explanation: The diagram above shows the original matrix and the generated matrix.\n        Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.\n        Example 2:\n        Input: 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]]\n        Output: [[2,2,2],[2,2,2],[2,2,2]]\n        Explanation: Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2374,
-        "title": "Node With Highest Edge Score",
-        "question": "class Solution:\n    def edgeScore(self, edges: List[int]) -> int:\n        \"\"\"\n        You are given a directed graph with n nodes labeled from 0 to n - 1, where each node has exactly one outgoing edge.\n        The 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].\n        The 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.\n        Return 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:\n        Input: edges = [1,0,0,0,0,7,7,5]\n        Output: 7\n        Explanation:\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.\n        Node 7 has the highest edge score so return 7.\n        Example 2:\n        Input: edges = [2,0,0,2]\n        Output: 0\n        Explanation:\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.\n        Nodes 0 and 2 both have an edge score of 3. Since node 0 has a smaller index, we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2375,
-        "title": "Construct Smallest Number From DI String",
-        "question": "class Solution:\n    def smallestNumber(self, pattern: str) -> str:\n        \"\"\"\n        You are given a 0-indexed string pattern of length n consisting of the characters 'I' meaning increasing and 'D' meaning decreasing.\n        A 0-indexed string num of length n + 1 is created using the following conditions:\n            num consists of the digits '1' to '9', where each digit is used at most once.\n            If pattern[i] == 'I', then num[i] < num[i + 1].\n            If pattern[i] == 'D', then num[i] > num[i + 1].\n        Return the lexicographically smallest possible string num that meets the conditions.\n        Example 1:\n        Input: pattern = \"IIIDIDDD\"\n        Output: \"123549876\"\n        Explanation:\n        At indices 0, 1, 2, and 4 we must have that num[i] < num[i+1].\n        At indices 3, 5, 6, and 7 we must have that num[i] > num[i+1].\n        Some possible values of num are \"245639871\", \"135749862\", and \"123849765\".\n        It can be proven that \"123549876\" is the smallest possible num that meets the conditions.\n        Note that \"123414321\" is not possible because the digit '1' is used more than once.\n        Example 2:\n        Input: pattern = \"DDD\"\n        Output: \"4321\"\n        Explanation:\n        Some possible values of num are \"9876\", \"7321\", and \"8742\".\n        It can be proven that \"4321\" is the smallest possible num that meets the conditions.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2376,
-        "title": "Count Special Integers",
-        "question": "class Solution:\n    def countSpecialNumbers(self, n: int) -> int:\n        \"\"\"\n        We call a positive integer special if all of its digits are distinct.\n        Given a positive integer n, return the number of special integers that belong to the interval [1, n].\n        Example 1:\n        Input: n = 20\n        Output: 19\n        Explanation: All the integers from 1 to 20, except 11, are special. Thus, there are 19 special integers.\n        Example 2:\n        Input: n = 5\n        Output: 5\n        Explanation: All the integers from 1 to 5 are special.\n        Example 3:\n        Input: n = 135\n        Output: 110\n        Explanation: There are 110 integers from 1 to 135 that are special.\n        Some of the integers that are not special are: 22, 114, and 131.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2383,
-        "title": "Minimum Hours of Training to Win a Competition",
-        "question": "class Solution:\n    def minNumberOfHours(self, initialEnergy: int, initialExperience: int, energy: List[int], experience: List[int]) -> int:\n        \"\"\"\n        You are entering a competition, and are given two positive integers initialEnergy and initialExperience denoting your initial energy and initial experience respectively.\n        You are also given two 0-indexed integer arrays energy and experience, both of length n.\n        You 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.\n        Defeating the ith opponent increases your experience by experience[i], but decreases your energy by energy[i].\n        Before 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.\n        Return the minimum number of training hours required to defeat all n opponents.\n        Example 1:\n        Input: initialEnergy = 5, initialExperience = 3, energy = [1,4,3,2], experience = [2,6,3,1]\n        Output: 8\n        Explanation: You can increase your energy to 11 after 6 hours of training, and your experience to 5 after 2 hours of training.\n        You 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.\n        You did a total of 6 + 2 = 8 hours of training before the competition, so we return 8.\n        It can be proven that no smaller answer exists.\n        Example 2:\n        Input: initialEnergy = 2, initialExperience = 4, energy = [1], experience = [3]\n        Output: 0\n        Explanation: You do not need any additional energy or experience to win the competition, so we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2385,
-        "title": "Amount of Time for Binary Tree to Be Infected",
-        "question": "class Solution:\n    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:\n        \"\"\"\n        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.\n        Each minute, a node becomes infected if:\n            The node is currently uninfected.\n            The node is adjacent to an infected node.\n        Return the number of minutes needed for the entire tree to be infected.\n        Example 1:\n        Input: root = [1,5,3,null,4,10,6,9,2], start = 3\n        Output: 4\n        Explanation: 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\n        It takes 4 minutes for the whole tree to be infected so we return 4.\n        Example 2:\n        Input: root = [1], start = 1\n        Output: 0\n        Explanation: At minute 0, the only node in the tree is infected so we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2386,
-        "title": "Find the K-Sum of an Array",
-        "question": "class Solution:\n    def kSum(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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.\n        We define the K-Sum of the array as the kth largest subsequence sum that can be obtained (not necessarily distinct).\n        Return the K-Sum of the array.\n        A 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        Note that the empty subsequence is considered to have a sum of 0.\n        Example 1:\n        Input: nums = [2,4,-2], k = 5\n        Output: 2\n        Explanation: 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.\n        The 5-Sum of the array is 2.\n        Example 2:\n        Input: nums = [1,-2,3,4,-10,12], k = 16\n        Output: 10\n        Explanation: The 16-Sum of the array is 10.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2379,
-        "title": "Minimum Recolors to Get K Consecutive Black Blocks",
-        "question": "class Solution:\n    def minimumRecolors(self, blocks: str, k: int) -> int:\n        \"\"\"\n        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.\n        You are also given an integer k, which is the desired number of consecutive black blocks.\n        In one operation, you can recolor a white block such that it becomes a black block.\n        Return the minimum number of operations needed such that there is at least one occurrence of k consecutive black blocks.\n        Example 1:\n        Input: blocks = \"WBBWWBBWBW\", k = 7\n        Output: 3\n        Explanation:\n        One way to achieve 7 consecutive black blocks is to recolor the 0th, 3rd, and 4th blocks\n        so that blocks = \"BBBBBBBWBW\". \n        It can be shown that there is no way to achieve 7 consecutive black blocks in less than 3 operations.\n        Therefore, we return 3.\n        Example 2:\n        Input: blocks = \"WBWBBBW\", k = 2\n        Output: 0\n        Explanation:\n        No changes need to be made, since 2 consecutive black blocks already exist.\n        Therefore, we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2380,
-        "title": "Time Needed to Rearrange a Binary String",
-        "question": "class Solution:\n    def secondsToRemoveOccurrences(self, s: str) -> int:\n        \"\"\"\n        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.\n        Return the number of seconds needed to complete this process.\n        Example 1:\n        Input: s = \"0110101\"\n        Output: 4\n        Explanation: \n        After one second, s becomes \"1011010\".\n        After another second, s becomes \"1101100\".\n        After the third second, s becomes \"1110100\".\n        After the fourth second, s becomes \"1111000\".\n        No occurrence of \"01\" exists any longer, and the process needed 4 seconds to complete,\n        so we return 4.\n        Example 2:\n        Input: s = \"11100\"\n        Output: 0\n        Explanation:\n        No occurrence of \"01\" exists in s, and the processes needed 0 seconds to complete,\n        so we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2381,
-        "title": "Shifting Letters II",
-        "question": "class Solution:\n    def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:\n        \"\"\"\n        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.\n        Shifting 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').\n        Return the final string after all such shifts to s are applied.\n        Example 1:\n        Input: s = \"abc\", shifts = [[0,1,0],[1,2,1],[0,2,1]]\n        Output: \"ace\"\n        Explanation: Firstly, shift the characters from index 0 to index 1 backward. Now s = \"zac\".\n        Secondly, shift the characters from index 1 to index 2 forward. Now s = \"zbd\".\n        Finally, shift the characters from index 0 to index 2 forward. Now s = \"ace\".\n        Example 2:\n        Input: s = \"dztz\", shifts = [[0,0,0],[1,1,1]]\n        Output: \"catz\"\n        Explanation: Firstly, shift the characters from index 0 to index 0 backward. Now s = \"cztz\".\n        Finally, shift the characters from index 1 to index 1 forward. Now s = \"catz\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2382,
-        "title": "Maximum Segment Sum After Removals",
-        "question": "class Solution:\n    def maximumSegmentSum(self, nums: List[int], removeQueries: List[int]) -> List[int]:\n        \"\"\"\n        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.\n        A segment is a contiguous sequence of positive integers in nums. A segment sum is the sum of every element in a segment.\n        Return an integer array answer, of length n, where answer[i] is the maximum segment sum after applying the ith removal.\n        Note: The same index will not be removed more than once.\n        Example 1:\n        Input: nums = [1,2,5,6,1], removeQueries = [0,3,2,4,1]\n        Output: [14,7,2,2,0]\n        Explanation: Using 0 to indicate a removed element, the answer is as follows:\n        Query 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].\n        Query 2: Remove the 3rd element, nums becomes [0,2,5,0,1] and the maximum segment sum is 7 for segment [2,5].\n        Query 3: Remove the 2nd element, nums becomes [0,2,0,0,1] and the maximum segment sum is 2 for segment [2]. \n        Query 4: Remove the 4th element, nums becomes [0,2,0,0,0] and the maximum segment sum is 2 for segment [2]. \n        Query 5: Remove the 1st element, nums becomes [0,0,0,0,0] and the maximum segment sum is 0, since there are no segments.\n        Finally, we return [14,7,2,2,0].\n        Example 2:\n        Input: nums = [3,2,11,1], removeQueries = [3,2,1,0]\n        Output: [16,5,3,0]\n        Explanation: Using 0 to indicate a removed element, the answer is as follows:\n        Query 1: Remove the 3rd element, nums becomes [3,2,11,0] and the maximum segment sum is 16 for segment [3,2,11].\n        Query 2: Remove the 2nd element, nums becomes [3,2,0,0] and the maximum segment sum is 5 for segment [3,2].\n        Query 3: Remove the 1st element, nums becomes [3,0,0,0] and the maximum segment sum is 3 for segment [3].\n        Query 4: Remove the 0th element, nums becomes [0,0,0,0] and the maximum segment sum is 0, since there are no segments.\n        Finally, we return [16,5,3,0].\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2389,
-        "title": "Longest Subsequence With Limited Sum",
-        "question": "class Solution:\n    def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:\n        \"\"\"\n        You are given an integer array nums of length n, and an integer array queries of length m.\n        Return 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].\n        A 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:\n        Input: nums = [4,5,2,1], queries = [3,10,21]\n        Output: [2,3,4]\n        Explanation: 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.\n        Example 2:\n        Input: nums = [2,3,4,5], queries = [1]\n        Output: [0]\n        Explanation: The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2390,
-        "title": "Removing Stars From a String",
-        "question": "class Solution:\n    def removeStars(self, s: str) -> str:\n        \"\"\"\n        You are given a string s, which contains stars *.\n        In one operation, you can:\n            Choose a star in s.\n            Remove the closest non-star character to its left, as well as remove the star itself.\n        Return the string after all stars have been removed.\n        Note:\n            The input will be generated such that the operation is always possible.\n            It can be shown that the resulting string will always be unique.\n        Example 1:\n        Input: s = \"leet**cod*e\"\n        Output: \"lecoe\"\n        Explanation: 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\".\n        There are no more stars, so we return \"lecoe\".\n        Example 2:\n        Input: s = \"erase*****\"\n        Output: \"\"\n        Explanation: The entire string is removed, so we return an empty string.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2391,
-        "title": "Minimum Amount of Time to Collect Garbage",
-        "question": "class Solution:\n    def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:\n        \"\"\"\n        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.\n        You 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.\n        There 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.\n        Only 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.\n        Return the minimum number of minutes needed to pick up all the garbage.\n        Example 1:\n        Input: garbage = [\"G\",\"P\",\"GP\",\"GG\"], travel = [2,4,3]\n        Output: 21\n        Explanation:\n        The paper garbage truck:\n        1. Travels from house 0 to house 1\n        2. Collects the paper garbage at house 1\n        3. Travels from house 1 to house 2\n        4. Collects the paper garbage at house 2\n        Altogether, it takes 8 minutes to pick up all the paper garbage.\n        The glass garbage truck:\n        1. Collects the glass garbage at house 0\n        2. Travels from house 0 to house 1\n        3. Travels from house 1 to house 2\n        4. Collects the glass garbage at house 2\n        5. Travels from house 2 to house 3\n        6. Collects the glass garbage at house 3\n        Altogether, it takes 13 minutes to pick up all the glass garbage.\n        Since there is no metal garbage, we do not need to consider the metal garbage truck.\n        Therefore, it takes a total of 8 + 13 = 21 minutes to collect all the garbage.\n        Example 2:\n        Input: garbage = [\"MMM\",\"PGM\",\"GP\"], travel = [3,10]\n        Output: 37\n        Explanation:\n        The metal garbage truck takes 7 minutes to pick up all the metal garbage.\n        The paper garbage truck takes 15 minutes to pick up all the paper garbage.\n        The glass garbage truck takes 15 minutes to pick up all the glass garbage.\n        It takes a total of 7 + 15 + 15 = 37 minutes to collect all the garbage.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2392,
-        "title": "Build a Matrix With Conditions",
-        "question": "class Solution:\n    def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given a positive integer k. You are also given:\n            a 2D integer array rowConditions of size n where rowConditions[i] = [abovei, belowi], and\n            a 2D integer array colConditions of size m where colConditions[i] = [lefti, righti].\n        The two arrays contain integers from 1 to k.\n        You 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.\n        The matrix should also satisfy the following conditions:\n            The number abovei should appear in a row that is strictly above the row at which the number belowi appears for all i from 0 to n - 1.\n            The number lefti should appear in a column that is strictly left of the column at which the number righti appears for all i from 0 to m - 1.\n        Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.\n        Example 1:\n        Input: k = 3, rowConditions = [[1,2],[3,2]], colConditions = [[2,1],[3,2]]\n        Output: [[3,0,0],[0,0,1],[0,2,0]]\n        Explanation: The diagram above shows a valid example of a matrix that satisfies all the conditions.\n        The 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.\n        The 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.\n        Note that there may be multiple correct answers.\n        Example 2:\n        Input: k = 3, rowConditions = [[1,2],[2,3],[3,1],[2,3]], colConditions = [[2,1]]\n        Output: []\n        Explanation: From the first two conditions, 3 has to be below 1 but the third conditions needs 3 to be above 1 to be satisfied.\n        No matrix can satisfy all the conditions, so we return the empty matrix.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2342,
-        "title": "Max Sum of a Pair With Equal Sum of Digits",
-        "question": "class Solution:\n    def maximumSum(self, nums: List[int]) -> int:\n        \"\"\"\n        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].\n        Return 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:\n        Input: nums = [18,43,36,13,7]\n        Output: 54\n        Explanation: 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.\n        So the maximum sum that we can obtain is 54.\n        Example 2:\n        Input: nums = [10,12,19,14]\n        Output: -1\n        Explanation: There are no two numbers that satisfy the conditions, so we return -1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2384,
-        "title": "Largest Palindromic Number",
-        "question": "class Solution:\n    def largestPalindromic(self, num: str) -> str:\n        \"\"\"\n        You are given a string num consisting of digits only.\n        Return 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.\n        Notes:\n            You do not need to use all the digits of num, but you must use at least one digit.\n            The digits can be reordered.\n        Example 1:\n        Input: num = \"444947137\"\n        Output: \"7449447\"\n        Explanation: \n        Use the digits \"4449477\" from \"444947137\" to form the palindromic integer \"7449447\".\n        It can be shown that \"7449447\" is the largest palindromic integer that can be formed.\n        Example 2:\n        Input: num = \"00009\"\n        Output: \"9\"\n        Explanation: \n        It can be shown that \"9\" is the largest palindromic integer that can be formed.\n        Note that the integer returned should not contain leading zeroes.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2399,
-        "title": "Check Distances Between Same Letters",
-        "question": "class Solution:\n    def checkDistances(self, s: str, distance: List[int]) -> bool:\n        \"\"\"\n        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.\n        Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25).\n        In 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.\n        Return true if s is a well-spaced string, otherwise return false.\n        Example 1:\n        Input: 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]\n        Output: true\n        Explanation:\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.\n        Note that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.\n        Return true because s is a well-spaced string.\n        Example 2:\n        Input: 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]\n        Output: false\n        Explanation:\n        - 'a' appears at indices 0 and 1 so there are zero letters between them.\n        Because distance[0] = 1, s is not a well-spaced string.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2400,
-        "title": "Number of Ways to Reach a Position After Exactly k Steps",
-        "question": "class Solution:\n    def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:\n        \"\"\"\n        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.\n        Given 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.\n        Two ways are considered different if the order of the steps made is not exactly the same.\n        Note that the number line includes negative integers.\n        Example 1:\n        Input: startPos = 1, endPos = 2, k = 3\n        Output: 3\n        Explanation: 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.\n        It can be proven that no other way is possible, so we return 3.\n        Example 2:\n        Input: startPos = 2, endPos = 5, k = 10\n        Output: 0\n        Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2401,
-        "title": "Longest Nice Subarray",
-        "question": "class Solution:\n    def longestNiceSubarray(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given an array nums consisting of positive integers.\n        We 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.\n        Return the length of the longest nice subarray.\n        A subarray is a contiguous part of an array.\n        Note that subarrays of length 1 are always considered nice.\n        Example 1:\n        Input: nums = [1,3,8,48,10]\n        Output: 3\n        Explanation: 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.\n        It can be proven that no longer nice subarray can be obtained, so we return 3.\n        Example 2:\n        Input: nums = [3,1,5,11,13]\n        Output: 1\n        Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2402,
-        "title": "Meeting Rooms III",
-        "question": "class Solution:\n    def mostBooked(self, n: int, meetings: List[List[int]]) -> int:\n        \"\"\"\n        You are given an integer n. There are n rooms numbered from 0 to n - 1.\n        You 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.\n        Meetings are allocated to rooms in the following manner:\n            Each meeting will take place in the unused room with the lowest number.\n            If 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.\n            When a room becomes unused, meetings that have an earlier original start time should be given the room.\n        Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.\n        A half-closed interval [a, b) is the interval between a and b including a and not including b.\n        Example 1:\n        Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]\n        Output: 0\n        Explanation:\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).\n        Both rooms 0 and 1 held 2 meetings, so we return 0. \n        Example 2:\n        Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]\n        Output: 1\n        Explanation:\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).\n        Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1. \n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2395,
-        "title": "Find Subarrays With Equal Sum",
-        "question": "class Solution:\n    def findSubarrays(self, nums: List[int]) -> bool:\n        \"\"\"\n        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.\n        Return true if these subarrays exist, and false otherwise.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [4,2,4]\n        Output: true\n        Explanation: The subarrays with elements [4,2] and [2,4] have the same sum of 6.\n        Example 2:\n        Input: nums = [1,2,3,4,5]\n        Output: false\n        Explanation: No two subarrays of size 2 have the same sum.\n        Example 3:\n        Input: nums = [0,0,0]\n        Output: true\n        Explanation: The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. \n        Note 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        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2396,
-        "title": "Strictly Palindromic Number",
-        "question": "class Solution:\n    def isStrictlyPalindromic(self, n: int) -> bool:\n        \"\"\"\n        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.\n        Given an integer n, return true if n is strictly palindromic and false otherwise.\n        A string is palindromic if it reads the same forward and backward.\n        Example 1:\n        Input: n = 9\n        Output: false\n        Explanation: In base 2: 9 = 1001 (base 2), which is palindromic.\n        In base 3: 9 = 100 (base 3), which is not palindromic.\n        Therefore, 9 is not strictly palindromic so we return false.\n        Note that in bases 4, 5, 6, and 7, n = 9 is also not palindromic.\n        Example 2:\n        Input: n = 4\n        Output: false\n        Explanation: We only consider base 2: 4 = 100 (base 2), which is not palindromic.\n        Therefore, we return false.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2397,
-        "title": "Maximum Rows Covered by Columns",
-        "question": "class Solution:\n    def maximumRows(self, matrix: List[List[int]], numSelect: int) -> int:\n        \"\"\"\n        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.\n        Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if:\n            For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or,\n            No cell in row has a value of 1.\n        You need to choose numSelect columns such that the number of rows that are covered is maximized.\n        Return the maximum number of rows that can be covered by a set of numSelect columns.\n        Example 1:\n        Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2\n        Output: 3\n        Explanation: One possible way to cover 3 rows is shown in the diagram above.\n        We 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.\n        Thus, we can cover three rows.\n        Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered.\n        Example 2:\n        Input: matrix = [[1],[0]], numSelect = 1\n        Output: 2\n        Explanation: Selecting the only column will result in both rows being covered since the entire matrix is selected.\n        Therefore, we return 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2365,
-        "title": "Task Scheduler II",
-        "question": "class Solution:\n    def taskSchedulerII(self, tasks: List[int], space: int) -> int:\n        \"\"\"\n        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.\n        You 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.\n        Each day, until all tasks have been completed, you must either:\n            Complete the next task from tasks, or\n            Take a break.\n        Return the minimum number of days needed to complete all tasks.\n        Example 1:\n        Input: tasks = [1,2,1,2,3,1], space = 3\n        Output: 9\n        Explanation:\n        One way to complete all tasks in 9 days is as follows:\n        Day 1: Complete the 0th task.\n        Day 2: Complete the 1st task.\n        Day 3: Take a break.\n        Day 4: Take a break.\n        Day 5: Complete the 2nd task.\n        Day 6: Complete the 3rd task.\n        Day 7: Take a break.\n        Day 8: Complete the 4th task.\n        Day 9: Complete the 5th task.\n        It can be shown that the tasks cannot be completed in less than 9 days.\n        Example 2:\n        Input: tasks = [5,8,8,5], space = 2\n        Output: 6\n        Explanation:\n        One way to complete all tasks in 6 days is as follows:\n        Day 1: Complete the 0th task.\n        Day 2: Complete the 1st task.\n        Day 3: Take a break.\n        Day 4: Take a break.\n        Day 5: Complete the 2nd task.\n        Day 6: Complete the 3rd task.\n        It can be shown that the tasks cannot be completed in less than 6 days.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2404,
-        "title": "Most Frequent Even Element",
-        "question": "class Solution:\n    def mostFrequentEven(self, nums: List[int]) -> int:\n        \"\"\"\n        Given an integer array nums, return the most frequent even element.\n        If there is a tie, return the smallest one. If there is no such element, return -1.\n        Example 1:\n        Input: nums = [0,1,2,2,4,4,1]\n        Output: 2\n        Explanation:\n        The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.\n        We return the smallest one, which is 2.\n        Example 2:\n        Input: nums = [4,4,4,9,2,4]\n        Output: 4\n        Explanation: 4 is the even element appears the most.\n        Example 3:\n        Input: nums = [29,47,21,41,13,37,25,7]\n        Output: -1\n        Explanation: There is no even element.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2405,
-        "title": "Optimal Partition of String",
-        "question": "class Solution:\n    def partitionString(self, s: str) -> int:\n        \"\"\"\n        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.\n        Return the minimum number of substrings in such a partition.\n        Note that each character should belong to exactly one substring in a partition.\n        Example 1:\n        Input: s = \"abacaba\"\n        Output: 4\n        Explanation:\n        Two possible partitions are (\"a\",\"ba\",\"cab\",\"a\") and (\"ab\",\"a\",\"ca\",\"ba\").\n        It can be shown that 4 is the minimum number of substrings needed.\n        Example 2:\n        Input: s = \"ssssss\"\n        Output: 6\n        Explanation:\n        The only valid partition is (\"s\",\"s\",\"s\",\"s\",\"s\",\"s\").\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2406,
-        "title": "Divide Intervals Into Minimum Number of Groups",
-        "question": "class Solution:\n    def minGroups(self, intervals: List[List[int]]) -> int:\n        \"\"\"\n        You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].\n        You 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.\n        Return the minimum number of groups you need to make.\n        Two 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:\n        Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]\n        Output: 3\n        Explanation: 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].\n        It can be proven that it is not possible to divide the intervals into fewer than 3 groups.\n        Example 2:\n        Input: intervals = [[1,3],[5,6],[8,10],[11,13]]\n        Output: 1\n        Explanation: None of the intervals overlap, so we can put all of them in one group.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2413,
-        "title": "Smallest Even Multiple",
-        "question": "class Solution:\n    def smallestEvenMultiple(self, n: int) -> int:\n        \"\"\"\n        Given a positive integer n, return the smallest positive integer that is a multiple of both 2 and n.\n        Example 1:\n        Input: n = 5\n        Output: 10\n        Explanation: The smallest multiple of both 5 and 2 is 10.\n        Example 2:\n        Input: n = 6\n        Output: 6\n        Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2414,
-        "title": "Length of the Longest Alphabetical Continuous Substring",
-        "question": "class Solution:\n    def longestContinuousSubstring(self, s: str) -> int:\n        \"\"\"\n        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\".\n            For example, \"abc\" is an alphabetical continuous string, while \"acb\" and \"za\" are not.\n        Given a string s consisting of lowercase letters only, return the length of the longest alphabetical continuous substring.\n        Example 1:\n        Input: s = \"abacaba\"\n        Output: 2\n        Explanation: There are 4 distinct continuous substrings: \"a\", \"b\", \"c\" and \"ab\".\n        \"ab\" is the longest continuous substring.\n        Example 2:\n        Input: s = \"abcde\"\n        Output: 5\n        Explanation: \"abcde\" is the longest continuous substring.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2415,
-        "title": "Reverse Odd Levels of Binary Tree",
-        "question": "class Solution:\n    def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n        \"\"\"\n        Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.\n            For 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].\n        Return the root of the reversed tree.\n        A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.\n        The level of a node is the number of edges along the path between it and the root node.\n        Example 1:\n        Input: root = [2,3,5,8,13,21,34]\n        Output: [2,5,3,8,13,21,34]\n        Explanation: \n        The tree has only one odd level.\n        The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.\n        Example 2:\n        Input: root = [7,13,11]\n        Output: [7,11,13]\n        Explanation: \n        The nodes at level 1 are 13, 11, which are reversed and become 11, 13.\n        Example 3:\n        Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]\n        Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]\n        Explanation: \n        The odd levels have non-zero values.\n        The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.\n        The 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2416,
-        "title": "Sum of Prefix Scores of Strings",
-        "question": "class Solution:\n    def sumPrefixScores(self, words: List[str]) -> List[int]:\n        \"\"\"\n        You are given an array words of size n consisting of non-empty strings.\n        We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i].\n            For example, if words = [\"a\", \"ab\", \"abc\", \"cab\"], then the score of \"ab\" is 2, since \"ab\" is a prefix of both \"ab\" and \"abc\".\n        Return an array answer of size n where answer[i] is the sum of scores of every non-empty prefix of words[i].\n        Note that a string is considered as a prefix of itself.\n        Example 1:\n        Input: words = [\"abc\",\"ab\",\"bc\",\"b\"]\n        Output: [5,4,3,2]\n        Explanation: 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\".\n        The 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\".\n        The 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\".\n        The total is answer[2] = 2 + 1 = 3.\n        - \"b\" has 1 prefix: \"b\".\n        - There are 2 strings with the prefix \"b\".\n        The total is answer[3] = 2.\n        Example 2:\n        Input: words = [\"abcd\"]\n        Output: [4]\n        Explanation:\n        \"abcd\" has 4 prefixes: \"a\", \"ab\", \"abc\", and \"abcd\".\n        Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2409,
-        "title": "Count Days Spent Together",
-        "question": "class Solution:\n    def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:\n        \"\"\"\n        Alice and Bob are traveling to Rome for separate business meetings.\n        You 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.\n        Return the total number of days that Alice and Bob are in Rome together.\n        You 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:\n        Input: arriveAlice = \"08-15\", leaveAlice = \"08-18\", arriveBob = \"08-16\", leaveBob = \"08-19\"\n        Output: 3\n        Explanation: 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.\n        Example 2:\n        Input: arriveAlice = \"10-01\", leaveAlice = \"10-31\", arriveBob = \"11-01\", leaveBob = \"12-31\"\n        Output: 0\n        Explanation: There is no day when Alice and Bob are in Rome together, so we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2410,
-        "title": "Maximum Matching of Players With Trainers",
-        "question": "class Solution:\n    def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:\n        \"\"\"\n        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.\n        The 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.\n        Return the maximum number of matchings between players and trainers that satisfy these conditions.\n        Example 1:\n        Input: players = [4,7,9], trainers = [8,2,5,8]\n        Output: 2\n        Explanation:\n        One 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.\n        It can be proven that 2 is the maximum number of matchings that can be formed.\n        Example 2:\n        Input: players = [1,1,1], trainers = [10]\n        Output: 1\n        Explanation:\n        The trainer can be matched with any of the 3 players.\n        Each player can only be matched with one trainer, so the maximum answer is 1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2411,
-        "title": "Smallest Subarrays With Maximum Bitwise OR",
-        "question": "class Solution:\n    def smallestSubarrays(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        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.\n            In 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.\n        The bitwise OR of an array is the bitwise OR of all the numbers in it.\n        Return 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.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,0,2,1,3]\n        Output: [3,3,2,2,1]\n        Explanation:\n        The 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].\n        Therefore, we return [3,3,2,2,1]. \n        Example 2:\n        Input: nums = [1,2]\n        Output: [2,1]\n        Explanation:\n        Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2.\n        Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1.\n        Therefore, we return [2,1].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2412,
-        "title": "Minimum Money Required Before Transactions",
-        "question": "class Solution:\n    def minimumMoney(self, transactions: List[List[int]]) -> int:\n        \"\"\"\n        You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki].\n        The 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.\n        Return 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:\n        Input: transactions = [[2,1],[5,0],[4,2]]\n        Output: 10\n        Explanation:\n        Starting with money = 10, the transactions can be performed in any order.\n        It can be shown that starting with money < 10 will fail to complete all transactions in some order.\n        Example 2:\n        Input: transactions = [[3,0],[0,3]]\n        Output: 3\n        Explanation:\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.\n        Thus, starting with money = 3, the transactions can be performed in any order.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2418,
-        "title": "Sort the People",
-        "question": "class Solution:\n    def sortPeople(self, names: List[str], heights: List[int]) -> List[str]:\n        \"\"\"\n        You are given an array of strings names, and an array heights that consists of distinct positive integers. Both arrays are of length n.\n        For each index i, names[i] and heights[i] denote the name and height of the ith person.\n        Return names sorted in descending order by the people's heights.\n        Example 1:\n        Input: names = [\"Mary\",\"John\",\"Emma\"], heights = [180,165,170]\n        Output: [\"Mary\",\"Emma\",\"John\"]\n        Explanation: Mary is the tallest, followed by Emma and John.\n        Example 2:\n        Input: names = [\"Alice\",\"Bob\",\"Bob\"], heights = [155,185,150]\n        Output: [\"Bob\",\"Alice\",\"Bob\"]\n        Explanation: The first Bob is the tallest, followed by Alice and the second Bob.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2419,
-        "title": "Longest Subarray With Maximum Bitwise AND",
-        "question": "class Solution:\n    def longestSubarray(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given an integer array nums of size n.\n        Consider a non-empty subarray from nums that has the maximum possible bitwise AND.\n            In 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.\n        Return the length of the longest such subarray.\n        The bitwise AND of an array is the bitwise AND of all the numbers in it.\n        A subarray is a contiguous sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,2,3,3,2,2]\n        Output: 2\n        Explanation:\n        The maximum possible bitwise AND of a subarray is 3.\n        The longest subarray with that value is [3,3], so we return 2.\n        Example 2:\n        Input: nums = [1,2,3,4]\n        Output: 1\n        Explanation:\n        The maximum possible bitwise AND of a subarray is 4.\n        The longest subarray with that value is [4], so we return 1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2420,
-        "title": "Find All Good Indices",
-        "question": "class Solution:\n    def goodIndices(self, nums: List[int], k: int) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed integer array nums of size n and a positive integer k.\n        We call an index i in the range k <= i < n - k good if the following conditions are satisfied:\n            The k elements that are just before the index i are in non-increasing order.\n            The k elements that are just after the index i are in non-decreasing order.\n        Return an array of all good indices sorted in increasing order.\n        Example 1:\n        Input: nums = [2,1,1,1,3,4,1], k = 2\n        Output: [2,3]\n        Explanation: 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.\n        Note that the index 4 is not good because [4,1] is not non-decreasing.\n        Example 2:\n        Input: nums = [2,1,1,2], k = 2\n        Output: []\n        Explanation: There are no good indices in this array.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2421,
-        "title": "Number of Good Paths",
-        "question": "class Solution:\n    def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        You 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.\n        A good path is a simple path that satisfies the following conditions:\n            The starting node and the ending node have the same value.\n            All 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).\n        Return the number of distinct good paths.\n        Note 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:\n        Input: vals = [1,3,2,1,3], edges = [[0,1],[0,2],[2,3],[2,4]]\n        Output: 6\n        Explanation: There are 5 good paths consisting of a single node.\n        There 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.)\n        Note that 0 -> 2 -> 3 is not a good path because vals[2] > vals[0].\n        Example 2:\n        Input: vals = [1,1,2,2,3], edges = [[0,1],[1,2],[2,3],[2,4]]\n        Output: 7\n        Explanation: There are 5 good paths consisting of a single node.\n        There are 2 additional good paths: 0 -> 1 and 2 -> 3.\n        Example 3:\n        Input: vals = [1], edges = []\n        Output: 1\n        Explanation: The tree consists of only one node, so there is one good path.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2427,
-        "title": "Number of Common Factors",
-        "question": "class Solution:\n    def commonFactors(self, a: int, b: int) -> int:\n        \"\"\"\n        Given two positive integers a and b, return the number of common factors of a and b.\n        An integer x is a common factor of a and b if x divides both a and b.\n        Example 1:\n        Input: a = 12, b = 6\n        Output: 4\n        Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.\n        Example 2:\n        Input: a = 25, b = 30\n        Output: 2\n        Explanation: The common factors of 25 and 30 are 1, 5.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2428,
-        "title": "Maximum Sum of an Hourglass",
-        "question": "class Solution:\n    def maxSum(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        You are given an m x n integer matrix grid.\n        We define an hourglass as a part of the matrix with the following form:\n        Return the maximum sum of the elements of an hourglass.\n        Note that an hourglass cannot be rotated and must be entirely contained within the matrix.\n        Example 1:\n        Input: grid = [[6,2,1,3],[4,2,1,5],[9,2,8,7],[4,1,2,9]]\n        Output: 30\n        Explanation: The cells shown above represent the hourglass with the maximum sum: 6 + 2 + 1 + 2 + 9 + 2 + 8 = 30.\n        Example 2:\n        Input: grid = [[1,2,3],[4,5,6],[7,8,9]]\n        Output: 35\n        Explanation: There is only one hourglass in the matrix, with the sum: 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2429,
-        "title": "Minimize XOR",
-        "question": "class Solution:\n    def minimizeXor(self, num1: int, num2: int) -> int:\n        \"\"\"\n        Given two positive integers num1 and num2, find the positive integer x such that:\n            x has the same number of set bits as num2, and\n            The value x XOR num1 is minimal.\n        Note that XOR is the bitwise XOR operation.\n        Return the integer x. The test cases are generated such that x is uniquely determined.\n        The number of set bits of an integer is the number of 1's in its binary representation.\n        Example 1:\n        Input: num1 = 3, num2 = 5\n        Output: 3\n        Explanation:\n        The binary representations of num1 and num2 are 0011 and 0101, respectively.\n        The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.\n        Example 2:\n        Input: num1 = 1, num2 = 12\n        Output: 3\n        Explanation:\n        The binary representations of num1 and num2 are 0001 and 1100, respectively.\n        The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2430,
-        "title": "Maximum Deletions on a String",
-        "question": "class Solution:\n    def deleteString(self, s: str) -> int:\n        \"\"\"\n        You are given a string s consisting of only lowercase English letters. In one operation, you can:\n            Delete the entire string s, or\n            Delete 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.\n        For 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\".\n        Return the maximum number of operations needed to delete all of s.\n        Example 1:\n        Input: s = \"abcabcdabc\"\n        Output: 2\n        Explanation:\n        - Delete the first 3 letters (\"abc\") since the next 3 letters are equal. Now, s = \"abcdabc\".\n        - Delete all the letters.\n        We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.\n        Note that in the second operation we cannot delete \"abc\" again because the next occurrence of \"abc\" does not happen in the next 3 letters.\n        Example 2:\n        Input: s = \"aaabaab\"\n        Output: 4\n        Explanation:\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.\n        We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.\n        Example 3:\n        Input: s = \"aaaaa\"\n        Output: 5\n        Explanation: In each operation, we can delete the first letter of s.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2522,
-        "title": "Partition String Into Substrings With Values at Most K",
-        "question": "class Solution:\n    def minimumPartition(self, s: str, k: int) -> int:\n        \"\"\"\n        You are given a string s consisting of digits from 1 to 9 and an integer k.\n        A partition of a string s is called good if:\n            Each digit of s is part of exactly one substring.\n            The value of each substring is less than or equal to k.\n        Return the minimum number of substrings in a good partition of s. If no good partition of s exists, return -1.\n        Note that:\n            The value of a string is its result when interpreted as an integer. For example, the value of \"123\" is 123 and the value of \"1\" is 1.\n            A substring is a contiguous sequence of characters within a string.\n        Example 1:\n        Input: s = \"165462\", k = 60\n        Output: 4\n        Explanation: We can partition the string into substrings \"16\", \"54\", \"6\", and \"2\". Each substring has a value less than or equal to k = 60.\n        It can be shown that we cannot partition the string into less than 4 substrings.\n        Example 2:\n        Input: s = \"238182\", k = 5\n        Output: -1\n        Explanation: There is no good partition for this string.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2424,
-        "title": "Longest Uploaded Prefix",
-        "question": "class LUPrefix:\n    def __init__(self, n: int):\n    def upload(self, video: int) -> None:\n    def longest(self) -> int:\n        \"\"\"\n        You are given a stream of n videos, each represented by a distinct number from 1 to n that you need to \"upload\" to a server. You need to implement a data structure that calculates the length of the longest uploaded prefix at various points in the upload process.\n        We consider i to be an uploaded prefix if all videos in the range 1 to i (inclusive) have been uploaded to the server. The longest uploaded prefix is the maximum value of i that satisfies this definition.\n        Implement the LUPrefix class:\n            LUPrefix(int n) Initializes the object for a stream of n videos.\n            void upload(int video) Uploads video to the server.\n            int longest() Returns the length of the longest uploaded prefix defined above.\n        Example 1:\n        Input\n        [\"LUPrefix\", \"upload\", \"longest\", \"upload\", \"longest\", \"upload\", \"longest\"]\n        [[4], [3], [], [1], [], [2], []]\n        Output\n        [null, null, 0, null, 1, null, 3]\n        Explanation\n        LUPrefix server = new LUPrefix(4);   // Initialize a stream of 4 videos.\n        server.upload(3);                    // Upload video 3.\n        server.longest();                    // Since video 1 has not been uploaded yet, there is no prefix.\n                                             // So, we return 0.\n        server.upload(1);                    // Upload video 1.\n        server.longest();                    // The prefix [1] is the longest uploaded prefix, so we return 1.\n        server.upload(2);                    // Upload video 2.\n        server.longest();                    // The prefix [1,2,3] is the longest uploaded prefix, so we return 3.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2426,
-        "title": "Number of Pairs Satisfying Inequality",
-        "question": "class Solution:\n    def numberOfPairs(self, nums1: List[int], nums2: List[int], diff: int) -> int:\n        \"\"\"\n        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:\n            0 <= i < j <= n - 1 and\n            nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.\n        Return the number of pairs that satisfy the conditions.\n        Example 1:\n        Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1\n        Output: 3\n        Explanation:\n        There are 3 pairs that satisfy the conditions:\n        1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.\n        2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.\n        3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.\n        Therefore, we return 3.\n        Example 2:\n        Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1\n        Output: 0\n        Explanation:\n        Since there does not exist any pair that satisfies the conditions, we return 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2432,
-        "title": "The Employee That Worked on the Longest Task",
-        "question": "class Solution:\n    def hardestWorker(self, n: int, logs: List[List[int]]) -> int:\n        \"\"\"\n        There are n employees, each with a unique id from 0 to n - 1.\n        You are given a 2D integer array logs where logs[i] = [idi, leaveTimei] where:\n            idi is the id of the employee that worked on the ith task, and\n            leaveTimei is the time at which the employee finished the ith task. All the values leaveTimei are unique.\n        Note that the ith task starts the moment right after the (i - 1)th task ends, and the 0th task starts at time 0.\n        Return 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:\n        Input: n = 10, logs = [[0,3],[2,5],[0,9],[1,15]]\n        Output: 1\n        Explanation: \n        Task 0 started at 0 and ended at 3 with 3 units of times.\n        Task 1 started at 3 and ended at 5 with 2 units of times.\n        Task 2 started at 5 and ended at 9 with 4 units of times.\n        Task 3 started at 9 and ended at 15 with 6 units of times.\n        The 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.\n        Example 2:\n        Input: n = 26, logs = [[1,1],[3,7],[2,12],[7,17]]\n        Output: 3\n        Explanation: \n        Task 0 started at 0 and ended at 1 with 1 unit of times.\n        Task 1 started at 1 and ended at 7 with 6 units of times.\n        Task 2 started at 7 and ended at 12 with 5 units of times.\n        Task 3 started at 12 and ended at 17 with 5 units of times.\n        The tasks with the longest time is task 1. The employees that worked on it is 3, so we return 3.\n        Example 3:\n        Input: n = 2, logs = [[0,10],[1,20]]\n        Output: 0\n        Explanation: \n        Task 0 started at 0 and ended at 10 with 10 units of times.\n        Task 1 started at 10 and ended at 20 with 10 units of times.\n        The 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        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2433,
-        "title": "Find The Original Array of Prefix Xor",
-        "question": "class Solution:\n    def findArray(self, pref: List[int]) -> List[int]:\n        \"\"\"\n        You are given an integer array pref of size n. Find and return the array arr of size n that satisfies:\n            pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i].\n        Note that ^ denotes the bitwise-xor operation.\n        It can be proven that the answer is unique.\n        Example 1:\n        Input: pref = [5,2,0,3,1]\n        Output: [5,7,2,3,2]\n        Explanation: 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.\n        Example 2:\n        Input: pref = [13]\n        Output: [13]\n        Explanation: We have pref[0] = arr[0] = 13.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2434,
-        "title": "Using a Robot to Print the Lexicographically Smallest String",
-        "question": "class Solution:\n    def robotWithString(self, s: str) -> str:\n        \"\"\"\n        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:\n            Remove the first character of a string s and give it to the robot. The robot will append this character to the string t.\n            Remove the last character of a string t and give it to the robot. The robot will write this character on paper.\n        Return the lexicographically smallest string that can be written on the paper.\n        Example 1:\n        Input: s = \"zza\"\n        Output: \"azz\"\n        Explanation: Let p denote the written string.\n        Initially p=\"\", s=\"zza\", t=\"\".\n        Perform first operation three times p=\"\", s=\"\", t=\"zza\".\n        Perform second operation three times p=\"azz\", s=\"\", t=\"\".\n        Example 2:\n        Input: s = \"bac\"\n        Output: \"abc\"\n        Explanation: Let p denote the written string.\n        Perform first operation twice p=\"\", s=\"c\", t=\"ba\". \n        Perform second operation twice p=\"ab\", s=\"c\", t=\"\". \n        Perform first operation p=\"ab\", s=\"\", t=\"c\". \n        Perform second operation p=\"abc\", s=\"\", t=\"\".\n        Example 3:\n        Input: s = \"bdda\"\n        Output: \"addb\"\n        Explanation: Let p denote the written string.\n        Initially p=\"\", s=\"bdda\", t=\"\".\n        Perform first operation four times p=\"\", s=\"\", t=\"bdda\".\n        Perform second operation four times p=\"addb\", s=\"\", t=\"\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2435,
-        "title": "Paths in Matrix Whose Sum Is Divisible by K",
-        "question": "class Solution:\n    def numberOfPaths(self, grid: List[List[int]], k: int) -> int:\n        \"\"\"\n        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.\n        Return 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:\n        Input: grid = [[5,2,4],[3,0,5],[0,7,2]], k = 3\n        Output: 2\n        Explanation: There are two paths where the sum of the elements on the path is divisible by k.\n        The first path highlighted in red has a sum of 5 + 2 + 4 + 5 + 2 = 18 which is divisible by 3.\n        The second path highlighted in blue has a sum of 5 + 3 + 0 + 5 + 2 = 15 which is divisible by 3.\n        Example 2:\n        Input: grid = [[0,0]], k = 5\n        Output: 1\n        Explanation: The path highlighted in red has a sum of 0 + 0 = 0 which is divisible by 5.\n        Example 3:\n        Input: grid = [[7,3,4,9],[2,3,6,2],[2,3,7,0]], k = 1\n        Output: 10\n        Explanation: Every integer is divisible by 1 so the sum of the elements on every possible path is divisible by k.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2441,
-        "title": "Largest Positive Integer That Exists With Its Negative",
-        "question": "class Solution:\n    def findMaxK(self, nums: List[int]) -> int:\n        \"\"\"\n        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.\n        Return the positive integer k. If there is no such integer, return -1.\n        Example 1:\n        Input: nums = [-1,2,-3,3]\n        Output: 3\n        Explanation: 3 is the only valid k we can find in the array.\n        Example 2:\n        Input: nums = [-1,10,6,7,-7,1]\n        Output: 7\n        Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.\n        Example 3:\n        Input: nums = [-10,8,6,7,-2,-3]\n        Output: -1\n        Explanation: There is no a single valid k, we return -1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2442,
-        "title": "Count Number of Distinct Integers After Reverse Operations",
-        "question": "class Solution:\n    def countDistinctIntegers(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given an array nums consisting of positive integers.\n        You 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.\n        Return the number of distinct integers in the final array.\n        Example 1:\n        Input: nums = [1,13,10,12,31]\n        Output: 6\n        Explanation: After including the reverse of each number, the resulting array is [1,13,10,12,31,1,31,1,21,13].\n        The 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.\n        The number of distinct integers in this array is 6 (The numbers 1, 10, 12, 13, 21, and 31).\n        Example 2:\n        Input: nums = [2,2,2]\n        Output: 1\n        Explanation: After including the reverse of each number, the resulting array is [2,2,2,2,2,2].\n        The number of distinct integers in this array is 1 (The number 2).\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2407,
-        "title": "Longest Increasing Subsequence II",
-        "question": "class Solution:\n    def lengthOfLIS(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given an integer array nums and an integer k.\n        Find the longest subsequence of nums that meets the following requirements:\n            The subsequence is strictly increasing and\n            The difference between adjacent elements in the subsequence is at most k.\n        Return the length of the longest subsequence that meets the requirements.\n        A 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:\n        Input: nums = [4,2,1,4,3,4,5,8,15], k = 3\n        Output: 5\n        Explanation:\n        The longest subsequence that meets the requirements is [1,3,4,5,8].\n        The subsequence has a length of 5, so we return 5.\n        Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3.\n        Example 2:\n        Input: nums = [7,4,5,1,8,12,4,7], k = 5\n        Output: 4\n        Explanation:\n        The longest subsequence that meets the requirements is [4,5,8,12].\n        The subsequence has a length of 4, so we return 4.\n        Example 3:\n        Input: nums = [1,5], k = 1\n        Output: 1\n        Explanation:\n        The longest subsequence that meets the requirements is [1].\n        The subsequence has a length of 1, so we return 1.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2444,
-        "title": "Count Subarrays With Fixed Bounds",
-        "question": "class Solution:\n    def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:\n        \"\"\"\n        You are given an integer array nums and two integers minK and maxK.\n        A fixed-bound subarray of nums is a subarray that satisfies the following conditions:\n            The minimum value in the subarray is equal to minK.\n            The maximum value in the subarray is equal to maxK.\n        Return the number of fixed-bound subarrays.\n        A subarray is a contiguous part of an array.\n        Example 1:\n        Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5\n        Output: 2\n        Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].\n        Example 2:\n        Input: nums = [1,1,1,1], minK = 1, maxK = 1\n        Output: 10\n        Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2437,
-        "title": "Number of Valid Clock Times",
-        "question": "class Solution:\n    def countTime(self, time: str) -> int:\n        \"\"\"\n        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\".\n        In the string time, the digits represented by the ? symbol are unknown, and must be replaced with a digit from 0 to 9.\n        Return 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:\n        Input: time = \"?5:00\"\n        Output: 2\n        Explanation: 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.\n        Example 2:\n        Input: time = \"0?:0?\"\n        Output: 100\n        Explanation: Each ? can be replaced by any digit from 0 to 9, so we have 100 total choices.\n        Example 3:\n        Input: time = \"??:??\"\n        Output: 1440\n        Explanation: There are 24 possible choices for the hours, and 60 possible choices for the minutes. In total, we have 24 * 60 = 1440 choices.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2438,
-        "title": "Range Product Queries of Powers",
-        "question": "class Solution:\n    def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n        \"\"\"\n        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.\n        You 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.\n        Return 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:\n        Input: n = 15, queries = [[0,1],[2,2],[0,3]]\n        Output: [2,4,64]\n        Explanation:\n        For n = 15, powers = [1,2,4,8]. It can be shown that powers cannot be a smaller size.\n        Answer to 1st query: powers[0] * powers[1] = 1 * 2 = 2.\n        Answer to 2nd query: powers[2] = 4.\n        Answer to 3rd query: powers[0] * powers[1] * powers[2] * powers[3] = 1 * 2 * 4 * 8 = 64.\n        Each answer modulo 109 + 7 yields the same answer, so [2,4,64] is returned.\n        Example 2:\n        Input: n = 2, queries = [[0,0]]\n        Output: [2]\n        Explanation:\n        For n = 2, powers = [2].\n        The answer to the only query is powers[0] = 2. The answer modulo 109 + 7 is the same, so [2] is returned.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2439,
-        "title": "Minimize Maximum of Array",
-        "question": "class Solution:\n    def minimizeArrayValue(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed array nums comprising of n non-negative integers.\n        In one operation, you must:\n            Choose an integer i such that 1 <= i < n and nums[i] > 0.\n            Decrease nums[i] by 1.\n            Increase nums[i - 1] by 1.\n        Return the minimum possible value of the maximum integer of nums after performing any number of operations.\n        Example 1:\n        Input: nums = [3,7,1,6]\n        Output: 5\n        Explanation:\n        One set of optimal operations is as follows:\n        1. Choose i = 1, and nums becomes [4,6,1,6].\n        2. Choose i = 3, and nums becomes [4,6,2,5].\n        3. Choose i = 1, and nums becomes [5,5,2,5].\n        The maximum integer of nums is 5. It can be shown that the maximum number cannot be less than 5.\n        Therefore, we return 5.\n        Example 2:\n        Input: nums = [10,1]\n        Output: 10\n        Explanation:\n        It is optimal to leave nums as is, and since 10 is the maximum value, we return 10.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2440,
-        "title": "Create Components With Same Value",
-        "question": "class Solution:\n    def componentValue(self, nums: List[int], edges: List[List[int]]) -> int:\n        \"\"\"\n        There is an undirected tree with n nodes labeled from 0 to n - 1.\n        You 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.\n        You 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.\n        Return the maximum number of edges you can delete, such that every connected component in the tree has the same value.\n        Example 1:\n        Input: nums = [6,2,2,2,6], edges = [[0,1],[1,2],[1,3],[3,4]] \n        Output: 2 \n        Explanation: 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.\n        Example 2:\n        Input: nums = [2], edges = []\n        Output: 0\n        Explanation: There are no edges to be deleted.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2423,
-        "title": "Remove Letter To Equalize Frequency",
-        "question": "class Solution:\n    def equalFrequency(self, word: str) -> bool:\n        \"\"\"\n        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.\n        Return true if it is possible to remove one letter so that the frequency of all letters in word are equal, and false otherwise.\n        Note:\n            The frequency of a letter x is the number of times it occurs in the string.\n            You must remove exactly one letter and cannot chose to do nothing.\n        Example 1:\n        Input: word = \"abcc\"\n        Output: true\n        Explanation: Select index 3 and delete it: word becomes \"abc\" and each character has a frequency of 1.\n        Example 2:\n        Input: word = \"aazz\"\n        Output: false\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2425,
-        "title": "Bitwise XOR of All Pairings",
-        "question": "class Solution:\n    def xorAllNums(self, nums1: List[int], nums2: List[int]) -> int:\n        \"\"\"\n        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).\n        Return the bitwise XOR of all integers in nums3.\n        Example 1:\n        Input: nums1 = [2,1,3], nums2 = [10,2,5,0]\n        Output: 13\n        Explanation:\n        A possible nums3 array is [8,0,7,2,11,3,4,1,9,1,6,3].\n        The bitwise XOR of all these numbers is 13, so we return 13.\n        Example 2:\n        Input: nums1 = [1,2], nums2 = [3,4]\n        Output: 0\n        Explanation:\n        All possible pairs of bitwise XORs are nums1[0] ^ nums2[0], nums1[0] ^ nums2[1], nums1[1] ^ nums2[0],\n        and nums1[1] ^ nums2[1].\n        Thus, one possible nums3 array is [2,5,1,6].\n        2 ^ 5 ^ 1 ^ 6 = 0, so we return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2446,
-        "title": "Determine if Two Events Have Conflict",
-        "question": "class Solution:\n    def haveConflict(self, event1: List[str], event2: List[str]) -> bool:\n        \"\"\"\n        You are given two arrays of strings that represent two inclusive events that happened on the same day, event1 and event2, where:\n            event1 = [startTime1, endTime1] and\n            event2 = [startTime2, endTime2].\n        Event times are valid 24 hours format in the form of HH:MM.\n        A conflict happens when two events have some non-empty intersection (i.e., some moment is common to both events).\n        Return true if there is a conflict between two events. Otherwise, return false.\n        Example 1:\n        Input: event1 = [\"01:15\",\"02:00\"], event2 = [\"02:00\",\"03:00\"]\n        Output: true\n        Explanation: The two events intersect at time 2:00.\n        Example 2:\n        Input: event1 = [\"01:00\",\"02:00\"], event2 = [\"01:20\",\"03:00\"]\n        Output: true\n        Explanation: The two events intersect starting from 01:20 to 02:00.\n        Example 3:\n        Input: event1 = [\"10:00\",\"11:00\"], event2 = [\"14:00\",\"15:00\"]\n        Output: false\n        Explanation: The two events do not intersect.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2448,
-        "title": "Minimum Cost to Make Array Equal",
-        "question": "class Solution:\n    def minCost(self, nums: List[int], cost: List[int]) -> int:\n        \"\"\"\n        You are given two 0-indexed arrays nums and cost consisting each of n positive integers.\n        You can do the following operation any number of times:\n            Increase or decrease any element of the array nums by 1.\n        The cost of doing one operation on the ith element is cost[i].\n        Return the minimum total cost such that all the elements of the array nums become equal.\n        Example 1:\n        Input: nums = [1,3,5,2], cost = [2,3,1,14]\n        Output: 8\n        Explanation: 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.\n        The total cost is 2 + 3 + 3 = 8.\n        It can be shown that we cannot make the array equal with a smaller cost.\n        Example 2:\n        Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3]\n        Output: 0\n        Explanation: All the elements are already equal, so no operations are needed.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2449,
-        "title": "Minimum Number of Operations to Make Arrays Similar",
-        "question": "class Solution:\n    def makeSimilar(self, nums: List[int], target: List[int]) -> int:\n        \"\"\"\n        You are given two positive integer arrays nums and target, of the same length.\n        In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:\n            set nums[i] = nums[i] + 2 and\n            set nums[j] = nums[j] - 2.\n        Two arrays are considered to be similar if the frequency of each element is the same.\n        Return 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:\n        Input: nums = [8,12,6], target = [2,14,10]\n        Output: 2\n        Explanation: 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].\n        It can be shown that 2 is the minimum number of operations needed.\n        Example 2:\n        Input: nums = [1,2,5], target = [4,1,3]\n        Output: 1\n        Explanation: We can make nums similar to target in one operation:\n        - Choose i = 1 and j = 2, nums = [1,4,3].\n        Example 3:\n        Input: nums = [1,1,1,1,1], target = [1,1,1,1,1]\n        Output: 0\n        Explanation: The array nums is already similiar to target.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2443,
-        "title": "Sum of Number and Its Reverse",
-        "question": "class Solution:\n    def sumOfNumberAndReverse(self, num: int) -> bool:\n        \"\"\"\n        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:\n        Input: num = 443\n        Output: true\n        Explanation: 172 + 271 = 443 so we return true.\n        Example 2:\n        Input: num = 63\n        Output: false\n        Explanation: 63 cannot be expressed as the sum of a non-negative integer and its reverse so we return false.\n        Example 3:\n        Input: num = 181\n        Output: true\n        Explanation: 140 + 041 = 181 so we return true. Note that when a number is reversed, there may be leading zeros.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2455,
-        "title": "Average Value of Even Numbers That Are Divisible by Three",
-        "question": "class Solution:\n    def averageValue(self, nums: List[int]) -> int:\n        \"\"\"\n        Given an integer array nums of positive integers, return the average value of all even integers that are divisible by 3.\n        Note 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:\n        Input: nums = [1,3,6,10,12,15]\n        Output: 9\n        Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.\n        Example 2:\n        Input: nums = [1,2,4,7,10]\n        Output: 0\n        Explanation: There is no single number that satisfies the requirement, so return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2456,
-        "title": "Most Popular Video Creator",
-        "question": "class Solution:\n    def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]:\n        \"\"\"\n        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.\n        The 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.\n            If multiple creators have the highest popularity, find all of them.\n            If multiple videos have the highest view count for a creator, find the lexicographically smallest id.\n        Return 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:\n        Input: creators = [\"alice\",\"bob\",\"alice\",\"chris\"], ids = [\"one\",\"two\",\"three\",\"four\"], views = [5,10,5,4]\n        Output: [[\"alice\",\"one\"],[\"bob\",\"two\"]]\n        Explanation:\n        The popularity of alice is 5 + 5 = 10.\n        The popularity of bob is 10.\n        The popularity of chris is 4.\n        alice and bob are the most popular creators.\n        For bob, the video with the highest view count is \"two\".\n        For 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.\n        Example 2:\n        Input: creators = [\"alice\",\"alice\",\"alice\"], ids = [\"a\",\"b\",\"c\"], views = [1,2,2]\n        Output: [[\"alice\",\"b\"]]\n        Explanation:\n        The videos with id \"b\" and \"c\" have the highest view count.\n        Since \"b\" is lexicographically smaller than \"c\", it is included in the answer.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2457,
-        "title": "Minimum Addition to Make Integer Beautiful",
-        "question": "class Solution:\n    def makeIntegerBeautiful(self, n: int, target: int) -> int:\n        \"\"\"\n        You are given two positive integers n and target.\n        An integer is considered beautiful if the sum of its digits is less than or equal to target.\n        Return 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:\n        Input: n = 16, target = 6\n        Output: 4\n        Explanation: 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.\n        Example 2:\n        Input: n = 467, target = 6\n        Output: 33\n        Explanation: 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.\n        Example 3:\n        Input: n = 1, target = 1\n        Output: 0\n        Explanation: Initially n is 1 and its digit sum is 1, which is already smaller than or equal to target.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2458,
-        "title": "Height of Binary Tree After Subtree Removal Queries",
-        "question": "class Solution:\n    def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:\n        \"\"\"\n        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.\n        You have to perform m independent queries on the tree where in the ith query you do the following:\n            Remove 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.\n        Return an array answer of size m where answer[i] is the height of the tree after performing the ith query.\n        Note:\n            The queries are independent, so the tree returns to its initial state after each query.\n            The 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:\n        Input: root = [1,3,4,2,null,6,5,null,null,null,null,null,7], queries = [4]\n        Output: [2]\n        Explanation: The diagram above shows the tree after removing the subtree rooted at node with value 4.\n        The height of the tree is 2 (The path 1 -> 3 -> 2).\n        Example 2:\n        Input: root = [5,8,9,2,1,3,7,4,6], queries = [3,2,4,8]\n        Output: [3,2,3,2]\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2447,
-        "title": "Number of Subarrays With GCD Equal to K",
-        "question": "class Solution:\n    def subarrayGCD(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        The greatest common divisor of an array is the largest integer that evenly divides all the array elements.\n        Example 1:\n        Input: nums = [9,3,1,2,6,3], k = 3\n        Output: 4\n        Explanation: 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]\n        Example 2:\n        Input: nums = [4], k = 7\n        Output: 0\n        Explanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2451,
-        "title": "Odd String Difference",
-        "question": "class Solution:\n    def oddString(self, words: List[str]) -> str:\n        \"\"\"\n        You are given an array of equal-length strings words. Assume that the length of each string is n.\n        Each 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.\n            For example, for the string \"acb\", the difference integer array is [2 - 0, 1 - 2] = [2, -1].\n        All the strings in words have the same difference integer array, except one. You should find that string.\n        Return the string in words that has different difference integer array.\n        Example 1:\n        Input: words = [\"adc\",\"wzy\",\"abc\"]\n        Output: \"abc\"\n        Explanation: \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]. \n        The odd array out is [1, 1], so we return the corresponding string, \"abc\".\n        Example 2:\n        Input: words = [\"aaa\",\"bob\",\"ccc\",\"ddd\"]\n        Output: \"bob\"\n        Explanation: All the integer arrays are [0, 0] except for \"bob\", which corresponds to [13, -13].\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2453,
-        "title": "Destroy Sequential Targets",
-        "question": "class Solution:\n    def destroyTargets(self, nums: List[int], space: int) -> int:\n        \"\"\"\n        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.\n        You 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.\n        Return the minimum value of nums[i] you can seed the machine with to destroy the maximum number of targets.\n        Example 1:\n        Input: nums = [3,7,8,1,1,5], space = 2\n        Output: 1\n        Explanation: If we seed the machine with nums[3], then we destroy all targets equal to 1,3,5,7,9,... \n        In this case, we would destroy 5 total targets (all except for nums[2]). \n        It is impossible to destroy more than 5 targets, so we return nums[3].\n        Example 2:\n        Input: nums = [1,3,5,2,4,6], space = 2\n        Output: 1\n        Explanation: Seeding the machine with nums[0], or nums[3] destroys 3 targets. \n        It is not possible to destroy more than 3 targets.\n        Since nums[0] is the minimal integer that can destroy 3 targets, we return 1.\n        Example 3:\n        Input: nums = [6,2,5], space = 100\n        Output: 2\n        Explanation: Whatever initial seed we select, we can only destroy 1 target. The minimal seed is nums[1].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2454,
-        "title": "Next Greater Element IV",
-        "question": "class Solution:\n    def secondGreaterElement(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        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.\n        The second greater integer of nums[i] is nums[j] such that:\n            j > i\n            nums[j] > nums[i]\n            There exists exactly one index k such that nums[k] > nums[i] and i < k < j.\n        If there is no such nums[j], the second greater integer is considered to be -1.\n            For 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.\n        Return an integer array answer, where answer[i] is the second greater integer of nums[i].\n        Example 1:\n        Input: nums = [2,4,0,9,6]\n        Output: [9,6,6,-1,-1]\n        Explanation:\n        0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.\n        1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.\n        2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.\n        3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.\n        4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.\n        Thus, we return [9,6,6,-1,-1].\n        Example 2:\n        Input: nums = [3,3]\n        Output: [-1,-1]\n        Explanation:\n        We return [-1,-1] since neither integer has any integer greater than it.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2452,
-        "title": "Words Within Two Edits of Dictionary",
-        "question": "class Solution:\n    def twoEditWords(self, queries: List[str], dictionary: List[str]) -> List[str]:\n        \"\"\"\n        You are given two string arrays, queries and dictionary. All words in each array comprise of lowercase English letters and have the same length.\n        In 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.\n        Return 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:\n        Input: queries = [\"word\",\"note\",\"ants\",\"wood\"], dictionary = [\"wood\",\"joke\",\"moat\"]\n        Output: [\"word\",\"note\",\"wood\"]\n        Explanation:\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.\n        Thus, we return [\"word\",\"note\",\"wood\"].\n        Example 2:\n        Input: queries = [\"yes\"], dictionary = [\"not\"]\n        Output: []\n        Explanation:\n        Applying any two edits to \"yes\" cannot make it equal to \"not\". Thus, we return an empty array.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2460,
-        "title": "Apply Operations to an Array",
-        "question": "class Solution:\n    def applyOperations(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed array nums of size n consisting of non-negative integers.\n        You 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:\n            If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation.\n        After performing all the operations, shift all the 0's to the end of the array.\n            For 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].\n        Return the resulting array.\n        Note that the operations are applied sequentially, not all at once.\n        Example 1:\n        Input: nums = [1,2,2,1,1,0]\n        Output: [1,4,2,0,0,0]\n        Explanation: 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].\n        After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].\n        Example 2:\n        Input: nums = [0,1]\n        Output: [1,0]\n        Explanation: No operation can be applied, we just shift the 0 to the end.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2461,
-        "title": "Maximum Sum of Distinct Subarrays With Length K",
-        "question": "class Solution:\n    def maximumSubarraySum(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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:\n            The length of the subarray is k, and\n            All the elements of the subarray are distinct.\n        Return the maximum subarray sum of all the subarrays that meet the conditions. If no subarray meets the conditions, return 0.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,5,4,2,9,9,9], k = 3\n        Output: 15\n        Explanation: 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.\n        We return 15 because it is the maximum subarray sum of all the subarrays that meet the conditions\n        Example 2:\n        Input: nums = [4,4,4], k = 3\n        Output: 0\n        Explanation: The subarrays of nums with length 3 are:\n        - [4,4,4] which does not meet the requirements because the element 4 is repeated.\n        We return 0 because no subarrays meet the conditions.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2462,
-        "title": "Total Cost to Hire K Workers",
-        "question": "class Solution:\n    def totalCost(self, costs: List[int], k: int, candidates: int) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array costs where costs[i] is the cost of hiring the ith worker.\n        You are also given two integers k and candidates. We want to hire exactly k workers according to the following rules:\n            You will run k sessions and hire exactly one worker in each session.\n            In each hiring session, choose the worker with the lowest cost from either the first candidates workers or the last candidates workers. Break the tie by the smallest index.\n                For example, if costs = [3,2,7,7,1,2] and candidates = 2, then in the first hiring session, we will choose the 4th worker because they have the lowest cost [3,2,7,7,1,2].\n                In the second hiring session, we will choose 1st worker because they have the same lowest cost as 4th worker but they have the smallest index [3,2,7,7,2]. Please note that the indexing may be changed in the process.\n            If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index.\n            A worker can only be chosen once.\n        Return the total cost to hire exactly k workers.\n        Example 1:\n        Input: costs = [17,12,10,2,7,2,11,20,8], k = 3, candidates = 4\n        Output: 11\n        Explanation: 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.\n        The total hiring cost is 11.\n        Example 2:\n        Input: costs = [1,2,4,1], k = 3, candidates = 3\n        Output: 4\n        Explanation: 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.\n        The total hiring cost is 4.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2463,
-        "title": "Minimum Total Distance Traveled",
-        "question": "class Solution:\n    def minimumTotalDistance(self, robot: List[int], factory: List[List[int]]) -> int:\n        \"\"\"\n        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.\n        The 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.\n        All 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.\n        At 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.\n        Return the minimum total distance traveled by all the robots. The test cases are generated such that all the robots can be repaired.\n        Note that\n            All robots move at the same speed.\n            If two robots move in the same direction, they will never collide.\n            If two robots move in opposite directions and they meet at some point, they do not collide. They cross each other.\n            If a robot passes by a factory that reached its limits, it crosses it as if it does not exist.\n            If the robot moved from a position x to a position y, the distance it moved is |y - x|.\n        Example 1:\n        Input: robot = [0,4,6], factory = [[2,2],[6,2]]\n        Output: 4\n        Explanation: 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.\n        The limit of the first factory is 2, and it fixed 2 robots.\n        The limit of the second factory is 2, and it fixed 1 robot.\n        The total distance is |2 - 0| + |2 - 4| + |6 - 6| = 4. It can be shown that we cannot achieve a better total distance than 4.\n        Example 2:\n        Input: robot = [1,-1], factory = [[-2,1],[2,1]]\n        Output: 2\n        Explanation: 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.\n        The limit of the first factory is 1, and it fixed 1 robot.\n        The limit of the second factory is 1, and it fixed 1 robot.\n        The total distance is |2 - 1| + |(-2) - (-1)| = 2. It can be shown that we cannot achieve a better total distance than 2.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2469,
-        "title": "Convert the Temperature",
-        "question": "class Solution:\n    def convertTemperature(self, celsius: float) -> List[float]:\n        \"\"\"\n        You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius.\n        You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit].\n        Return the array ans. Answers within 10-5 of the actual answer will be accepted.\n        Note that:\n            Kelvin = Celsius + 273.15\n            Fahrenheit = Celsius * 1.80 + 32.00\n        Example 1:\n        Input: celsius = 36.50\n        Output: [309.65000,97.70000]\n        Explanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70.\n        Example 2:\n        Input: celsius = 122.11\n        Output: [395.26000,251.79800]\n        Explanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2470,
-        "title": "Number of Subarrays With LCM Equal to K",
-        "question": "class Solution:\n    def subarrayLCM(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        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.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        The least common multiple of an array is the smallest positive integer that is divisible by all the array elements.\n        Example 1:\n        Input: nums = [3,6,2,7,1], k = 6\n        Output: 4\n        Explanation: 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]\n        Example 2:\n        Input: nums = [3], k = 2\n        Output: 0\n        Explanation: There are no subarrays of nums where 2 is the least common multiple of all the subarray's elements.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2471,
-        "title": "Minimum Number of Operations to Sort a Binary Tree by Level",
-        "question": "class Solution:\n    def minimumOperations(self, root: Optional[TreeNode]) -> int:\n        \"\"\"\n        You are given the root of a binary tree with unique values.\n        In one operation, you can choose any two nodes at the same level and swap their values.\n        Return the minimum number of operations needed to make the values at each level sorted in a strictly increasing order.\n        The level of a node is the number of edges along the path between it and the root node.\n        Example 1:\n        Input: root = [1,4,3,7,6,8,5,null,null,null,null,9,null,10]\n        Output: 3\n        Explanation:\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].\n        We used 3 operations so return 3.\n        It can be proven that 3 is the minimum number of operations needed.\n        Example 2:\n        Input: root = [1,3,2,7,6,5,4]\n        Output: 3\n        Explanation:\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].\n        We used 3 operations so return 3.\n        It can be proven that 3 is the minimum number of operations needed.\n        Example 3:\n        Input: root = [1,2,3,4,5,6]\n        Output: 0\n        Explanation: Each level is already sorted in increasing order so return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2472,
-        "title": "Maximum Number of Non-overlapping Palindrome Substrings",
-        "question": "class Solution:\n    def maxPalindromes(self, s: str, k: int) -> int:\n        \"\"\"\n        You are given a string s and a positive integer k.\n        Select a set of non-overlapping substrings from the string s that satisfy the following conditions:\n            The length of each substring is at least k.\n            Each substring is a palindrome.\n        Return the maximum number of substrings in an optimal selection.\n        A substring is a contiguous sequence of characters within a string.\n        Example 1:\n        Input: s = \"abaccdbbd\", k = 3\n        Output: 2\n        Explanation: We can select the substrings underlined in s = \"abaccdbbd\". Both \"aba\" and \"dbbd\" are palindromes and have a length of at least k = 3.\n        It can be shown that we cannot find a selection with more than two valid substrings.\n        Example 2:\n        Input: s = \"adbcda\", k = 2\n        Output: 0\n        Explanation: There is no palindrome substring of length at least 2 in the string.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2465,
-        "title": "Number of Distinct Averages",
-        "question": "class Solution:\n    def distinctAverages(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums of even length.\n        As long as nums is not empty, you must repetitively:\n            Find the minimum number in nums and remove it.\n            Find the maximum number in nums and remove it.\n            Calculate the average of the two removed numbers.\n        The average of two numbers a and b is (a + b) / 2.\n            For example, the average of 2 and 3 is (2 + 3) / 2 = 2.5.\n        Return the number of distinct averages calculated using the above process.\n        Note that when there is a tie for a minimum or maximum number, any can be removed.\n        Example 1:\n        Input: nums = [4,1,4,0,3,5]\n        Output: 2\n        Explanation:\n        1. Remove 0 and 5, and the average is (0 + 5) / 2 = 2.5. Now, nums = [4,1,4,3].\n        2. Remove 1 and 4. The average is (1 + 4) / 2 = 2.5, and nums = [4,3].\n        3. Remove 3 and 4, and the average is (3 + 4) / 2 = 3.5.\n        Since there are 2 distinct numbers among 2.5, 2.5, and 3.5, we return 2.\n        Example 2:\n        Input: nums = [1,100]\n        Output: 1\n        Explanation:\n        There is only one average to be calculated after removing 1 and 100, so we return 1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2466,
-        "title": "Count Ways To Build Good Strings",
-        "question": "class Solution:\n    def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:\n        \"\"\"\n        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:\n            Append the character '0' zero times.\n            Append the character '1' one times.\n        This can be performed any number of times.\n        A good string is a string constructed by the above process having a length between low and high (inclusive).\n        Return 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:\n        Input: low = 3, high = 3, zero = 1, one = 1\n        Output: 8\n        Explanation: \n        One possible valid good string is \"011\". \n        It can be constructed as follows: \"\" -> \"0\" -> \"01\" -> \"011\". \n        All binary strings from \"000\" to \"111\" are good strings in this example.\n        Example 2:\n        Input: low = 2, high = 3, zero = 1, one = 2\n        Output: 5\n        Explanation: The good strings are \"00\", \"11\", \"000\", \"110\", and \"011\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2468,
-        "title": "Split Message Based on Limit",
-        "question": "class Solution:\n    def splitMessage(self, message: str, limit: int) -> List[str]:\n        \"\"\"\n        You are given a string, message, and a positive integer, limit.\n        You 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.\n        The 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.\n        Return 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:\n        Input: message = \"this is really a very awesome message\", limit = 9\n        Output: [\"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>\"]\n        Explanation:\n        The first 9 parts take 3 characters each from the beginning of message.\n        The next 5 parts take 2 characters each to finish splitting message. \n        In this example, each part, including the last, has length 9. \n        It can be shown it is not possible to split message into less than 14 parts.\n        Example 2:\n        Input: message = \"short message\", limit = 15\n        Output: [\"short mess<1/2>\",\"age<2/2>\"]\n        Explanation:\n        Under 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        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2467,
-        "title": "Most Profitable Path in a Tree",
-        "question": "class Solution:\n    def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:\n        \"\"\"\n        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.\n        At every node i, there is a gate. You are also given an array of even integers amount, where amount[i] represents:\n            the price needed to open the gate at node i, if amount[i] is negative, or,\n            the cash reward obtained on opening the gate at node i, otherwise.\n        The game goes on as follows:\n            Initially, Alice is at node 0 and Bob is at node bob.\n            At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node 0.\n            For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that:\n                If the gate is already open, no price will be required, nor will there be any cash reward.\n                If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is c, then both Alice and Bob pay c / 2 each. Similarly, if the reward at the gate is c, both of them receive c / 2 each.\n            If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node 0, he stops moving. Note that these events are independent of each other.\n        Return the maximum net income Alice can have if she travels towards the optimal leaf node.\n        Example 1:\n        Input: edges = [[0,1],[1,2],[1,3],[3,4]], bob = 3, amount = [-2,4,2,-4,6]\n        Output: 6\n        Explanation: \n        The 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.\n        Now, neither Alice nor Bob can make any further moves, and the game ends.\n        It is not possible for Alice to get a higher net income.\n        Example 2:\n        Input: edges = [[0,1]], bob = 1, amount = [-7280,2350]\n        Output: -7280\n        Explanation: \n        Alice follows the path 0->1 whereas Bob follows the path 1->0.\n        Thus, Alice opens the gate at node 0 only. Hence, her net income is -7280. \n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2475,
-        "title": "Number of Unequal Triplets in Array",
-        "question": "class Solution:\n    def unequalTriplets(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed array of positive integers nums. Find the number of triplets (i, j, k) that meet the following conditions:\n            0 <= i < j < k < nums.length\n            nums[i], nums[j], and nums[k] are pairwise distinct.\n                In other words, nums[i] != nums[j], nums[i] != nums[k], and nums[j] != nums[k].\n        Return the number of triplets that meet the conditions.\n        Example 1:\n        Input: nums = [4,4,2,4,3]\n        Output: 3\n        Explanation: 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\n        Since there are 3 triplets, we return 3.\n        Note that (2, 0, 4) is not a valid triplet because 2 > 0.\n        Example 2:\n        Input: nums = [1,1,1,1,1]\n        Output: 0\n        Explanation: No triplets meet the conditions so we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2476,
-        "title": "Closest Nodes Queries in a Binary Search Tree",
-        "question": "class Solution:\n    def closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]:\n        \"\"\"\n        You are given the root of a binary search tree and an array queries of size n consisting of positive integers.\n        Find a 2D array answer of size n where answer[i] = [mini, maxi]:\n            mini 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.\n            maxi 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.\n        Return the array answer.\n        Example 1:\n        Input: root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]\n        Output: [[2,2],[4,6],[15,-1]]\n        Explanation: 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].\n        Example 2:\n        Input: root = [4,null,9], queries = [3]\n        Output: [[-1,4]]\n        Explanation: 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        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2477,
-        "title": "Minimum Fuel Cost to Report to the Capital",
-        "question": "class Solution:\n    def minimumFuelCost(self, roads: List[List[int]], seats: int) -> int:\n        \"\"\"\n        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.\n        There is a meeting for the representatives of each city. The meeting is in the capital city.\n        There is a car in each city. You are given an integer seats that indicates the number of seats in each car.\n        A 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.\n        Return the minimum number of liters of fuel to reach the capital city.\n        Example 1:\n        Input: roads = [[0,1],[0,2],[0,3]], seats = 5\n        Output: 3\n        Explanation: \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.\n        It costs 3 liters of fuel at minimum. \n        It can be proven that 3 is the minimum number of liters of fuel needed.\n        Example 2:\n        Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2\n        Output: 7\n        Explanation: \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.\n        It costs 7 liters of fuel at minimum. \n        It can be proven that 7 is the minimum number of liters of fuel needed.\n        Example 3:\n        Input: roads = [], seats = 1\n        Output: 0\n        Explanation: No representatives need to travel to the capital city.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2478,
-        "title": "Number of Beautiful Partitions",
-        "question": "class Solution:\n    def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:\n        \"\"\"\n        You are given a string s that consists of the digits '1' to '9' and two integers k and minLength.\n        A partition of s is called beautiful if:\n            s is partitioned into k non-intersecting substrings.\n            Each substring has a length of at least minLength.\n            Each 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.\n        Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 109 + 7.\n        A substring is a contiguous sequence of characters within a string.\n        Example 1:\n        Input: s = \"23542185131\", k = 3, minLength = 2\n        Output: 3\n        Explanation: There exists three ways to create a beautiful partition:\n        \"2354 | 218 | 5131\"\n        \"2354 | 21851 | 31\"\n        \"2354218 | 51 | 31\"\n        Example 2:\n        Input: s = \"23542185131\", k = 3, minLength = 3\n        Output: 1\n        Explanation: There exists one way to create a beautiful partition: \"2354 | 218 | 5131\".\n        Example 3:\n        Input: s = \"3312958\", k = 3, minLength = 1\n        Output: 1\n        Explanation: There exists one way to create a beautiful partition: \"331 | 29 | 58\".\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2485,
-        "title": "Find the Pivot Integer",
-        "question": "class Solution:\n    def pivotInteger(self, n: int) -> int:\n        \"\"\"\n        Given a positive integer n, find the pivot integer x such that:\n            The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.\n        Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.\n        Example 1:\n        Input: n = 8\n        Output: 6\n        Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.\n        Example 2:\n        Input: n = 1\n        Output: 1\n        Explanation: 1 is the pivot integer since: 1 = 1.\n        Example 3:\n        Input: n = 4\n        Output: -1\n        Explanation: It can be proved that no such integer exist.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2486,
-        "title": "Append Characters to String to Make Subsequence",
-        "question": "class Solution:\n    def appendCharacters(self, s: str, t: str) -> int:\n        \"\"\"\n        You are given two strings s and t consisting of only lowercase English letters.\n        Return the minimum number of characters that need to be appended to the end of s so that t becomes a subsequence of s.\n        A 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:\n        Input: s = \"coaching\", t = \"coding\"\n        Output: 4\n        Explanation: Append the characters \"ding\" to the end of s so that s = \"coachingding\".\n        Now, t is a subsequence of s (\"coachingding\").\n        It can be shown that appending any 3 characters to the end of s will never make t a subsequence.\n        Example 2:\n        Input: s = \"abcde\", t = \"a\"\n        Output: 0\n        Explanation: t is already a subsequence of s (\"abcde\").\n        Example 3:\n        Input: s = \"z\", t = \"abcde\"\n        Output: 5\n        Explanation: Append the characters \"abcde\" to the end of s so that s = \"zabcde\".\n        Now, t is a subsequence of s (\"zabcde\").\n        It can be shown that appending any 4 characters to the end of s will never make t a subsequence.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2487,
-        "title": "Remove Nodes From Linked List",
-        "question": "class Solution:\n    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:\n        \"\"\"\n        You are given the head of a linked list.\n        Remove every node which has a node with a strictly greater value anywhere to the right side of it.\n        Return the head of the modified linked list.\n        Example 1:\n        Input: head = [5,2,13,3,8]\n        Output: [13,8]\n        Explanation: The nodes that should be removed are 5, 2 and 3.\n        - Node 13 is to the right of node 5.\n        - Node 13 is to the right of node 2.\n        - Node 8 is to the right of node 3.\n        Example 2:\n        Input: head = [1,1,1,1]\n        Output: [1,1,1,1]\n        Explanation: Every node has value 1, so no nodes are removed.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2488,
-        "title": "Count Subarrays With Median K",
-        "question": "class Solution:\n    def countSubarrays(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given an array nums of size n consisting of distinct integers from 1 to n and a positive integer k.\n        Return the number of non-empty subarrays in nums that have a median equal to k.\n        Note:\n            The median of an array is the middle element after sorting the array in ascending order. If the array is of even length, the median is the left middle element.\n                For example, the median of [2,3,1,4] is 2, and the median of [8,4,3,5,1] is 4.\n            A subarray is a contiguous part of an array.\n        Example 1:\n        Input: nums = [3,2,1,4,5], k = 4\n        Output: 3\n        Explanation: The subarrays that have a median equal to 4 are: [4], [4,5] and [1,4,5].\n        Example 2:\n        Input: nums = [2,3,1], k = 3\n        Output: 1\n        Explanation: [3] is the only subarray that has a median equal to 3.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2481,
-        "title": "Minimum Cuts to Divide a Circle",
-        "question": "class Solution:\n    def numberOfCuts(self, n: int) -> int:\n        \"\"\"\n        A valid cut in a circle can be:\n            A cut that is represented by a straight line that touches two points on the edge of the circle and passes through its center, or\n            A cut that is represented by a straight line that touches one point on the edge of the circle and its center.\n        Some valid and invalid cuts are shown in the figures below.\n        Given the integer n, return the minimum number of cuts needed to divide a circle into n equal slices.\n        Example 1:\n        Input: n = 4\n        Output: 2\n        Explanation: \n        The above figure shows how cutting the circle twice through the middle divides it into 4 equal slices.\n        Example 2:\n        Input: n = 3\n        Output: 3\n        Explanation:\n        At least 3 cuts are needed to divide the circle into 3 equal slices. \n        It can be shown that less than 3 cuts cannot result in 3 slices of equal size and shape.\n        Also note that the first cut will not divide the circle into distinct parts.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2483,
-        "title": "Minimum Penalty for a Shop",
-        "question": "class Solution:\n    def bestClosingTime(self, customers: str) -> int:\n        \"\"\"\n        You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':\n            if the ith character is 'Y', it means that customers come at the ith hour\n            whereas 'N' indicates that no customers come at the ith hour.\n        If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:\n            For every hour when the shop is open and no customers come, the penalty increases by 1.\n            For every hour when the shop is closed and customers come, the penalty increases by 1.\n        Return the earliest hour at which the shop must be closed to incur a minimum penalty.\n        Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.\n        Example 1:\n        Input: customers = \"YYNY\"\n        Output: 2\n        Explanation: \n        - Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.\n        - Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.\n        - Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.\n        - Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.\n        - Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.\n        Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.\n        Example 2:\n        Input: customers = \"NNNNN\"\n        Output: 0\n        Explanation: It is best to close the shop at the 0th hour as no customers arrive.\n        Example 3:\n        Input: customers = \"YYYY\"\n        Output: 4\n        Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2484,
-        "title": "Count Palindromic Subsequences",
-        "question": "class Solution:\n    def countPalindromes(self, s: str) -> int:\n        \"\"\"\n        Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 109 + 7.\n        Note:\n            A string is palindromic if it reads the same forward and backward.\n            A 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:\n        Input: s = \"103301\"\n        Output: 2\n        Explanation: \n        There are 6 possible subsequences of length 5: \"10330\",\"10331\",\"10301\",\"10301\",\"13301\",\"03301\". \n        Two of them (both equal to \"10301\") are palindromic.\n        Example 2:\n        Input: s = \"0000000\"\n        Output: 21\n        Explanation: All 21 subsequences are \"00000\", which is palindromic.\n        Example 3:\n        Input: s = \"9999900000\"\n        Output: 2\n        Explanation: The only two palindromic subsequences are \"99999\" and \"00000\".\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2490,
-        "title": "Circular Sentence",
-        "question": "class Solution:\n    def isCircularSentence(self, sentence: str) -> bool:\n        \"\"\"\n        A sentence is a list of words that are separated by a single space with no leading or trailing spaces.\n            For example, \"Hello World\", \"HELLO\", \"hello world hello world\" are all sentences.\n        Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters are considered different.\n        A sentence is circular if:\n            The last character of a word is equal to the first character of the next word.\n            The last character of the last word is equal to the first character of the first word.\n        For example, \"leetcode exercises sound delightful\", \"eetcode\", \"leetcode eats soul\" are all circular sentences. However, \"Leetcode is cool\", \"happy Leetcode\", \"Leetcode\" and \"I like Leetcode\" are not circular sentences.\n        Given a string sentence, return true if it is circular. Otherwise, return false.\n        Example 1:\n        Input: sentence = \"leetcode exercises sound delightful\"\n        Output: true\n        Explanation: The words in sentence are [\"leetcode\", \"exercises\", \"sound\", \"delightful\"].\n        - leetcode's last character is equal to exercises's first character.\n        - exercises's last character is equal to sound's first character.\n        - sound's last character is equal to delightful's first character.\n        - delightful's last character is equal to leetcode's first character.\n        The sentence is circular.\n        Example 2:\n        Input: sentence = \"eetcode\"\n        Output: true\n        Explanation: The words in sentence are [\"eetcode\"].\n        - eetcode's last character is equal to eetcode's first character.\n        The sentence is circular.\n        Example 3:\n        Input: sentence = \"Leetcode is cool\"\n        Output: false\n        Explanation: The words in sentence are [\"Leetcode\", \"is\", \"cool\"].\n        - Leetcode's last character is not equal to is's first character.\n        The sentence is not circular.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2491,
-        "title": "Divide Players Into Teams of Equal Skill",
-        "question": "class Solution:\n    def dividePlayers(self, skill: List[int]) -> int:\n        \"\"\"\n        You are given a positive integer array skill of even length n where skill[i] denotes the skill of the ith player. Divide the players into n / 2 teams of size 2 such that the total skill of each team is equal.\n        The chemistry of a team is equal to the product of the skills of the players on that team.\n        Return the sum of the chemistry of all the teams, or return -1 if there is no way to divide the players into teams such that the total skill of each team is equal.\n        Example 1:\n        Input: skill = [3,2,5,1,3,4]\n        Output: 22\n        Explanation: \n        Divide the players into the following teams: (1, 5), (2, 4), (3, 3), where each team has a total skill of 6.\n        The sum of the chemistry of all the teams is: 1 * 5 + 2 * 4 + 3 * 3 = 5 + 8 + 9 = 22.\n        Example 2:\n        Input: skill = [3,4]\n        Output: 12\n        Explanation: \n        The two players form a team with a total skill of 7.\n        The chemistry of the team is 3 * 4 = 12.\n        Example 3:\n        Input: skill = [1,1,2,3]\n        Output: -1\n        Explanation: \n        There is no way to divide the players into teams such that the total skill of each team is equal.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2492,
-        "title": "Minimum Score of a Path Between Two Cities",
-        "question": "class Solution:\n    def minScore(self, n: int, roads: List[List[int]]) -> int:\n        \"\"\"\n        You are given a positive integer n representing n cities numbered from 1 to n. You are also given a 2D array roads where roads[i] = [ai, bi, distancei] indicates that there is a bidirectional road between cities ai and bi with a distance equal to distancei. The cities graph is not necessarily connected.\n        The score of a path between two cities is defined as the minimum distance of a road in this path.\n        Return the minimum possible score of a path between cities 1 and n.\n        Note:\n            A path is a sequence of roads between two cities.\n            It is allowed for a path to contain the same road multiple times, and you can visit cities 1 and n multiple times along the path.\n            The test cases are generated such that there is at least one path between 1 and n.\n        Example 1:\n        Input: n = 4, roads = [[1,2,9],[2,3,6],[2,4,5],[1,4,7]]\n        Output: 5\n        Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 4. The score of this path is min(9,5) = 5.\n        It can be shown that no other path has less score.\n        Example 2:\n        Input: n = 4, roads = [[1,2,2],[1,3,4],[3,4,7]]\n        Output: 2\n        Explanation: The path from city 1 to 4 with the minimum score is: 1 -> 2 -> 1 -> 3 -> 4. The score of this path is min(2,2,4,7) = 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2493,
-        "title": "Divide Nodes Into the Maximum Number of Groups",
-        "question": "class Solution:\n    def magnificentSets(self, n: int, edges: List[List[int]]) -> int:\n        \"\"\"\n        You are given a positive integer n representing the number of nodes in an undirected graph. The nodes are labeled from 1 to n.\n        You are also given a 2D integer array edges, where edges[i] = [ai, bi] indicates that there is a bidirectional edge between nodes ai and bi. Notice that the given graph may be disconnected.\n        Divide the nodes of the graph into m groups (1-indexed) such that:\n            Each node in the graph belongs to exactly one group.\n            For every pair of nodes in the graph that are connected by an edge [ai, bi], if ai belongs to the group with index x, and bi belongs to the group with index y, then |y - x| = 1.\n        Return the maximum number of groups (i.e., maximum m) into which you can divide the nodes. Return -1 if it is impossible to group the nodes with the given conditions.\n        Example 1:\n        Input: n = 6, edges = [[1,2],[1,4],[1,5],[2,6],[2,3],[4,6]]\n        Output: 4\n        Explanation: As shown in the image we:\n        - Add node 5 to the first group.\n        - Add node 1 to the second group.\n        - Add nodes 2 and 4 to the third group.\n        - Add nodes 3 and 6 to the fourth group.\n        We can see that every edge is satisfied.\n        It can be shown that that if we create a fifth group and move any node from the third or fourth group to it, at least on of the edges will not be satisfied.\n        Example 2:\n        Input: n = 3, edges = [[1,2],[2,3],[3,1]]\n        Output: -1\n        Explanation: If we add node 1 to the first group, node 2 to the second group, and node 3 to the third group to satisfy the first two edges, we can see that the third edge will not be satisfied.\n        It can be shown that no grouping is possible.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2500,
-        "title": "Delete Greatest Value in Each Row",
-        "question": "class Solution:\n    def deleteGreatestValue(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        You are given an m x n matrix grid consisting of positive integers.\n        Perform the following operation until grid becomes empty:\n            Delete the element with the greatest value from each row. If multiple such elements exist, delete any of them.\n            Add the maximum of deleted elements to the answer.\n        Note that the number of columns decreases by one after each operation.\n        Return the answer after performing the operations described above.\n        Example 1:\n        Input: grid = [[1,2,4],[3,3,1]]\n        Output: 8\n        Explanation: The diagram above shows the removed values in each step.\n        - In the first operation, we remove 4 from the first row and 3 from the second row (notice that, there are two cells with value 3 and we can remove any of them). We add 4 to the answer.\n        - In the second operation, we remove 2 from the first row and 3 from the second row. We add 3 to the answer.\n        - In the third operation, we remove 1 from the first row and 1 from the second row. We add 1 to the answer.\n        The final answer = 4 + 3 + 1 = 8.\n        Example 2:\n        Input: grid = [[10]]\n        Output: 10\n        Explanation: The diagram above shows the removed values in each step.\n        - In the first operation, we remove 10 from the first row. We add 10 to the answer.\n        The final answer = 10.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2501,
-        "title": "Longest Square Streak in an Array",
-        "question": "class Solution:\n    def longestSquareStreak(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given an integer array nums. A subsequence of nums is called a square streak if:\n            The length of the subsequence is at least 2, and\n            after sorting the subsequence, each element (except the first element) is the square of the previous number.\n        Return the length of the longest square streak in nums, or return -1 if there is no square streak.\n        A 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:\n        Input: nums = [4,3,6,16,8,2]\n        Output: 3\n        Explanation: Choose the subsequence [4,16,2]. After sorting it, it becomes [2,4,16].\n        - 4 = 2 * 2.\n        - 16 = 4 * 4.\n        Therefore, [4,16,2] is a square streak.\n        It can be shown that every subsequence of length 4 is not a square streak.\n        Example 2:\n        Input: nums = [2,3,5,6,7]\n        Output: -1\n        Explanation: There is no square streak in nums so return -1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2502,
-        "title": "Design Memory Allocator",
-        "question": "class Allocator:\n    def __init__(self, n: int):\n    def allocate(self, size: int, mID: int) -> int:\n    def free(self, mID: int) -> int:\n        \"\"\"\n        You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free.\n        You have a memory allocator with the following functionalities:\n            Allocate a block of size consecutive free memory units and assign it the id mID.\n            Free all memory units with the given id mID.\n        Note that:\n            Multiple blocks can be allocated to the same mID.\n            You should free all the memory units with mID, even if they were allocated in different blocks.\n        Implement the Allocator class:\n            Allocator(int n) Initializes an Allocator object with a memory array of size n.\n            int allocate(int size, int mID) Find the leftmost block of size consecutive free memory units and allocate it with the id mID. Return the block's first index. If such a block does not exist, return -1.\n            int free(int mID) Free all memory units with the id mID. Return the number of memory units you have freed.\n        Example 1:\n        Input\n        [\"Allocator\", \"allocate\", \"allocate\", \"allocate\", \"free\", \"allocate\", \"allocate\", \"allocate\", \"free\", \"allocate\", \"free\"]\n        [[10], [1, 1], [1, 2], [1, 3], [2], [3, 4], [1, 1], [1, 1], [1], [10, 2], [7]]\n        Output\n        [null, 0, 1, 2, 1, 3, 1, 6, 3, -1, 0]\n        Explanation\n        Allocator loc = new Allocator(10); // Initialize a memory array of size 10. All memory units are initially free.\n        loc.allocate(1, 1); // The leftmost block's first index is 0. The memory array becomes [1,_,_,_,_,_,_,_,_,_]. We return 0.\n        loc.allocate(1, 2); // The leftmost block's first index is 1. The memory array becomes [1,2,_,_,_,_,_,_,_,_]. We return 1.\n        loc.allocate(1, 3); // The leftmost block's first index is 2. The memory array becomes [1,2,3,_,_,_,_,_,_,_]. We return 2.\n        loc.free(2); // Free all memory units with mID 2. The memory array becomes [1,_, 3,_,_,_,_,_,_,_]. We return 1 since there is only 1 unit with mID 2.\n        loc.allocate(3, 4); // The leftmost block's first index is 3. The memory array becomes [1,_,3,4,4,4,_,_,_,_]. We return 3.\n        loc.allocate(1, 1); // The leftmost block's first index is 1. The memory array becomes [1,1,3,4,4,4,_,_,_,_]. We return 1.\n        loc.allocate(1, 1); // The leftmost block's first index is 6. The memory array becomes [1,1,3,4,4,4,1,_,_,_]. We return 6.\n        loc.free(1); // Free all memory units with mID 1. The memory array becomes [_,_,3,4,4,4,_,_,_,_]. We return 3 since there are 3 units with mID 1.\n        loc.allocate(10, 2); // We can not find any free block with 10 consecutive free memory units, so we return -1.\n        loc.free(7); // Free all memory units with mID 7. The memory array remains the same since there is no memory unit with mID 7. We return 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2503,
-        "title": "Maximum Number of Points From Grid Queries",
-        "question": "class Solution:\n    def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:\n        \"\"\"\n        You are given an m x n integer matrix grid and an array queries of size k.\n        Find an array answer of size k such that for each integer queries[i] you start in the top left cell of the matrix and repeat the following process:\n            If queries[i] is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all 4 directions: up, down, left, and right.\n            Otherwise, you do not get any points, and you end this process.\n        After the process, answer[i] is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times.\n        Return the resulting array answer.\n        Example 1:\n        Input: grid = [[1,2,3],[2,5,7],[3,5,1]], queries = [5,6,2]\n        Output: [5,8,1]\n        Explanation: The diagrams above show which cells we visit to get points for each query.\n        Example 2:\n        Input: grid = [[5,2,1],[1,1,2]], queries = [3]\n        Output: [0]\n        Explanation: We can not get any points because the value of the top left cell is already greater than or equal to 3.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2496,
-        "title": "Maximum Value of a String in an Array",
-        "question": "class Solution:\n    def maximumValue(self, strs: List[str]) -> int:\n        \"\"\"\n        The value of an alphanumeric string can be defined as:\n            The numeric representation of the string in base 10, if it comprises of digits only.\n            The length of the string, otherwise.\n        Given an array strs of alphanumeric strings, return the maximum value of any string in strs.\n        Example 1:\n        Input: strs = [\"alic3\",\"bob\",\"3\",\"4\",\"00000\"]\n        Output: 5\n        Explanation: \n        - \"alic3\" consists of both letters and digits, so its value is its length, i.e. 5.\n        - \"bob\" consists only of letters, so its value is also its length, i.e. 3.\n        - \"3\" consists only of digits, so its value is its numeric equivalent, i.e. 3.\n        - \"4\" also consists only of digits, so its value is 4.\n        - \"00000\" consists only of digits, so its value is 0.\n        Hence, the maximum value is 5, of \"alic3\".\n        Example 2:\n        Input: strs = [\"1\",\"01\",\"001\",\"0001\"]\n        Output: 1\n        Explanation: \n        Each string in the array has value 1. Hence, we return 1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2497,
-        "title": "Maximum Star Sum of a Graph",
-        "question": "class Solution:\n    def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int:\n        \"\"\"\n        There is an undirected graph consisting of n nodes numbered from 0 to n - 1. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of the ith node.\n        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.\n        A star graph is a subgraph of the given graph having a center node containing 0 or more neighbors. In other words, it is a subset of edges of the given graph such that there exists a common node for all edges.\n        The image below shows star graphs with 3 and 4 neighbors respectively, centered at the blue node.\n        The star sum is the sum of the values of all the nodes present in the star graph.\n        Given an integer k, return the maximum star sum of a star graph containing at most k edges.\n        Example 1:\n        Input: vals = [1,2,3,4,10,-10,-20], edges = [[0,1],[1,2],[1,3],[3,4],[3,5],[3,6]], k = 2\n        Output: 16\n        Explanation: The above diagram represents the input graph.\n        The star graph with the maximum star sum is denoted by blue. It is centered at 3 and includes its neighbors 1 and 4.\n        It can be shown it is not possible to get a star graph with a sum greater than 16.\n        Example 2:\n        Input: vals = [-5], edges = [], k = 0\n        Output: -5\n        Explanation: There is only one possible star graph, which is node 0 itself.\n        Hence, we return -5.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2498,
-        "title": "Frog Jump II",
-        "question": "class Solution:\n    def maxJump(self, stones: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array stones sorted in strictly increasing order representing the positions of stones in a river.\n        A frog, initially on the first stone, wants to travel to the last stone and then return to the first stone. However, it can jump to any stone at most once.\n        The length of a jump is the absolute difference between the position of the stone the frog is currently on and the position of the stone to which the frog jumps.\n            More formally, if the frog is at stones[i] and is jumping to stones[j], the length of the jump is |stones[i] - stones[j]|.\n        The cost of a path is the maximum length of a jump among all jumps in the path.\n        Return the minimum cost of a path for the frog.\n        Example 1:\n        Input: stones = [0,2,5,6,7]\n        Output: 5\n        Explanation: The above figure represents one of the optimal paths the frog can take.\n        The cost of this path is 5, which is the maximum length of a jump.\n        Since it is not possible to achieve a cost of less than 5, we return it.\n        Example 2:\n        Input: stones = [0,3,9]\n        Output: 9\n        Explanation: \n        The frog can jump directly to the last stone and come back to the first stone. \n        In this case, the length of each jump will be 9. The cost for the path will be max(9, 9) = 9.\n        It can be shown that this is the minimum achievable cost.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2499,
-        "title": "Minimum Total Cost to Make Arrays Unequal",
-        "question": "class Solution:\n    def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int:\n        \"\"\"\n        You are given two 0-indexed integer arrays nums1 and nums2, of equal length n.\n        In one operation, you can swap the values of any two indices of nums1. The cost of this operation is the sum of the indices.\n        Find the minimum total cost of performing the given operation any number of times such that nums1[i] != nums2[i] for all 0 <= i <= n - 1 after performing all the operations.\n        Return the minimum total cost such that nums1 and nums2 satisfy the above condition. In case it is not possible, return -1.\n        Example 1:\n        Input: nums1 = [1,2,3,4,5], nums2 = [1,2,3,4,5]\n        Output: 10\n        Explanation: \n        One of the ways we can perform the operations is:\n        - Swap values at indices 0 and 3, incurring cost = 0 + 3 = 3. Now, nums1 = [4,2,3,1,5]\n        - Swap values at indices 1 and 2, incurring cost = 1 + 2 = 3. Now, nums1 = [4,3,2,1,5].\n        - Swap values at indices 0 and 4, incurring cost = 0 + 4 = 4. Now, nums1 =[5,3,2,1,4].\n        We can see that for each index i, nums1[i] != nums2[i]. The cost required here is 10.\n        Note that there are other ways to swap values, but it can be proven that it is not possible to obtain a cost less than 10.\n        Example 2:\n        Input: nums1 = [2,2,2,1,3], nums2 = [1,2,2,3,3]\n        Output: 10\n        Explanation: \n        One of the ways we can perform the operations is:\n        - Swap values at indices 2 and 3, incurring cost = 2 + 3 = 5. Now, nums1 = [2,2,1,2,3].\n        - Swap values at indices 1 and 4, incurring cost = 1 + 4 = 5. Now, nums1 = [2,3,1,2,2].\n        The total cost needed here is 10, which is the minimum possible.\n        Example 3:\n        Input: nums1 = [1,2,2], nums2 = [1,2,2]\n        Output: -1\n        Explanation: \n        It can be shown that it is not possible to satisfy the given conditions irrespective of the number of operations we perform.\n        Hence, we return -1.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2506,
-        "title": "Count Pairs Of Similar Strings",
-        "question": "class Solution:\n    def similarPairs(self, words: List[str]) -> int:\n        \"\"\"\n        You are given a 0-indexed string array words.\n        Two strings are similar if they consist of the same characters.\n            For example, \"abca\" and \"cba\" are similar since both consist of characters 'a', 'b', and 'c'.\n            However, \"abacba\" and \"bcfd\" are not similar since they do not consist of the same characters.\n        Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings words[i] and words[j] are similar.\n        Example 1:\n        Input: words = [\"aba\",\"aabb\",\"abcd\",\"bac\",\"aabc\"]\n        Output: 2\n        Explanation: There are 2 pairs that satisfy the conditions:\n        - i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'. \n        - i = 3 and j = 4 : both words[3] and words[4] only consist of characters 'a', 'b', and 'c'. \n        Example 2:\n        Input: words = [\"aabb\",\"ab\",\"ba\"]\n        Output: 3\n        Explanation: There are 3 pairs that satisfy the conditions:\n        - i = 0 and j = 1 : both words[0] and words[1] only consist of characters 'a' and 'b'. \n        - i = 0 and j = 2 : both words[0] and words[2] only consist of characters 'a' and 'b'.\n        - i = 1 and j = 2 : both words[1] and words[2] only consist of characters 'a' and 'b'.\n        Example 3:\n        Input: words = [\"nba\",\"cba\",\"dba\"]\n        Output: 0\n        Explanation: Since there does not exist any pair that satisfies the conditions, we return 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2507,
-        "title": "Smallest Value After Replacing With Sum of Prime Factors",
-        "question": "class Solution:\n    def smallestValue(self, n: int) -> int:\n        \"\"\"\n        You are given a positive integer n.\n        Continuously replace n with the sum of its prime factors.\n            Note that if a prime factor divides n multiple times, it should be included in the sum as many times as it divides n.\n        Return the smallest value n will take on.\n        Example 1:\n        Input: n = 15\n        Output: 5\n        Explanation: Initially, n = 15.\n        15 = 3 * 5, so replace n with 3 + 5 = 8.\n        8 = 2 * 2 * 2, so replace n with 2 + 2 + 2 = 6.\n        6 = 2 * 3, so replace n with 2 + 3 = 5.\n        5 is the smallest value n will take on.\n        Example 2:\n        Input: n = 3\n        Output: 3\n        Explanation: Initially, n = 3.\n        3 is the smallest value n will take on.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2508,
-        "title": "Add Edges to Make Degrees of All Nodes Even",
-        "question": "class Solution:\n    def isPossible(self, n: int, edges: List[List[int]]) -> bool:\n        \"\"\"\n        There is an undirected graph consisting of n nodes numbered from 1 to n. You are given the integer n and a 2D array edges where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi. The graph can be disconnected.\n        You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops.\n        Return true if it is possible to make the degree of each node in the graph even, otherwise return false.\n        The degree of a node is the number of edges connected to it.\n        Example 1:\n        Input: n = 5, edges = [[1,2],[2,3],[3,4],[4,2],[1,4],[2,5]]\n        Output: true\n        Explanation: The above diagram shows a valid way of adding an edge.\n        Every node in the resulting graph is connected to an even number of edges.\n        Example 2:\n        Input: n = 4, edges = [[1,2],[3,4]]\n        Output: true\n        Explanation: The above diagram shows a valid way of adding two edges.\n        Example 3:\n        Input: n = 4, edges = [[1,2],[1,3],[1,4]]\n        Output: false\n        Explanation: It is not possible to obtain a valid graph with adding at most 2 edges.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2509,
-        "title": "Cycle Length Queries in a Tree",
-        "question": "class Solution:\n    def cycleLengthQueries(self, n: int, queries: List[List[int]]) -> List[int]:\n        \"\"\"\n        You are given an integer n. There is a complete binary tree with 2n - 1 nodes. The root of that tree is the node with the value 1, and every node with a value val in the range [1, 2n - 1 - 1] has two children where:\n            The left node has the value 2 * val, and\n            The right node has the value 2 * val + 1.\n        You are also given a 2D integer array queries of length m, where queries[i] = [ai, bi]. For each query, solve the following problem:\n            Add an edge between the nodes with values ai and bi.\n            Find the length of the cycle in the graph.\n            Remove the added edge between nodes with values ai and bi.\n        Note that:\n            A cycle is a path that starts and ends at the same node, and each edge in the path is visited only once.\n            The length of a cycle is the number of edges visited in the cycle.\n            There could be multiple edges between two nodes in the tree after adding the edge of the query.\n        Return an array answer of length m where answer[i] is the answer to the ith query.\n        Example 1:\n        Input: n = 3, queries = [[5,3],[4,7],[2,3]]\n        Output: [4,5,3]\n        Explanation: The diagrams above show the tree of 23 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.\n        - After adding the edge between nodes 3 and 5, the graph contains a cycle of nodes [5,2,1,3]. Thus answer to the first query is 4. We delete the added edge and process the next query.\n        - After adding the edge between nodes 4 and 7, the graph contains a cycle of nodes [4,2,1,3,7]. Thus answer to the second query is 5. We delete the added edge and process the next query.\n        - After adding the edge between nodes 2 and 3, the graph contains a cycle of nodes [2,1,3]. Thus answer to the third query is 3. We delete the added edge.\n        Example 2:\n        Input: n = 2, queries = [[1,2]]\n        Output: [2]\n        Explanation: The diagram above shows the tree of 22 - 1 nodes. Nodes colored in red describe the nodes in the cycle after adding the edge.\n        - After adding the edge between nodes 1 and 2, the graph contains a cycle of nodes [2,1]. Thus answer for the first query is 2. We delete the added edge.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2515,
-        "title": "Shortest Distance to Target String in a Circular Array",
-        "question": "class Solution:\n    def closetTarget(self, words: List[str], target: str, startIndex: int) -> int:\n        \"\"\"\n        You are given a 0-indexed circular string array words and a string target. A circular array means that the array's end connects to the array's beginning.\n            Formally, the next element of words[i] is words[(i + 1) % n] and the previous element of words[i] is words[(i - 1 + n) % n], where n is the length of words.\n        Starting from startIndex, you can move to either the next word or the previous word with 1 step at a time.\n        Return the shortest distance needed to reach the string target. If the string target does not exist in words, return -1.\n        Example 1:\n        Input: words = [\"hello\",\"i\",\"am\",\"leetcode\",\"hello\"], target = \"hello\", startIndex = 1\n        Output: 1\n        Explanation: We start from index 1 and can reach \"hello\" by\n        - moving 3 units to the right to reach index 4.\n        - moving 2 units to the left to reach index 4.\n        - moving 4 units to the right to reach index 0.\n        - moving 1 unit to the left to reach index 0.\n        The shortest distance to reach \"hello\" is 1.\n        Example 2:\n        Input: words = [\"a\",\"b\",\"leetcode\"], target = \"leetcode\", startIndex = 0\n        Output: 1\n        Explanation: We start from index 0 and can reach \"leetcode\" by\n        - moving 2 units to the right to reach index 3.\n        - moving 1 unit to the left to reach index 3.\n        The shortest distance to reach \"leetcode\" is 1.\n        Example 3:\n        Input: words = [\"i\",\"eat\",\"leetcode\"], target = \"ate\", startIndex = 0\n        Output: -1\n        Explanation: Since \"ate\" does not exist in words, we return -1.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2516,
-        "title": "Take K of Each Character From Left and Right",
-        "question": "class Solution:\n    def takeCharacters(self, s: str, k: int) -> int:\n        \"\"\"\n        You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s.\n        Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character.\n        Example 1:\n        Input: s = \"aabaaaacaabc\", k = 2\n        Output: 8\n        Explanation: \n        Take three characters from the left of s. You now have two 'a' characters, and one 'b' character.\n        Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters.\n        A total of 3 + 5 = 8 minutes is needed.\n        It can be proven that 8 is the minimum number of minutes needed.\n        Example 2:\n        Input: s = \"a\", k = 1\n        Output: -1\n        Explanation: It is not possible to take one 'b' or 'c' so return -1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2517,
-        "title": "Maximum Tastiness of Candy Basket",
-        "question": "class Solution:\n    def maximumTastiness(self, price: List[int], k: int) -> int:\n        \"\"\"\n        You are given an array of positive integers price where price[i] denotes the price of the ith candy and a positive integer k.\n        The store sells baskets of k distinct candies. The tastiness of a candy basket is the smallest absolute difference of the prices of any two candies in the basket.\n        Return the maximum tastiness of a candy basket.\n        Example 1:\n        Input: price = [13,5,1,8,21,2], k = 3\n        Output: 8\n        Explanation: Choose the candies with the prices [13,5,21].\n        The tastiness of the candy basket is: min(|13 - 5|, |13 - 21|, |5 - 21|) = min(8, 8, 16) = 8.\n        It can be proven that 8 is the maximum tastiness that can be achieved.\n        Example 2:\n        Input: price = [1,3,1], k = 2\n        Output: 2\n        Explanation: Choose the candies with the prices [1,3].\n        The tastiness of the candy basket is: min(|1 - 3|) = min(2) = 2.\n        It can be proven that 2 is the maximum tastiness that can be achieved.\n        Example 3:\n        Input: price = [7,7,7,7], k = 2\n        Output: 0\n        Explanation: Choosing any two distinct candies from the candies we have will result in a tastiness of 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2518,
-        "title": "Number of Great Partitions",
-        "question": "class Solution:\n    def countPartitions(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given an array nums consisting of positive integers and an integer k.\n        Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k.\n        Return the number of distinct great partitions. Since the answer may be too large, return it modulo 109 + 7.\n        Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.\n        Example 1:\n        Input: nums = [1,2,3,4], k = 4\n        Output: 6\n        Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]).\n        Example 2:\n        Input: nums = [3,3,3], k = 4\n        Output: 0\n        Explanation: There are no great partitions for this array.\n        Example 3:\n        Input: nums = [6,6], k = 2\n        Output: 2\n        Explanation: We can either put nums[0] in the first partition or in the second partition.\n        The great partitions will be ([6], [6]) and ([6], [6]).\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2511,
-        "title": "Maximum Enemy Forts That Can Be Captured",
-        "question": "class Solution:\n    def captureForts(self, forts: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array forts of length n representing the positions of several forts. forts[i] can be -1, 0, or 1 where:\n            -1 represents there is no fort at the ith position.\n            0 indicates there is an enemy fort at the ith position.\n            1 indicates the fort at the ith the position is under your command.\n        Now you have decided to move your army from one of your forts at position i to an empty position j such that:\n            0 <= i, j <= n - 1\n            The army travels over enemy forts only. Formally, for all k where min(i,j) < k < max(i,j), forts[k] == 0.\n        While moving the army, all the enemy forts that come in the way are captured.\n        Return the maximum number of enemy forts that can be captured. In case it is impossible to move your army, or you do not have any fort under your command, return 0.\n        Example 1:\n        Input: forts = [1,0,0,-1,0,0,0,0,1]\n        Output: 4\n        Explanation:\n        - Moving the army from position 0 to position 3 captures 2 enemy forts, at 1 and 2.\n        - Moving the army from position 8 to position 3 captures 4 enemy forts.\n        Since 4 is the maximum number of enemy forts that can be captured, we return 4.\n        Example 2:\n        Input: forts = [0,0,1,-1]\n        Output: 0\n        Explanation: Since no enemy fort can be captured, 0 is returned.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2512,
-        "title": "Reward Top K Students",
-        "question": "class Solution:\n    def topStudents(self, positive_feedback: List[str], negative_feedback: List[str], report: List[str], student_id: List[int], k: int) -> List[int]:\n        \"\"\"\n        You are given two string arrays positive_feedback and negative_feedback, containing the words denoting positive and negative feedback, respectively. Note that no word is both positive and negative.\n        Initially every student has 0 points. Each positive word in a feedback report increases the points of a student by 3, whereas each negative word decreases the points by 1.\n        You are given n feedback reports, represented by a 0-indexed string array report and a 0-indexed integer array student_id, where student_id[i] represents the ID of the student who has received the feedback report report[i]. The ID of each student is unique.\n        Given an integer k, return the top k students after ranking them in non-increasing order by their points. In case more than one student has the same points, the one with the lower ID ranks higher.\n        Example 1:\n        Input: positive_feedback = [\"smart\",\"brilliant\",\"studious\"], negative_feedback = [\"not\"], report = [\"this student is studious\",\"the student is smart\"], student_id = [1,2], k = 2\n        Output: [1,2]\n        Explanation: \n        Both the students have 1 positive feedback and 3 points but since student 1 has a lower ID he ranks higher.\n        Example 2:\n        Input: positive_feedback = [\"smart\",\"brilliant\",\"studious\"], negative_feedback = [\"not\"], report = [\"this student is not studious\",\"the student is smart\"], student_id = [1,2], k = 2\n        Output: [2,1]\n        Explanation: \n        - The student with ID 1 has 1 positive feedback and 1 negative feedback, so he has 3-1=2 points. \n        - The student with ID 2 has 1 positive feedback, so he has 3 points. \n        Since student 2 has more points, [2,1] is returned.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2541,
-        "title": "Minimum Operations to Make Array Equal II",
-        "question": "class Solution:\n    def minOperations(self, nums1: List[int], nums2: List[int], k: int) -> int:\n        \"\"\"\n        You are given two integer arrays nums1 and nums2 of equal length n and an integer k. You can perform the following operation on nums1:\n            Choose two indexes i and j and increment nums1[i] by k and decrement nums1[j] by k. In other words, nums1[i] = nums1[i] + k and nums1[j] = nums1[j] - k.\n        nums1 is said to be equal to nums2 if for all indices i such that 0 <= i < n, nums1[i] == nums2[i].\n        Return the minimum number of operations required to make nums1 equal to nums2. If it is impossible to make them equal, return -1.\n        Example 1:\n        Input: nums1 = [4,3,1,4], nums2 = [1,3,7,1], k = 3\n        Output: 2\n        Explanation: In 2 operations, we can transform nums1 to nums2.\n        1st operation: i = 2, j = 0. After applying the operation, nums1 = [1,3,4,4].\n        2nd operation: i = 2, j = 3. After applying the operation, nums1 = [1,3,7,1].\n        One can prove that it is impossible to make arrays equal in fewer operations.\n        Example 2:\n        Input: nums1 = [3,8,5,2], nums2 = [2,4,1,6], k = 1\n        Output: -1\n        Explanation: It can be proved that it is impossible to make the two arrays equal.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2514,
-        "title": "Count Anagrams",
-        "question": "class Solution:\n    def countAnagrams(self, s: str) -> int:\n        \"\"\"\n        You are given a string s containing one or more words. Every consecutive pair of words is separated by a single space ' '.\n        A string t is an anagram of string s if the ith word of t is a permutation of the ith word of s.\n            For example, \"acb dfe\" is an anagram of \"abc def\", but \"def cab\" and \"adc bef\" are not.\n        Return the number of distinct anagrams of s. Since the answer may be very large, return it modulo 109 + 7.\n        Example 1:\n        Input: s = \"too hot\"\n        Output: 18\n        Explanation: Some of the anagrams of the given string are \"too hot\", \"oot hot\", \"oto toh\", \"too toh\", and \"too oht\".\n        Example 2:\n        Input: s = \"aa\"\n        Output: 1\n        Explanation: There is only one anagram possible for the given string.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2482,
-        "title": "Difference Between Ones and Zeros in Row and Column",
-        "question": "class Solution:\n    def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given a 0-indexed m x n binary matrix grid.\n        A 0-indexed m x n difference matrix diff is created with the following procedure:\n            Let the number of ones in the ith row be onesRowi.\n            Let the number of ones in the jth column be onesColj.\n            Let the number of zeros in the ith row be zerosRowi.\n            Let the number of zeros in the jth column be zerosColj.\n            diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj\n        Return the difference matrix diff.\n        Example 1:\n        Input: grid = [[0,1,1],[1,0,1],[0,0,1]]\n        Output: [[0,0,4],[0,0,4],[-2,-2,2]]\n        Explanation:\n        - diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 2 + 1 - 1 - 2 = 0 \n        - diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 2 + 1 - 1 - 2 = 0 \n        - diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 2 + 3 - 1 - 0 = 4 \n        - diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 2 + 1 - 1 - 2 = 0 \n        - diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 2 + 1 - 1 - 2 = 0 \n        - diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 2 + 3 - 1 - 0 = 4 \n        - diff[2][0] = onesRow2 + onesCol0 - zerosRow2 - zerosCol0 = 1 + 1 - 2 - 2 = -2\n        - diff[2][1] = onesRow2 + onesCol1 - zerosRow2 - zerosCol1 = 1 + 1 - 2 - 2 = -2\n        - diff[2][2] = onesRow2 + onesCol2 - zerosRow2 - zerosCol2 = 1 + 3 - 2 - 0 = 2\n        Example 2:\n        Input: grid = [[1,1,1],[1,1,1]]\n        Output: [[5,5,5],[5,5,5]]\n        Explanation:\n        - diff[0][0] = onesRow0 + onesCol0 - zerosRow0 - zerosCol0 = 3 + 2 - 0 - 0 = 5\n        - diff[0][1] = onesRow0 + onesCol1 - zerosRow0 - zerosCol1 = 3 + 2 - 0 - 0 = 5\n        - diff[0][2] = onesRow0 + onesCol2 - zerosRow0 - zerosCol2 = 3 + 2 - 0 - 0 = 5\n        - diff[1][0] = onesRow1 + onesCol0 - zerosRow1 - zerosCol0 = 3 + 2 - 0 - 0 = 5\n        - diff[1][1] = onesRow1 + onesCol1 - zerosRow1 - zerosCol1 = 3 + 2 - 0 - 0 = 5\n        - diff[1][2] = onesRow1 + onesCol2 - zerosRow1 - zerosCol2 = 3 + 2 - 0 - 0 = 5\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2520,
-        "title": "Count the Digits That Divide a Number",
-        "question": "class Solution:\n    def countDigits(self, num: int) -> int:\n        \"\"\"\n        Given an integer num, return the number of digits in num that divide num.\n        An integer val divides nums if nums % val == 0.\n        Example 1:\n        Input: num = 7\n        Output: 1\n        Explanation: 7 divides itself, hence the answer is 1.\n        Example 2:\n        Input: num = 121\n        Output: 2\n        Explanation: 121 is divisible by 1, but not 2. Since 1 occurs twice as a digit, we return 2.\n        Example 3:\n        Input: num = 1248\n        Output: 4\n        Explanation: 1248 is divisible by all of its digits, hence the answer is 4.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2521,
-        "title": "Distinct Prime Factors of Product of Array",
-        "question": "class Solution:\n    def distinctPrimeFactors(self, nums: List[int]) -> int:\n        \"\"\"\n        Given an array of positive integers nums, return the number of distinct prime factors in the product of the elements of nums.\n        Note that:\n            A number greater than 1 is called prime if it is divisible by only 1 and itself.\n            An integer val1 is a factor of another integer val2 if val2 / val1 is an integer.\n        Example 1:\n        Input: nums = [2,4,3,7,10,6]\n        Output: 4\n        Explanation:\n        The product of all the elements in nums is: 2 * 4 * 3 * 7 * 10 * 6 = 10080 = 25 * 32 * 5 * 7.\n        There are 4 distinct prime factors so we return 4.\n        Example 2:\n        Input: nums = [2,4,8,16]\n        Output: 1\n        Explanation:\n        The product of all the elements in nums is: 2 * 4 * 8 * 16 = 1024 = 210.\n        There is 1 distinct prime factor so we return 1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2523,
-        "title": "Closest Prime Numbers in Range",
-        "question": "class Solution:\n    def closestPrimes(self, left: int, right: int) -> List[int]:\n        \"\"\"\n        Given two positive integers left and right, find the two integers num1 and num2 such that:\n            left <= nums1 < nums2 <= right .\n            nums1 and nums2 are both prime numbers.\n            nums2 - nums1 is the minimum amongst all other pairs satisfying the above conditions.\n        Return the positive integer array ans = [nums1, nums2]. If there are multiple pairs satisfying these conditions, return the one with the minimum nums1 value or [-1, -1] if such numbers do not exist.\n        A number greater than 1 is called prime if it is only divisible by 1 and itself.\n        Example 1:\n        Input: left = 10, right = 19\n        Output: [11,13]\n        Explanation: The prime numbers between 10 and 19 are 11, 13, 17, and 19.\n        The closest gap between any pair is 2, which can be achieved by [11,13] or [17,19].\n        Since 11 is smaller than 17, we return the first pair.\n        Example 2:\n        Input: left = 4, right = 6\n        Output: [-1,-1]\n        Explanation: There exists only one prime number in the given range, so the conditions cannot be satisfied.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2529,
-        "title": "Maximum Count of Positive Integer and Negative Integer",
-        "question": "class Solution:\n    def maximumCount(self, nums: List[int]) -> int:\n        \"\"\"\n        Given an array nums sorted in non-decreasing order, return the maximum between the number of positive integers and the number of negative integers.\n            In other words, if the number of positive integers in nums is pos and the number of negative integers is neg, then return the maximum of pos and neg.\n        Note that 0 is neither positive nor negative.\n        Example 1:\n        Input: nums = [-2,-1,-1,1,2,3]\n        Output: 3\n        Explanation: There are 3 positive integers and 3 negative integers. The maximum count among them is 3.\n        Example 2:\n        Input: nums = [-3,-2,-1,0,0,1,2]\n        Output: 3\n        Explanation: There are 2 positive integers and 3 negative integers. The maximum count among them is 3.\n        Example 3:\n        Input: nums = [5,20,66,1314]\n        Output: 4\n        Explanation: There are 4 positive integers and 0 negative integers. The maximum count among them is 4.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2531,
-        "title": "Make Number of Distinct Characters Equal",
-        "question": "class Solution:\n    def isItPossible(self, word1: str, word2: str) -> bool:\n        \"\"\"\n        You are given two 0-indexed strings word1 and word2.\n        A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j].\n        Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise.\n        Example 1:\n        Input: word1 = \"ac\", word2 = \"b\"\n        Output: false\n        Explanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string.\n        Example 2:\n        Input: word1 = \"abcc\", word2 = \"aab\"\n        Output: true\n        Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = \"abac\" and word2 = \"cab\", which both have 3 distinct characters.\n        Example 3:\n        Input: word1 = \"abcde\", word2 = \"fghij\"\n        Output: true\n        Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2530,
-        "title": "Maximal Score After Applying K Operations",
-        "question": "class Solution:\n    def maxKelements(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.\n        In one operation:\n            choose an index i such that 0 <= i < nums.length,\n            increase your score by nums[i], and\n            replace nums[i] with ceil(nums[i] / 3).\n        Return the maximum possible score you can attain after applying exactly k operations.\n        The ceiling function ceil(val) is the least integer greater than or equal to val.\n        Example 1:\n        Input: nums = [10,10,10,10,10], k = 5\n        Output: 50\n        Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.\n        Example 2:\n        Input: nums = [1,10,3,3,3], k = 3\n        Output: 17\n        Explanation: You can do the following operations:\n        Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10.\n        Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4.\n        Operation 3: Select i = 2, so nums becomes [1,1,1,3,3]. Your score increases by 3.\n        The final score is 10 + 4 + 3 = 17.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2528,
-        "title": "Maximize the Minimum Powered City",
-        "question": "class Solution:\n    def maxPower(self, stations: List[int], r: int, k: int) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array stations of length n, where stations[i] represents the number of power stations in the ith city.\n        Each power station can provide power to every city in a fixed range. In other words, if the range is denoted by r, then a power station at city i can provide power to all cities j such that |i - j| <= r and 0 <= i, j <= n - 1.\n            Note that |x| denotes absolute value. For example, |7 - 5| = 2 and |3 - 10| = 7.\n        The power of a city is the total number of power stations it is being provided power from.\n        The government has sanctioned building k more power stations, each of which can be built in any city, and have the same range as the pre-existing ones.\n        Given the two integers r and k, return the maximum possible minimum power of a city, if the additional power stations are built optimally.\n        Note that you can build the k power stations in multiple cities.\n        Example 1:\n        Input: stations = [1,2,4,5,0], r = 1, k = 2\n        Output: 5\n        Explanation: \n        One of the optimal ways is to install both the power stations at city 1. \n        So stations will become [1,4,4,5,0].\n        - City 0 is provided by 1 + 4 = 5 power stations.\n        - City 1 is provided by 1 + 4 + 4 = 9 power stations.\n        - City 2 is provided by 4 + 4 + 5 = 13 power stations.\n        - City 3 is provided by 5 + 4 = 9 power stations.\n        - City 4 is provided by 5 + 0 = 5 power stations.\n        So the minimum power of a city is 5.\n        Since it is not possible to obtain a larger power, we return 5.\n        Example 2:\n        Input: stations = [4,4,4,4], r = 0, k = 3\n        Output: 4\n        Explanation: \n        It can be proved that we cannot make the minimum power of a city greater than 4.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2525,
-        "title": "Categorize Box According to Criteria",
-        "question": "class Solution:\n    def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:\n        \"\"\"\n        Given four integers length, width, height, and mass, representing the dimensions and mass of a box, respectively, return a string representing the category of the box.\n            The box is \"Bulky\" if:\n                Any of the dimensions of the box is greater or equal to 104.\n                Or, the volume of the box is greater or equal to 109.\n            If the mass of the box is greater or equal to 100, it is \"Heavy\".\n            If the box is both \"Bulky\" and \"Heavy\", then its category is \"Both\".\n            If the box is neither \"Bulky\" nor \"Heavy\", then its category is \"Neither\".\n            If the box is \"Bulky\" but not \"Heavy\", then its category is \"Bulky\".\n            If the box is \"Heavy\" but not \"Bulky\", then its category is \"Heavy\".\n        Note that the volume of the box is the product of its length, width and height.\n        Example 1:\n        Input: length = 1000, width = 35, height = 700, mass = 300\n        Output: \"Heavy\"\n        Explanation: \n        None of the dimensions of the box is greater or equal to 104. \n        Its volume = 24500000 <= 109. So it cannot be categorized as \"Bulky\".\n        However mass >= 100, so the box is \"Heavy\".\n        Since the box is not \"Bulky\" but \"Heavy\", we return \"Heavy\".\n        Example 2:\n        Input: length = 200, width = 50, height = 800, mass = 50\n        Output: \"Neither\"\n        Explanation: \n        None of the dimensions of the box is greater or equal to 104.\n        Its volume = 8 * 106 <= 109. So it cannot be categorized as \"Bulky\".\n        Its mass is also less than 100, so it cannot be categorized as \"Heavy\" either. \n        Since its neither of the two above categories, we return \"Neither\".\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2526,
-        "title": "Find Consecutive Integers from a Data Stream",
-        "question": "class DataStream:\n    def __init__(self, value: int, k: int):\n    def consec(self, num: int) -> bool:\n        \"\"\"\n        For a stream of integers, implement a data structure that checks if the last k integers parsed in the stream are equal to value.\n        Implement the DataStream class:\n            DataStream(int value, int k) Initializes the object with an empty integer stream and the two integers value and k.\n            boolean consec(int num) Adds num to the stream of integers. Returns true if the last k integers are equal to value, and false otherwise. If there are less than k integers, the condition does not hold true, so returns false.\n        Example 1:\n        Input\n        [\"DataStream\", \"consec\", \"consec\", \"consec\", \"consec\"]\n        [[4, 3], [4], [4], [4], [3]]\n        Output\n        [null, false, false, true, false]\n        Explanation\n        DataStream dataStream = new DataStream(4, 3); //value = 4, k = 3 \n        dataStream.consec(4); // Only 1 integer is parsed, so returns False. \n        dataStream.consec(4); // Only 2 integers are parsed.\n                              // Since 2 is less than k, returns False. \n        dataStream.consec(4); // The 3 integers parsed are all equal to value, so returns True. \n        dataStream.consec(3); // The last k integers parsed in the stream are [4,4,3].\n                              // Since 3 is not equal to value, it returns False.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2527,
-        "title": "Find Xor-Beauty of Array",
-        "question": "class Solution:\n    def xorBeauty(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums.\n        The effective value of three indices i, j, and k is defined as ((nums[i] | nums[j]) & nums[k]).\n        The xor-beauty of the array is the XORing of the effective values of all the possible triplets of indices (i, j, k) where 0 <= i, j, k < n.\n        Return the xor-beauty of nums.\n        Note that:\n            val1 | val2 is bitwise OR of val1 and val2.\n            val1 & val2 is bitwise AND of val1 and val2.\n        Example 1:\n        Input: nums = [1,4]\n        Output: 5\n        Explanation: \n        The triplets and their corresponding effective values are listed below:\n        - (0,0,0) with effective value ((1 | 1) & 1) = 1\n        - (0,0,1) with effective value ((1 | 1) & 4) = 0\n        - (0,1,0) with effective value ((1 | 4) & 1) = 1\n        - (0,1,1) with effective value ((1 | 4) & 4) = 4\n        - (1,0,0) with effective value ((4 | 1) & 1) = 1\n        - (1,0,1) with effective value ((4 | 1) & 4) = 4\n        - (1,1,0) with effective value ((4 | 4) & 1) = 0\n        - (1,1,1) with effective value ((4 | 4) & 4) = 4 \n        Xor-beauty of array will be bitwise XOR of all beauties = 1 ^ 0 ^ 1 ^ 4 ^ 1 ^ 4 ^ 0 ^ 4 = 5.\n        Example 2:\n        Input: nums = [15,45,20,2,34,35,5,44,32,30]\n        Output: 34\n        Explanation: The xor-beauty of the given array is 34.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2535,
-        "title": "Difference Between Element Sum and Digit Sum of an Array",
-        "question": "class Solution:\n    def differenceOfSum(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a positive integer array nums.\n            The element sum is the sum of all the elements in nums.\n            The digit sum is the sum of all the digits (not necessarily distinct) that appear in nums.\n        Return the absolute difference between the element sum and digit sum of nums.\n        Note that the absolute difference between two integers x and y is defined as |x - y|.\n        Example 1:\n        Input: nums = [1,15,6,3]\n        Output: 9\n        Explanation: \n        The element sum of nums is 1 + 15 + 6 + 3 = 25.\n        The digit sum of nums is 1 + 1 + 5 + 6 + 3 = 16.\n        The absolute difference between the element sum and digit sum is |25 - 16| = 9.\n        Example 2:\n        Input: nums = [1,2,3,4]\n        Output: 0\n        Explanation:\n        The element sum of nums is 1 + 2 + 3 + 4 = 10.\n        The digit sum of nums is 1 + 2 + 3 + 4 = 10.\n        The absolute difference between the element sum and digit sum is |10 - 10| = 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2536,
-        "title": "Increment Submatrices by One",
-        "question": "class Solution:\n    def rangeAddQueries(self, n: int, queries: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given a positive integer n, indicating that we initially have an n x n 0-indexed integer matrix mat filled with zeroes.\n        You are also given a 2D integer array query. For each query[i] = [row1i, col1i, row2i, col2i], you should do the following operation:\n            Add 1 to every element in the submatrix with the top left corner (row1i, col1i) and the bottom right corner (row2i, col2i). That is, add 1 to mat[x][y] for all row1i <= x <= row2i and col1i <= y <= col2i.\n        Return the matrix mat after performing every query.\n        Example 1:\n        Input: n = 3, queries = [[1,1,2,2],[0,0,1,1]]\n        Output: [[1,1,0],[1,2,1],[0,1,1]]\n        Explanation: The diagram above shows the initial matrix, the matrix after the first query, and the matrix after the second query.\n        - In the first query, we add 1 to every element in the submatrix with the top left corner (1, 1) and bottom right corner (2, 2).\n        - In the second query, we add 1 to every element in the submatrix with the top left corner (0, 0) and bottom right corner (1, 1).\n        Example 2:\n        Input: n = 2, queries = [[0,0,1,1]]\n        Output: [[1,1],[1,1]]\n        Explanation: The diagram above shows the initial matrix and the matrix after the first query.\n        - In the first query we add 1 to every element in the matrix.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2537,
-        "title": "Count the Number of Good Subarrays",
-        "question": "class Solution:\n    def countGood(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        Given an integer array nums and an integer k, return the number of good subarrays of nums.\n        A subarray arr is good if it there are at least k pairs of indices (i, j) such that i < j and arr[i] == arr[j].\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,1,1,1,1], k = 10\n        Output: 1\n        Explanation: The only good subarray is the array nums itself.\n        Example 2:\n        Input: nums = [3,1,4,3,2,2,4], k = 2\n        Output: 4\n        Explanation: There are 4 different good subarrays:\n        - [3,1,4,3,2,2] that has 2 pairs.\n        - [3,1,4,3,2,2,4] that has 3 pairs.\n        - [1,4,3,2,2,4] that has 2 pairs.\n        - [4,3,2,2,4] that has 2 pairs.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2538,
-        "title": "Difference Between Maximum and Minimum Price Sum",
-        "question": "class Solution:\n    def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:\n        \"\"\"\n        There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and 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.\n        Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.\n        The price sum of a given path is the sum of the prices of all nodes lying on that path.\n        The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root.\n        Return the maximum possible cost amongst all possible root choices.\n        Example 1:\n        Input: n = 6, edges = [[0,1],[1,2],[1,3],[3,4],[3,5]], price = [9,8,7,6,10,5]\n        Output: 24\n        Explanation: The diagram above denotes the tree after rooting it at node 2. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.\n        - The first path contains nodes [2,1,3,4]: the prices are [7,8,6,10], and the sum of the prices is 31.\n        - The second path contains the node [2] with the price [7].\n        The difference between the maximum and minimum price sum is 24. It can be proved that 24 is the maximum cost.\n        Example 2:\n        Input: n = 3, edges = [[0,1],[1,2]], price = [1,1,1]\n        Output: 2\n        Explanation: The diagram above denotes the tree after rooting it at node 0. The first part (colored in red) shows the path with the maximum price sum. The second part (colored in blue) shows the path with the minimum price sum.\n        - The first path contains nodes [0,1,2]: the prices are [1,1,1], and the sum of the prices is 3.\n        - The second path contains node [0] with a price [1].\n        The difference between the maximum and minimum price sum is 2. It can be proved that 2 is the maximum cost.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2513,
-        "title": "Minimize the Maximum of Two Arrays",
-        "question": "class Solution:\n    def minimizeSet(self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int) -> int:\n        \"\"\"\n        We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:\n            arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1.\n            arr2 contains uniqueCnt2 distinct positive integers, each of which is not divisible by divisor2.\n            No integer is present in both arr1 and arr2.\n        Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.\n        Example 1:\n        Input: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3\n        Output: 4\n        Explanation: \n        We can distribute the first 4 natural numbers into arr1 and arr2.\n        arr1 = [1] and arr2 = [2,3,4].\n        We can see that both arrays satisfy all the conditions.\n        Since the maximum value is 4, we return it.\n        Example 2:\n        Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1\n        Output: 3\n        Explanation: \n        Here arr1 = [1,2], and arr2 = [3] satisfy all conditions.\n        Since the maximum value is 3, we return it.\n        Example 3:\n        Input: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2\n        Output: 15\n        Explanation: \n        Here, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6].\n        It can be shown that it is not possible to obtain a lower maximum satisfying all conditions. \n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2544,
-        "title": "Alternating Digit Sum",
-        "question": "class Solution:\n    def alternateDigitSum(self, n: int) -> int:\n        \"\"\"\n        You are given a positive integer n. Each digit of n has a sign according to the following rules:\n            The most significant digit is assigned a positive sign.\n            Each other digit has an opposite sign to its adjacent digits.\n        Return the sum of all digits with their corresponding sign.\n        Example 1:\n        Input: n = 521\n        Output: 4\n        Explanation: (+5) + (-2) + (+1) = 4.\n        Example 2:\n        Input: n = 111\n        Output: 1\n        Explanation: (+1) + (-1) + (+1) = 1.\n        Example 3:\n        Input: n = 886996\n        Output: 0\n        Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2545,
-        "title": "Sort the Students by Their Kth Score",
-        "question": "class Solution:\n    def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:\n        \"\"\"\n        There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix score contains distinct integers only.\n        You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-indexed) exam from the highest to the lowest.\n        Return the matrix after sorting it.\n        Example 1:\n        Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2\n        Output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]\n        Explanation: In the above diagram, S denotes the student, while E denotes the exam.\n        - The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place.\n        - The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place.\n        - The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place.\n        Example 2:\n        Input: score = [[3,4],[5,6]], k = 0\n        Output: [[5,6],[3,4]]\n        Explanation: In the above diagram, S denotes the student, while E denotes the exam.\n        - The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place.\n        - The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2546,
-        "title": "Apply Bitwise Operations to Make Strings Equal",
-        "question": "class Solution:\n    def makeStringsEqual(self, s: str, target: str) -> bool:\n        \"\"\"\n        You are given two 0-indexed binary strings s and target of the same length n. You can do the following operation on s any number of times:\n            Choose two different indices i and j where 0 <= i, j < n.\n            Simultaneously, replace s[i] with (s[i] OR s[j]) and s[j] with (s[i] XOR s[j]).\n        For example, if s = \"0110\", you can choose i = 0 and j = 2, then simultaneously replace s[0] with (s[0] OR s[2] = 0 OR 1 = 1), and s[2] with (s[0] XOR s[2] = 0 XOR 1 = 1), so we will have s = \"1110\".\n        Return true if you can make the string s equal to target, or false otherwise.\n        Example 1:\n        Input: s = \"1010\", target = \"0110\"\n        Output: true\n        Explanation: We can do the following operations:\n        - Choose i = 2 and j = 0. We have now s = \"0010\".\n        - Choose i = 2 and j = 1. We have now s = \"0110\".\n        Since we can make s equal to target, we return true.\n        Example 2:\n        Input: s = \"11\", target = \"00\"\n        Output: false\n        Explanation: It is not possible to make s equal to target with any number of operations.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2547,
-        "title": "Minimum Cost to Split an Array",
-        "question": "class Solution:\n    def minCost(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given an integer array nums and an integer k.\n        Split the array into some number of non-empty subarrays. The cost of a split is the sum of the importance value of each subarray in the split.\n        Let trimmed(subarray) be the version of the subarray where all numbers which appear only once are removed.\n            For example, trimmed([3,1,2,4,3,4]) = [3,4,3,4].\n        The importance value of a subarray is k + trimmed(subarray).length.\n            For example, if a subarray is [1,2,3,3,3,4,4], then trimmed([1,2,3,3,3,4,4]) = [3,3,3,4,4].The importance value of this subarray will be k + 5.\n        Return the minimum possible cost of a split of nums.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [1,2,1,2,1,3,3], k = 2\n        Output: 8\n        Explanation: We split nums to have two subarrays: [1,2], [1,2,1,3,3].\n        The importance value of [1,2] is 2 + (0) = 2.\n        The importance value of [1,2,1,3,3] is 2 + (2 + 2) = 6.\n        The cost of the split is 2 + 6 = 8. It can be shown that this is the minimum possible cost among all the possible splits.\n        Example 2:\n        Input: nums = [1,2,1,2,1], k = 2\n        Output: 6\n        Explanation: We split nums to have two subarrays: [1,2], [1,2,1].\n        The importance value of [1,2] is 2 + (0) = 2.\n        The importance value of [1,2,1] is 2 + (2) = 4.\n        The cost of the split is 2 + 4 = 6. It can be shown that this is the minimum possible cost among all the possible splits.\n        Example 3:\n        Input: nums = [1,2,1,2,1], k = 5\n        Output: 10\n        Explanation: We split nums to have one subarray: [1,2,1,2,1].\n        The importance value of [1,2,1,2,1] is 5 + (3 + 2) = 10.\n        The cost of the split is 10. It can be shown that this is the minimum possible cost among all the possible splits.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2540,
-        "title": "Minimum Common Value",
-        "question": "class Solution:\n    def getCommon(self, nums1: List[int], nums2: List[int]) -> int:\n        \"\"\"\n        Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1.\n        Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer.\n        Example 1:\n        Input: nums1 = [1,2,3], nums2 = [2,4]\n        Output: 2\n        Explanation: The smallest element common to both arrays is 2, so we return 2.\n        Example 2:\n        Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5]\n        Output: 2\n        Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2543,
-        "title": "Check if Point Is Reachable",
-        "question": "class Solution:\n    def isReachable(self, targetX: int, targetY: int) -> bool:\n        \"\"\"\n        There exists an infinitely large grid. You are currently at point (1, 1), and you need to reach the point (targetX, targetY) using a finite number of steps.\n        In one step, you can move from point (x, y) to any one of the following points:\n            (x, y - x)\n            (x - y, y)\n            (2 * x, y)\n            (x, 2 * y)\n        Given two integers targetX and targetY representing the X-coordinate and Y-coordinate of your final position, return true if you can reach the point from (1, 1) using some number of steps, and false otherwise.\n        Example 1:\n        Input: targetX = 6, targetY = 9\n        Output: false\n        Explanation: It is impossible to reach (6,9) from (1,1) using any sequence of moves, so false is returned.\n        Example 2:\n        Input: targetX = 4, targetY = 7\n        Output: true\n        Explanation: You can follow the path (1,1) -> (1,2) -> (1,4) -> (1,8) -> (1,7) -> (2,7) -> (4,7).\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2542,
-        "title": "Maximum Subsequence Score",
-        "question": "class Solution:\n    def maxScore(self, nums1: List[int], nums2: List[int], k: int) -> int:\n        \"\"\"\n        You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.\n        For chosen indices i0, i1, ..., ik - 1, your score is defined as:\n            The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2.\n            It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]).\n        Return the maximum possible score.\n        A subsequence of indices of an array is a set that can be derived from the set {0, 1, ..., n-1} by deleting some or no elements.\n        Example 1:\n        Input: nums1 = [1,3,3,2], nums2 = [2,1,3,4], k = 3\n        Output: 12\n        Explanation: \n        The four possible subsequence scores are:\n        - We choose the indices 0, 1, and 2 with score = (1+3+3) * min(2,1,3) = 7.\n        - We choose the indices 0, 1, and 3 with score = (1+3+2) * min(2,1,4) = 6. \n        - We choose the indices 0, 2, and 3 with score = (1+3+2) * min(2,3,4) = 12. \n        - We choose the indices 1, 2, and 3 with score = (3+3+2) * min(1,3,4) = 8.\n        Therefore, we return the max score, which is 12.\n        Example 2:\n        Input: nums1 = [4,2,3,1,1], nums2 = [7,5,10,9,6], k = 1\n        Output: 30\n        Explanation: \n        Choosing index 2 is optimal: nums1[2] * nums2[2] = 3 * 10 = 30 is the maximum possible score.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2553,
-        "title": "Separate the Digits in an Array",
-        "question": "class Solution:\n    def separateDigits(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        Given an array of positive integers nums, return an array answer that consists of the digits of each integer in nums after separating them in the same order they appear in nums.\n        To separate the digits of an integer is to get all the digits it has in the same order.\n            For example, for the integer 10921, the separation of its digits is [1,0,9,2,1].\n        Example 1:\n        Input: nums = [13,25,83,77]\n        Output: [1,3,2,5,8,3,7,7]\n        Explanation: \n        - The separation of 13 is [1,3].\n        - The separation of 25 is [2,5].\n        - The separation of 83 is [8,3].\n        - The separation of 77 is [7,7].\n        answer = [1,3,2,5,8,3,7,7]. Note that answer contains the separations in the same order.\n        Example 2:\n        Input: nums = [7,1,3,9]\n        Output: [7,1,3,9]\n        Explanation: The separation of each integer in nums is itself.\n        answer = [7,1,3,9].\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2554,
-        "title": "Maximum Number of Integers to Choose From a Range I",
-        "question": "class Solution:\n    def maxCount(self, banned: List[int], n: int, maxSum: int) -> int:\n        \"\"\"\n        You are given an integer array banned and two integers n and maxSum. You are choosing some number of integers following the below rules:\n            The chosen integers have to be in the range [1, n].\n            Each integer can be chosen at most once.\n            The chosen integers should not be in the array banned.\n            The sum of the chosen integers should not exceed maxSum.\n        Return the maximum number of integers you can choose following the mentioned rules.\n        Example 1:\n        Input: banned = [1,6,5], n = 5, maxSum = 6\n        Output: 2\n        Explanation: You can choose the integers 2 and 4.\n        2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum.\n        Example 2:\n        Input: banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1\n        Output: 0\n        Explanation: You cannot choose any integer while following the mentioned conditions.\n        Example 3:\n        Input: banned = [11], n = 7, maxSum = 50\n        Output: 7\n        Explanation: You can choose the integers 1, 2, 3, 4, 5, 6, and 7.\n        They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2556,
-        "title": "Disconnect Path in a Binary Matrix by at Most One Flip",
-        "question": "class Solution:\n    def isPossibleToCutPath(self, grid: List[List[int]]) -> bool:\n        \"\"\"\n        You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1) that has the value 1. The matrix is disconnected if there is no path from (0, 0) to (m - 1, n - 1).\n        You can flip the value of at most one (possibly none) cell. You cannot flip the cells (0, 0) and (m - 1, n - 1).\n        Return true if it is possible to make the matrix disconnect or false otherwise.\n        Note that flipping a cell changes its value from 0 to 1 or from 1 to 0.\n        Example 1:\n        Input: grid = [[1,1,1],[1,0,0],[1,1,1]]\n        Output: true\n        Explanation: We can change the cell shown in the diagram above. There is no path from (0, 0) to (2, 2) in the resulting grid.\n        Example 2:\n        Input: grid = [[1,1,1],[1,0,1],[1,1,1]]\n        Output: false\n        Explanation: It is not possible to change at most one cell such that there is not path from (0, 0) to (2, 2).\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2532,
-        "title": "Time to Cross a Bridge",
-        "question": "class Solution:\n    def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int:\n        \"\"\"\n        There are k workers who want to move n boxes from an old warehouse to a new one. You are given the two integers n and k, and a 2D integer array time of size k x 4 where time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi].\n        The warehouses are separated by a river and connected by a bridge. The old warehouse is on the right bank of the river, and the new warehouse is on the left bank of the river. Initially, all k workers are waiting on the left side of the bridge. To move the boxes, the ith worker (0-indexed) can :\n            Cross the bridge from the left bank (new warehouse) to the right bank (old warehouse) in leftToRighti minutes.\n            Pick a box from the old warehouse and return to the bridge in pickOldi minutes. Different workers can pick up their boxes simultaneously.\n            Cross the bridge from the right bank (old warehouse) to the left bank (new warehouse) in rightToLefti minutes.\n            Put the box in the new warehouse and return to the bridge in putNewi minutes. Different workers can put their boxes simultaneously.\n        A worker i is less efficient than a worker j if either condition is met:\n            leftToRighti + rightToLefti > leftToRightj + rightToLeftj\n            leftToRighti + rightToLefti == leftToRightj + rightToLeftj and i > j\n        The following rules regulate the movement of the workers through the bridge :\n            If a worker x reaches the bridge while another worker y is crossing the bridge, x waits at their side of the bridge.\n            If the bridge is free, the worker waiting on the right side of the bridge gets to cross the bridge. If more than one worker is waiting on the right side, the one with the lowest efficiency crosses first.\n            If the bridge is free and no worker is waiting on the right side, and at least one box remains at the old warehouse, the worker on the left side of the river gets to cross the bridge. If more than one worker is waiting on the left side, the one with the lowest efficiency crosses first.\n        Return the instance of time at which the last worker reaches the left bank of the river after all n boxes have been put in the new warehouse.\n        Example 1:\n        Input: n = 1, k = 3, time = [[1,1,2,1],[1,1,3,1],[1,1,4,1]]\n        Output: 6\n        Explanation: \n        From 0 to 1: worker 2 crosses the bridge from the left bank to the right bank.\n        From 1 to 2: worker 2 picks up a box from the old warehouse.\n        From 2 to 6: worker 2 crosses the bridge from the right bank to the left bank.\n        From 6 to 7: worker 2 puts a box at the new warehouse.\n        The whole process ends after 7 minutes. We return 6 because the problem asks for the instance of time at which the last worker reaches the left bank.\n        Example 2:\n        Input: n = 3, k = 2, time = [[1,9,1,8],[10,10,10,10]]\n        Output: 50\n        Explanation: \n        From 0  to 10: worker 1 crosses the bridge from the left bank to the right bank.\n        From 10 to 20: worker 1 picks up a box from the old warehouse.\n        From 10 to 11: worker 0 crosses the bridge from the left bank to the right bank.\n        From 11 to 20: worker 0 picks up a box from the old warehouse.\n        From 20 to 30: worker 1 crosses the bridge from the right bank to the left bank.\n        From 30 to 40: worker 1 puts a box at the new warehouse.\n        From 30 to 31: worker 0 crosses the bridge from the right bank to the left bank.\n        From 31 to 39: worker 0 puts a box at the new warehouse.\n        From 39 to 40: worker 0 crosses the bridge from the left bank to the right bank.\n        From 40 to 49: worker 0 picks up a box from the old warehouse.\n        From 49 to 50: worker 0 crosses the bridge from the right bank to the left bank.\n        From 50 to 58: worker 0 puts a box at the new warehouse.\n        The whole process ends after 58 minutes. We return 50 because the problem asks for the instance of time at which the last worker reaches the left bank.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2582,
-        "title": "Pass the Pillow",
-        "question": "class Solution:\n    def passThePillow(self, n: int, time: int) -> int:\n        \"\"\"\n        There are n people standing in a line labeled from 1 to n. The first person in the line is holding a pillow initially. Every second, the person holding the pillow passes it to the next person standing in the line. Once the pillow reaches the end of the line, the direction changes, and people continue passing the pillow in the opposite direction.\n            For example, once the pillow reaches the nth person they pass it to the n - 1th person, then to the n - 2th person and so on.\n        Given the two positive integers n and time, return the index of the person holding the pillow after time seconds.\n        Example 1:\n        Input: n = 4, time = 5\n        Output: 2\n        Explanation: People pass the pillow in the following way: 1 -> 2 -> 3 -> 4 -> 3 -> 2.\n        Afer five seconds, the pillow is given to the 2nd person.\n        Example 2:\n        Input: n = 3, time = 2\n        Output: 3\n        Explanation: People pass the pillow in the following way: 1 -> 2 -> 3.\n        Afer two seconds, the pillow is given to the 3rd person.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2583,
-        "title": "Kth Largest Sum in a Binary Tree",
-        "question": "class Solution:\n    def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:\n        \"\"\"\n        You are given the root of a binary tree and a positive integer k.\n        The level sum in the tree is the sum of the values of the nodes that are on the same level.\n        Return the kth largest level sum in the tree (not necessarily distinct). If there are fewer than k levels in the tree, return -1.\n        Note that two nodes are on the same level if they have the same distance from the root.\n        Example 1:\n        Input: root = [5,8,9,2,1,3,7,4,6], k = 2\n        Output: 13\n        Explanation: The level sums are the following:\n        - Level 1: 5.\n        - Level 2: 8 + 9 = 17.\n        - Level 3: 2 + 1 + 3 + 7 = 13.\n        - Level 4: 4 + 6 = 10.\n        The 2nd largest level sum is 13.\n        Example 2:\n        Input: root = [1,2,null,3], k = 1\n        Output: 3\n        Explanation: The largest level sum is 3.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2584,
-        "title": "Split the Array to Make Coprime Products",
-        "question": "class Solution:\n    def findValidSplit(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums of length n.\n        A split at an index i where 0 <= i <= n - 2 is called valid if the product of the first i + 1 elements and the product of the remaining elements are coprime.\n            For example, if nums = [2, 3, 3], then a split at the index i = 0 is valid because 2 and 9 are coprime, while a split at the index i = 1 is not valid because 6 and 3 are not coprime. A split at the index i = 2 is not valid because i == n - 1.\n        Return the smallest index i at which the array can be split validly or -1 if there is no such split.\n        Two values val1 and val2 are coprime if gcd(val1, val2) == 1 where gcd(val1, val2) is the greatest common divisor of val1 and val2.\n        Example 1:\n        Input: nums = [4,7,8,15,3,5]\n        Output: 2\n        Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.\n        The only valid split is at index 2.\n        Example 2:\n        Input: nums = [4,7,15,8,3,5]\n        Output: -1\n        Explanation: The table above shows the values of the product of the first i + 1 elements, the remaining elements, and their gcd at each index i.\n        There is no valid split.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2585,
-        "title": "Number of Ways to Earn Points",
-        "question": "class Solution:\n    def waysToReachTarget(self, target: int, types: List[List[int]]) -> int:\n        \"\"\"\n        There is a test that has n types of questions. You are given an integer target and a 0-indexed 2D integer array types where types[i] = [counti, marksi] indicates that there are counti questions of the ith type, and each one of them is worth marksi points.\n        Return the number of ways you can earn exactly target points in the exam. Since the answer may be too large, return it modulo 109 + 7.\n        Note that questions of the same type are indistinguishable.\n            For example, if there are 3 questions of the same type, then solving the 1st and 2nd questions is the same as solving the 1st and 3rd questions, or the 2nd and 3rd questions.\n        Example 1:\n        Input: target = 6, types = [[6,1],[3,2],[2,3]]\n        Output: 7\n        Explanation: You can earn 6 points in one of the seven ways:\n        - Solve 6 questions of the 0th type: 1 + 1 + 1 + 1 + 1 + 1 = 6\n        - Solve 4 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 1 + 2 = 6\n        - Solve 2 questions of the 0th type and 2 questions of the 1st type: 1 + 1 + 2 + 2 = 6\n        - Solve 3 questions of the 0th type and 1 question of the 2nd type: 1 + 1 + 1 + 3 = 6\n        - Solve 1 question of the 0th type, 1 question of the 1st type and 1 question of the 2nd type: 1 + 2 + 3 = 6\n        - Solve 3 questions of the 1st type: 2 + 2 + 2 = 6\n        - Solve 2 questions of the 2nd type: 3 + 3 = 6\n        Example 2:\n        Input: target = 5, types = [[50,1],[50,2],[50,5]]\n        Output: 4\n        Explanation: You can earn 5 points in one of the four ways:\n        - Solve 5 questions of the 0th type: 1 + 1 + 1 + 1 + 1 = 5\n        - Solve 3 questions of the 0th type and 1 question of the 1st type: 1 + 1 + 1 + 2 = 5\n        - Solve 1 questions of the 0th type and 2 questions of the 1st type: 1 + 2 + 2 = 5\n        - Solve 1 question of the 2nd type: 5\n        Example 3:\n        Input: target = 18, types = [[6,1],[3,2],[2,3]]\n        Output: 1\n        Explanation: You can only earn 18 points by answering all questions.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2579,
-        "title": "Count Total Number of Colored Cells",
-        "question": "class Solution:\n    def coloredCells(self, n: int) -> int:\n        \"\"\"\n        There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer n, indicating that you must do the following routine for n minutes:\n            At the first minute, color any arbitrary unit cell blue.\n            Every minute thereafter, color blue every uncolored cell that touches a blue cell.\n        Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.\n        Return the number of colored cells at the end of n minutes.\n        Example 1:\n        Input: n = 1\n        Output: 1\n        Explanation: After 1 minute, there is only 1 blue cell, so we return 1.\n        Example 2:\n        Input: n = 2\n        Output: 5\n        Explanation: After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5. \n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2578,
-        "title": "Split With Minimum Sum",
-        "question": "class Solution:\n    def splitNum(self, num: int) -> int:\n        \"\"\"\n        Given a positive integer num, split it into two non-negative integers num1 and num2 such that:\n            The concatenation of num1 and num2 is a permutation of num.\n                In other words, the sum of the number of occurrences of each digit in num1 and num2 is equal to the number of occurrences of that digit in num.\n            num1 and num2 can contain leading zeros.\n        Return the minimum possible sum of num1 and num2.\n        Notes:\n            It is guaranteed that num does not contain any leading zeros.\n            The order of occurrence of the digits in num1 and num2 may differ from the order of occurrence of num.\n        Example 1:\n        Input: num = 4325\n        Output: 59\n        Explanation: We can split 4325 so that num1 is 24 and num2 is 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.\n        Example 2:\n        Input: num = 687\n        Output: 75\n        Explanation: We can split 687 so that num1 is 68 and num2 is 7, which would give an optimal sum of 75.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2580,
-        "title": "Count Ways to Group Overlapping Ranges",
-        "question": "class Solution:\n    def countWays(self, ranges: List[List[int]]) -> int:\n        \"\"\"\n        You are given a 2D integer array ranges where ranges[i] = [starti, endi] denotes that all integers between starti and endi (both inclusive) are contained in the ith range.\n        You are to split ranges into two (possibly empty) groups such that:\n            Each range belongs to exactly one group.\n            Any two overlapping ranges must belong to the same group.\n        Two ranges are said to be overlapping if there exists at least one integer that is present in both ranges.\n            For example, [1, 3] and [2, 5] are overlapping because 2 and 3 occur in both ranges.\n        Return the total number of ways to split ranges into two groups. Since the answer may be very large, return it modulo 109 + 7.\n        Example 1:\n        Input: ranges = [[6,10],[5,15]]\n        Output: 2\n        Explanation: \n        The two ranges are overlapping, so they must be in the same group.\n        Thus, there are two possible ways:\n        - Put both the ranges together in group 1.\n        - Put both the ranges together in group 2.\n        Example 2:\n        Input: ranges = [[1,3],[10,20],[2,5],[4,8]]\n        Output: 4\n        Explanation: \n        Ranges [1,3], and [2,5] are overlapping. So, they must be in the same group.\n        Again, ranges [2,5] and [4,8] are also overlapping. So, they must also be in the same group. \n        Thus, there are four possible ways to group them:\n        - All the ranges in group 1.\n        - All the ranges in group 2.\n        - Ranges [1,3], [2,5], and [4,8] in group 1 and [10,20] in group 2.\n        - Ranges [1,3], [2,5], and [4,8] in group 2 and [10,20] in group 1.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2581,
-        "title": "Count Number of Possible Root Nodes",
-        "question": "class Solution:\n    def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n        \"\"\"\n        Alice has an undirected tree with n nodes labeled from 0 to n - 1. The tree is represented as 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.\n        Alice wants Bob to find the root of the tree. She allows Bob to make several guesses about her tree. In one guess, he does the following:\n            Chooses two distinct integers u and v such that there exists an edge [u, v] in the tree.\n            He tells Alice that u is the parent of v in the tree.\n        Bob's guesses are represented by a 2D integer array guesses where guesses[j] = [uj, vj] indicates Bob guessed uj to be the parent of vj.\n        Alice being lazy, does not reply to each of Bob's guesses, but just says that at least k of his guesses are true.\n        Given the 2D integer arrays edges, guesses and the integer k, return the number of possible nodes that can be the root of Alice's tree. If there is no such tree, return 0.\n        Example 1:\n        Input: edges = [[0,1],[1,2],[1,3],[4,2]], guesses = [[1,3],[0,1],[1,0],[2,4]], k = 3\n        Output: 3\n        Explanation: \n        Root = 0, correct guesses = [1,3], [0,1], [2,4]\n        Root = 1, correct guesses = [1,3], [1,0], [2,4]\n        Root = 2, correct guesses = [1,3], [1,0], [2,4]\n        Root = 3, correct guesses = [1,0], [2,4]\n        Root = 4, correct guesses = [1,3], [1,0]\n        Considering 0, 1, or 2 as root node leads to 3 correct guesses.\n        Example 2:\n        Input: edges = [[0,1],[1,2],[2,3],[3,4]], guesses = [[1,0],[3,4],[2,1],[3,2]], k = 1\n        Output: 5\n        Explanation: \n        Root = 0, correct guesses = [3,4]\n        Root = 1, correct guesses = [1,0], [3,4]\n        Root = 2, correct guesses = [1,0], [2,1], [3,4]\n        Root = 3, correct guesses = [1,0], [2,1], [3,2], [3,4]\n        Root = 4, correct guesses = [1,0], [2,1], [3,2]\n        Considering any node as root will give at least 1 correct guess. \n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2586,
-        "title": "Count the Number of Vowel Strings in Range",
-        "question": "class Solution:\n    def vowelStrings(self, words: List[str], left: int, right: int) -> int:\n        \"\"\"\n        You are given a 0-indexed array of string words and two integers left and right.\n        A string is called a vowel string if it starts with a vowel character and ends with a vowel character where vowel characters are 'a', 'e', 'i', 'o', and 'u'.\n        Return the number of vowel strings words[i] where i belongs to the inclusive range [left, right].\n        Example 1:\n        Input: words = [\"are\",\"amy\",\"u\"], left = 0, right = 2\n        Output: 2\n        Explanation: \n        - \"are\" is a vowel string because it starts with 'a' and ends with 'e'.\n        - \"amy\" is not a vowel string because it does not end with a vowel.\n        - \"u\" is a vowel string because it starts with 'u' and ends with 'u'.\n        The number of vowel strings in the mentioned range is 2.\n        Example 2:\n        Input: words = [\"hey\",\"aeo\",\"mu\",\"ooo\",\"artro\"], left = 1, right = 4\n        Output: 3\n        Explanation: \n        - \"aeo\" is a vowel string because it starts with 'a' and ends with 'o'.\n        - \"mu\" is not a vowel string because it does not start with a vowel.\n        - \"ooo\" is a vowel string because it starts with 'o' and ends with 'o'.\n        - \"artro\" is a vowel string because it starts with 'a' and ends with 'o'.\n        The number of vowel strings in the mentioned range is 3.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2587,
-        "title": "Rearrange Array to Maximize Prefix Score",
-        "question": "class Solution:\n    def maxScore(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums. You can rearrange the elements of nums to any order (including the given order).\n        Let prefix be the array containing the prefix sums of nums after rearranging it. In other words, prefix[i] is the sum of the elements from 0 to i in nums after rearranging it. The score of nums is the number of positive integers in the array prefix.\n        Return the maximum score you can achieve.\n        Example 1:\n        Input: nums = [2,-1,0,1,-3,3,-3]\n        Output: 6\n        Explanation: We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].\n        prefix = [2,5,6,5,2,2,-1], so the score is 6.\n        It can be shown that 6 is the maximum score we can obtain.\n        Example 2:\n        Input: nums = [-2,-3,0]\n        Output: 0\n        Explanation: Any rearrangement of the array will result in a score of 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2588,
-        "title": "Count the Number of Beautiful Subarrays",
-        "question": "class Solution:\n    def beautifulSubarrays(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums. In one operation, you can:\n            Choose two different indices i and j such that 0 <= i, j < nums.length.\n            Choose a non-negative integer k such that the kth bit (0-indexed) in the binary representation of nums[i] and nums[j] is 1.\n            Subtract 2k from nums[i] and nums[j].\n        A subarray is beautiful if it is possible to make all of its elements equal to 0 after applying the above operation any number of times.\n        Return the number of beautiful subarrays in the array nums.\n        A subarray is a contiguous non-empty sequence of elements within an array.\n        Example 1:\n        Input: nums = [4,3,1,2,4]\n        Output: 2\n        Explanation: There are 2 beautiful subarrays in nums: [4,3,1,2,4] and [4,3,1,2,4].\n        - We can make all elements in the subarray [3,1,2] equal to 0 in the following way:\n          - Choose [3, 1, 2] and k = 1. Subtract 21 from both numbers. The subarray becomes [1, 1, 0].\n          - Choose [1, 1, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 0, 0].\n        - We can make all elements in the subarray [4,3,1,2,4] equal to 0 in the following way:\n          - Choose [4, 3, 1, 2, 4] and k = 2. Subtract 22 from both numbers. The subarray becomes [0, 3, 1, 2, 0].\n          - Choose [0, 3, 1, 2, 0] and k = 0. Subtract 20 from both numbers. The subarray becomes [0, 2, 0, 2, 0].\n          - Choose [0, 2, 0, 2, 0] and k = 1. Subtract 21 from both numbers. The subarray becomes [0, 0, 0, 0, 0].\n        Example 2:\n        Input: nums = [1,10,4]\n        Output: 0\n        Explanation: There are no beautiful subarrays in nums.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2589,
-        "title": "Minimum Time to Complete All Tasks",
-        "question": "class Solution:\n    def findMinimumTime(self, tasks: List[List[int]]) -> int:\n        \"\"\"\n        There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi].\n        You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.\n        Return the minimum time during which the computer should be turned on to complete all tasks.\n        Example 1:\n        Input: tasks = [[2,3,1],[4,5,1],[1,5,2]]\n        Output: 2\n        Explanation: \n        - The first task can be run in the inclusive time range [2, 2].\n        - The second task can be run in the inclusive time range [5, 5].\n        - The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].\n        The computer will be on for a total of 2 seconds.\n        Example 2:\n        Input: tasks = [[1,3,2],[2,5,3],[5,6,2]]\n        Output: 4\n        Explanation: \n        - The first task can be run in the inclusive time range [2, 3].\n        - The second task can be run in the inclusive time ranges [2, 3] and [5, 5].\n        - The third task can be run in the two inclusive time range [5, 6].\n        The computer will be on for a total of 4 seconds.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2595,
-        "title": "Number of Even and Odd Bits",
-        "question": "class Solution:\n    def evenOddBit(self, n: int) -> List[int]:\n        \"\"\"\n        You are given a positive integer n.\n        Let even denote the number of even indices in the binary representation of n (0-indexed) with value 1.\n        Let odd denote the number of odd indices in the binary representation of n (0-indexed) with value 1.\n        Return an integer array answer where answer = [even, odd].\n        Example 1:\n        Input: n = 17\n        Output: [2,0]\n        Explanation: The binary representation of 17 is 10001. \n        It contains 1 on the 0th and 4th indices. \n        There are 2 even and 0 odd indices.\n        Example 2:\n        Input: n = 2\n        Output: [0,1]\n        Explanation: The binary representation of 2 is 10.\n        It contains 1 on the 1st index. \n        There are 0 even and 1 odd indices.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2598,
-        "title": "Smallest Missing Non-negative Integer After Operations",
-        "question": "class Solution:\n    def findSmallestInteger(self, nums: List[int], value: int) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums and an integer value.\n        In one operation, you can add or subtract value from any element of nums.\n            For example, if nums = [1,2,3] and value = 2, you can choose to subtract value from nums[0] to make nums = [-1,2,3].\n        The MEX (minimum excluded) of an array is the smallest missing non-negative integer in it.\n            For example, the MEX of [-1,2,3] is 0 while the MEX of [1,0,3] is 2.\n        Return the maximum MEX of nums after applying the mentioned operation any number of times.\n        Example 1:\n        Input: nums = [1,-10,7,13,6,8], value = 5\n        Output: 4\n        Explanation: One can achieve this result by applying the following operations:\n        - Add value to nums[1] twice to make nums = [1,0,7,13,6,8]\n        - Subtract value from nums[2] once to make nums = [1,0,2,13,6,8]\n        - Subtract value from nums[3] twice to make nums = [1,0,2,3,6,8]\n        The MEX of nums is 4. It can be shown that 4 is the maximum MEX we can achieve.\n        Example 2:\n        Input: nums = [1,-10,7,13,6,8], value = 7\n        Output: 2\n        Explanation: One can achieve this result by applying the following operation:\n        - subtract value from nums[2] once to make nums = [1,-10,0,13,6,8]\n        The MEX of nums is 2. It can be shown that 2 is the maximum MEX we can achieve.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2596,
-        "title": "Check Knight Tour Configuration",
-        "question": "class Solution:\n    def checkValidGrid(self, grid: List[List[int]]) -> bool:\n        \"\"\"\n        There is a knight on an n x n chessboard. In a valid configuration, the knight starts at the top-left cell of the board and visits every cell on the board exactly once.\n        You are given an n x n integer matrix grid consisting of distinct integers from the range [0, n * n - 1] where grid[row][col] indicates that the cell (row, col) is the grid[row][col]th cell that the knight visited. The moves are 0-indexed.\n        Return true if grid represents a valid configuration of the knight's movements or false otherwise.\n        Note that a valid knight move consists of moving two squares vertically and one square horizontally, or two squares horizontally and one square vertically. The figure below illustrates all the possible eight moves of a knight from some cell.\n        Example 1:\n        Input: grid = [[0,11,16,5,20],[17,4,19,10,15],[12,1,8,21,6],[3,18,23,14,9],[24,13,2,7,22]]\n        Output: true\n        Explanation: The above diagram represents the grid. It can be shown that it is a valid configuration.\n        Example 2:\n        Input: grid = [[0,3,6],[5,8,1],[2,7,4]]\n        Output: false\n        Explanation: The above diagram represents the grid. The 8th move of the knight is not valid considering its position after the 7th move.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2591,
-        "title": "Distribute Money to Maximum Children",
-        "question": "class Solution:\n    def distMoney(self, money: int, children: int) -> int:\n        \"\"\"\n        You are given an integer money denoting the amount of money (in dollars) that you have and another integer children denoting the number of children that you must distribute the money to.\n        You have to distribute the money according to the following rules:\n            All money must be distributed.\n            Everyone must receive at least 1 dollar.\n            Nobody receives 4 dollars.\n        Return the maximum number of children who may receive exactly 8 dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money, return -1.\n        Example 1:\n        Input: money = 20, children = 3\n        Output: 1\n        Explanation: \n        The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:\n        - 8 dollars to the first child.\n        - 9 dollars to the second child. \n        - 3 dollars to the third child.\n        It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.\n        Example 2:\n        Input: money = 16, children = 2\n        Output: 2\n        Explanation: Each child can be given 8 dollars.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2592,
-        "title": "Maximize Greatness of an Array",
-        "question": "class Solution:\n    def maximizeGreatness(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums. You are allowed to permute nums into a new array perm of your choosing.\n        We define the greatness of nums be the number of indices 0 <= i < nums.length for which perm[i] > nums[i].\n        Return the maximum possible greatness you can achieve after permuting nums.\n        Example 1:\n        Input: nums = [1,3,5,2,1,3,1]\n        Output: 4\n        Explanation: One of the optimal rearrangements is perm = [2,5,1,3,3,1,1].\n        At indices = 0, 1, 3, and 4, perm[i] > nums[i]. Hence, we return 4.\n        Example 2:\n        Input: nums = [1,2,3,4]\n        Output: 3\n        Explanation: We can prove the optimal perm is [2,3,4,1].\n        At indices = 0, 1, and 2, perm[i] > nums[i]. Hence, we return 3.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2594,
-        "title": "Minimum Time to Repair Cars",
-        "question": "class Solution:\n    def repairCars(self, ranks: List[int], cars: int) -> int:\n        \"\"\"\n        You are given an integer array ranks representing the ranks of some mechanics. ranksi is the rank of the ith mechanic. A mechanic with a rank r can repair n cars in r * n2 minutes.\n        You are also given an integer cars representing the total number of cars waiting in the garage to be repaired.\n        Return the minimum time taken to repair all the cars.\n        Note: All the mechanics can repair the cars simultaneously.\n        Example 1:\n        Input: ranks = [4,2,3,1], cars = 10\n        Output: 16\n        Explanation: \n        - The first mechanic will repair two cars. The time required is 4 * 2 * 2 = 16 minutes.\n        - The second mechanic will repair two cars. The time required is 2 * 2 * 2 = 8 minutes.\n        - The third mechanic will repair two cars. The time required is 3 * 2 * 2 = 12 minutes.\n        - The fourth mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.\n        It can be proved that the cars cannot be repaired in less than 16 minutes.\u200b\u200b\u200b\u200b\u200b\n        Example 2:\n        Input: ranks = [5,1,8], cars = 6\n        Output: 16\n        Explanation: \n        - The first mechanic will repair one car. The time required is 5 * 1 * 1 = 5 minutes.\n        - The second mechanic will repair four cars. The time required is 1 * 4 * 4 = 16 minutes.\n        - The third mechanic will repair one car. The time required is 8 * 1 * 1 = 8 minutes.\n        It can be proved that the cars cannot be repaired in less than 16 minutes.\u200b\u200b\u200b\u200b\u200b\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2555,
-        "title": "Maximize Win From Two Segments",
-        "question": "class Solution:\n    def maximizeWin(self, prizePositions: List[int], k: int) -> int:\n        \"\"\"\n        There are some prizes on the X-axis. You are given an integer array prizePositions that is sorted in non-decreasing order, where prizePositions[i] is the position of the ith prize. There could be different prizes at the same position on the line. You are also given an integer k.\n        You are allowed to select two segments with integer endpoints. The length of each segment must be k. You will collect all prizes whose position falls within at least one of the two selected segments (including the endpoints of the segments). The two selected segments may intersect.\n            For example if k = 2, you can choose segments [1, 3] and [2, 4], and you will win any prize i that satisfies 1 <= prizePositions[i] <= 3 or 2 <= prizePositions[i] <= 4.\n        Return the maximum number of prizes you can win if you choose the two segments optimally.\n        Example 1:\n        Input: prizePositions = [1,1,2,2,3,3,5], k = 2\n        Output: 7\n        Explanation: In this example, you can win all 7 prizes by selecting two segments [1, 3] and [3, 5].\n        Example 2:\n        Input: prizePositions = [1,2,3,4], k = 0\n        Output: 2\n        Explanation: For this example, one choice for the segments is [3, 3] and [4, 4], and you will be able to get 2 prizes. \n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2549,
-        "title": "Count Distinct Numbers on Board",
-        "question": "class Solution:\n    def distinctIntegers(self, n: int) -> int:\n        \"\"\"\n        You are given a positive integer n, that is initially placed on a board. Every day, for 109 days, you perform the following procedure:\n            For each number x present on the board, find all numbers 1 <= i <= n such that x % i == 1.\n            Then, place those numbers on the board.\n        Return the number of distinct integers present on the board after 109 days have elapsed.\n        Note:\n            Once a number is placed on the board, it will remain on it until the end.\n            % stands for the modulo operation. For example, 14 % 3 is 2.\n        Example 1:\n        Input: n = 5\n        Output: 4\n        Explanation: Initially, 5 is present on the board. \n        The next day, 2 and 4 will be added since 5 % 2 == 1 and 5 % 4 == 1. \n        After that day, 3 will be added to the board because 4 % 3 == 1. \n        At the end of a billion days, the distinct numbers on the board will be 2, 3, 4, and 5. \n        Example 2:\n        Input: n = 3\n        Output: 2\n        Explanation: \n        Since 3 % 2 == 1, 2 will be added to the board. \n        After a billion days, the only two distinct numbers on the board are 2 and 3. \n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2550,
-        "title": "Count Collisions of Monkeys on a Polygon",
-        "question": "class Solution:\n    def monkeyMove(self, n: int) -> int:\n        \"\"\"\n        There is a regular convex polygon with n vertices. The vertices are labeled from 0 to n - 1 in a clockwise direction, and each vertex has exactly one monkey. The following figure shows a convex polygon of 6 vertices.\n        Each monkey moves simultaneously to a neighboring vertex. A neighboring vertex for a vertex i can be:\n            the vertex (i + 1) % n in the clockwise direction, or\n            the vertex (i - 1 + n) % n in the counter-clockwise direction.\n        A collision happens if at least two monkeys reside on the same vertex after the movement or intersect on an edge.\n        Return the number of ways the monkeys can move so that at least one collision  happens. Since the answer may be very large, return it modulo 109 + 7.\n        Note that each monkey can only move once.\n        Example 1:\n        Input: n = 3\n        Output: 6\n        Explanation: There are 8 total possible movements.\n        Two ways such that they collide at some point are:\n        - Monkey 1 moves in a clockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 2 collide.\n        - Monkey 1 moves in an anticlockwise direction; monkey 2 moves in an anticlockwise direction; monkey 3 moves in a clockwise direction. Monkeys 1 and 3 collide.\n        It can be shown 6 total movements result in a collision.\n        Example 2:\n        Input: n = 4\n        Output: 14\n        Explanation: It can be shown that there are 14 ways for the monkeys to collide.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2551,
-        "title": "Put Marbles in Bags",
-        "question": "class Solution:\n    def putMarbles(self, weights: List[int], k: int) -> int:\n        \"\"\"\n        You have k bags. You are given a 0-indexed integer array weights where weights[i] is the weight of the ith marble. You are also given the integer k.\n        Divide the marbles into the k bags according to the following rules:\n            No bag is empty.\n            If the ith marble and jth marble are in a bag, then all marbles with an index between the ith and jth indices should also be in that same bag.\n            If a bag consists of all the marbles with an index from i to j inclusively, then the cost of the bag is weights[i] + weights[j].\n        The score after distributing the marbles is the sum of the costs of all the k bags.\n        Return the difference between the maximum and minimum scores among marble distributions.\n        Example 1:\n        Input: weights = [1,3,5,1], k = 2\n        Output: 4\n        Explanation: \n        The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6. \n        The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10. \n        Thus, we return their difference 10 - 6 = 4.\n        Example 2:\n        Input: weights = [1, 3], k = 2\n        Output: 0\n        Explanation: The only distribution possible is [1],[3]. \n        Since both the maximal and minimal score are the same, we return 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2552,
-        "title": "Count Increasing Quadruplets",
-        "question": "class Solution:\n    def countQuadruplets(self, nums: List[int]) -> int:\n        \"\"\"\n        Given a 0-indexed integer array nums of size n containing all numbers from 1 to n, return the number of increasing quadruplets.\n        A quadruplet (i, j, k, l) is increasing if:\n            0 <= i < j < k < l < n, and\n            nums[i] < nums[k] < nums[j] < nums[l].\n        Example 1:\n        Input: nums = [1,3,2,4,5]\n        Output: 2\n        Explanation: \n        - When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l].\n        - When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. \n        There are no other quadruplets, so we return 2.\n        Example 2:\n        Input: nums = [1,2,3,4]\n        Output: 0\n        Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2561,
-        "title": "Rearranging Fruits",
-        "question": "class Solution:\n    def minCost(self, basket1: List[int], basket2: List[int]) -> int:\n        \"\"\"\n        You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want:\n            Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.\n            The cost of the swap is min(basket1[i],basket2[j]).\n        Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.\n        Return the minimum cost to make both the baskets equal or -1 if impossible.\n        Example 1:\n        Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2]\n        Output: 1\n        Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal.\n        Example 2:\n        Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1]\n        Output: -1\n        Explanation: It can be shown that it is impossible to make both the baskets equal.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2560,
-        "title": "House Robber IV",
-        "question": "class Solution:\n    def minCapability(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he refuses to steal from adjacent homes.\n        The capability of the robber is the maximum amount of money he steals from one house of all the houses he robbed.\n        You are given an integer array nums representing how much money is stashed in each house. More formally, the ith house from the left has nums[i] dollars.\n        You are also given an integer k, representing the minimum number of houses the robber will steal from. It is always possible to steal at least k houses.\n        Return the minimum capability of the robber out of all the possible ways to steal at least k houses.\n        Example 1:\n        Input: nums = [2,3,5,9], k = 2\n        Output: 5\n        Explanation: \n        There are three ways to rob at least 2 houses:\n        - Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5.\n        - Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9.\n        - Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9.\n        Therefore, we return min(5, 9, 9) = 5.\n        Example 2:\n        Input: nums = [2,7,9,3,1], k = 2\n        Output: 2\n        Explanation: There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2559,
-        "title": "Count Vowel Strings in Ranges",
-        "question": "class Solution:\n    def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed array of strings words and a 2D array of integers queries.\n        Each query queries[i] = [li, ri] asks us to find the number of strings present in the range li to ri (both inclusive) of words that start and end with a vowel.\n        Return an array ans of size queries.length, where ans[i] is the answer to the ith query.\n        Note that the vowel letters are 'a', 'e', 'i', 'o', and 'u'.\n        Example 1:\n        Input: words = [\"aba\",\"bcb\",\"ece\",\"aa\",\"e\"], queries = [[0,2],[1,4],[1,1]]\n        Output: [2,3,0]\n        Explanation: The strings starting and ending with a vowel are \"aba\", \"ece\", \"aa\" and \"e\".\n        The answer to the query [0,2] is 2 (strings \"aba\" and \"ece\").\n        to query [1,4] is 3 (strings \"ece\", \"aa\", \"e\").\n        to query [1,1] is 0.\n        We return [2,3,0].\n        Example 2:\n        Input: words = [\"a\",\"e\",\"i\"], queries = [[0,2],[0,1],[2,2]]\n        Output: [3,2,1]\n        Explanation: Every string satisfies the conditions, so we return [3,2,1].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2558,
-        "title": "Take Gifts From the Richest Pile",
-        "question": "class Solution:\n    def pickGifts(self, gifts: List[int], k: int) -> int:\n        \"\"\"\n        You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following:\n            Choose the pile with the maximum number of gifts.\n            If there is more than one pile with the maximum number of gifts, choose any.\n            Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts.\n        Return the number of gifts remaining after k seconds.\n        Example 1:\n        Input: gifts = [25,64,9,4,100], k = 4\n        Output: 29\n        Explanation: \n        The gifts are taken in the following way:\n        - In the first second, the last pile is chosen and 10 gifts are left behind.\n        - Then the second pile is chosen and 8 gifts are left behind.\n        - After that the first pile is chosen and 5 gifts are left behind.\n        - Finally, the last pile is chosen again and 3 gifts are left behind.\n        The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is 29.\n        Example 2:\n        Input: gifts = [1,1,1,1], k = 4\n        Output: 4\n        Explanation: \n        In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile. \n        That is, you can't take any pile with you. \n        So, the total gifts remaining are 4.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2593,
-        "title": "Find Score of an Array After Marking All Elements",
-        "question": "class Solution:\n    def findScore(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given an array nums consisting of positive integers.\n        Starting with score = 0, apply the following algorithm:\n            Choose the smallest integer of the array that is not marked. If there is a tie, choose the one with the smallest index.\n            Add the value of the chosen integer to score.\n            Mark the chosen element and its two adjacent elements if they exist.\n            Repeat until all the array elements are marked.\n        Return the score you get after applying the above algorithm.\n        Example 1:\n        Input: nums = [2,1,3,4,5,2]\n        Output: 7\n        Explanation: We mark the elements as follows:\n        - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,1,3,4,5,2].\n        - 2 is the smallest unmarked element, so we mark it and its left adjacent element: [2,1,3,4,5,2].\n        - 4 is the only remaining unmarked element, so we mark it: [2,1,3,4,5,2].\n        Our score is 1 + 2 + 4 = 7.\n        Example 2:\n        Input: nums = [2,3,5,1,3,2]\n        Output: 5\n        Explanation: We mark the elements as follows:\n        - 1 is the smallest unmarked element, so we mark it and its two adjacent elements: [2,3,5,1,3,2].\n        - 2 is the smallest unmarked element, since there are two of them, we choose the left-most one, so we mark the one at index 0 and its right adjacent element: [2,3,5,1,3,2].\n        - 2 is the only remaining unmarked element, so we mark it: [2,3,5,1,3,2].\n        Our score is 1 + 2 + 2 = 5.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2597,
-        "title": "The Number of Beautiful Subsets",
-        "question": "class Solution:\n    def beautifulSubsets(self, nums: List[int], k: int) -> int:\n        \"\"\"\n        You are given an array nums of positive integers and a positive integer k.\n        A subset of nums is beautiful if it does not contain two integers with an absolute difference equal to k.\n        Return the number of non-empty beautiful subsets of the array nums.\n        A subset of nums is an array that can be obtained by deleting some (possibly none) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.\n        Example 1:\n        Input: nums = [2,4,6], k = 2\n        Output: 4\n        Explanation: The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].\n        It can be proved that there are only 4 beautiful subsets in the array [2,4,6].\n        Example 2:\n        Input: nums = [1], k = 1\n        Output: 1\n        Explanation: The beautiful subset of the array nums is [1].\n        It can be proved that there is only 1 beautiful subset in the array [1].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2562,
-        "title": "Find the Array Concatenation Value",
-        "question": "class Solution:\n    def findTheArrayConcVal(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums.\n        The concatenation of two numbers is the number formed by concatenating their numerals.\n            For example, the concatenation of 15, 49 is 1549.\n        The concatenation value of nums is initially equal to 0. Perform this operation until nums becomes empty:\n            If there exists more than one number in nums, pick the first element and last element in nums respectively and add the value of their concatenation to the concatenation value of nums, then delete the first and last element from nums.\n            If one element exists, add its value to the concatenation value of nums, then delete it.\n        Return the concatenation value of the nums.\n        Example 1:\n        Input: nums = [7,52,2,4]\n        Output: 596\n        Explanation: Before performing any operation, nums is [7,52,2,4] and concatenation value is 0.\n         - In the first operation:\n        We pick the first element, 7, and the last element, 4.\n        Their concatenation is 74, and we add it to the concatenation value, so it becomes equal to 74.\n        Then we delete them from nums, so nums becomes equal to [52,2].\n         - In the second operation:\n        We pick the first element, 52, and the last element, 2.\n        Their concatenation is 522, and we add it to the concatenation value, so it becomes equal to 596.\n        Then we delete them from the nums, so nums becomes empty.\n        Since the concatenation value is 596 so the answer is 596.\n        Example 2:\n        Input: nums = [5,14,13,8,12]\n        Output: 673\n        Explanation: Before performing any operation, nums is [5,14,13,8,12] and concatenation value is 0.\n         - In the first operation:\n        We pick the first element, 5, and the last element, 12.\n        Their concatenation is 512, and we add it to the concatenation value, so it becomes equal to 512.\n        Then we delete them from the nums, so nums becomes equal to [14,13,8].\n         - In the second operation:\n        We pick the first element, 14, and the last element, 8.\n        Their concatenation is 148, and we add it to the concatenation value, so it becomes equal to 660.\n        Then we delete them from the nums, so nums becomes equal to [13].\n         - In the third operation:\n        nums has only one element, so we pick 13 and add it to the concatenation value, so it becomes equal to 673.\n        Then we delete it from nums, so nums become empty.\n        Since the concatenation value is 673 so the answer is 673.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2563,
-        "title": "Count the Number of Fair Pairs",
-        "question": "class Solution:\n    def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int:\n        \"\"\"\n        Given a 0-indexed integer array nums of size n and two integers lower and upper, return the number of fair pairs.\n        A pair (i, j) is fair if:\n            0 <= i < j < n, and\n            lower <= nums[i] + nums[j] <= upper\n        Example 1:\n        Input: nums = [0,1,7,4,4,5], lower = 3, upper = 6\n        Output: 6\n        Explanation: There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).\n        Example 2:\n        Input: nums = [1,7,9,2,5], lower = 11, upper = 11\n        Output: 1\n        Explanation: There is a single fair pair: (2,3).\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2564,
-        "title": "Substring XOR Queries",
-        "question": "class Solution:\n    def substringXorQueries(self, s: str, queries: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given a binary string s, and a 2D integer array queries where queries[i] = [firsti, secondi].\n        For the ith query, find the shortest substring of s whose decimal value, val, yields secondi when bitwise XORed with firsti. In other words, val ^ firsti == secondi.\n        The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum lefti.\n        Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query.\n        A substring is a contiguous non-empty sequence of characters within a string.\n        Example 1:\n        Input: s = \"101101\", queries = [[0,5],[1,2]]\n        Output: [[0,2],[2,3]]\n        Explanation: For the first query the substring in range [0,2] is \"101\" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is \"11\", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. \n        Example 2:\n        Input: s = \"0101\", queries = [[12,8]]\n        Output: [[-1,-1]]\n        Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned.\n        Example 3:\n        Input: s = \"1\", queries = [[4,5]]\n        Output: [[0,0]]\n        Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2565,
-        "title": "Subsequence With the Minimum Score",
-        "question": "class Solution:\n    def minimumScore(self, s: str, t: str) -> int:\n        \"\"\"\n        You are given two strings s and t.\n        You are allowed to remove any number of characters from the string t.\n        The score of the string is 0 if no characters are removed from the string t, otherwise:\n            Let left be the minimum index among all removed characters.\n            Let right be the maximum index among all removed characters.\n        Then the score of the string is right - left + 1.\n        Return the minimum possible score to make t a subsequence of s.\n        A 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:\n        Input: s = \"abacaba\", t = \"bzaa\"\n        Output: 1\n        Explanation: In this example, we remove the character \"z\" at index 1 (0-indexed).\n        The string t becomes \"baa\" which is a subsequence of the string \"abacaba\" and the score is 1 - 1 + 1 = 1.\n        It can be proven that 1 is the minimum score that we can achieve.\n        Example 2:\n        Input: s = \"cde\", t = \"xyz\"\n        Output: 3\n        Explanation: In this example, we remove characters \"x\", \"y\" and \"z\" at indices 0, 1, and 2 (0-indexed).\n        The string t becomes \"\" which is a subsequence of the string \"cde\" and the score is 2 - 0 + 1 = 3.\n        It can be proven that 3 is the minimum score that we can achieve.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2569,
-        "title": "Handling Sum Queries After Update",
-        "question": "class Solution:\n    def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]:\n        \"\"\"\n        You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries:\n            For a query of type 1, queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r are 0-indexed.\n            For a query of type 2, queries[i] = [2, p, 0]. For every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p.\n            For a query of type 3, queries[i] = [3, 0, 0]. Find the sum of the elements in nums2.\n        Return an array containing all the answers to the third type queries.\n        Example 1:\n        Input: nums1 = [1,0,1], nums2 = [0,0,0], queries = [[1,1,1],[2,1,0],[3,0,0]]\n        Output: [3]\n        Explanation: After the first query nums1 becomes [1,1,1]. After the second query, nums2 becomes [1,1,1], so the answer to the third query is 3. Thus, [3] is returned.\n        Example 2:\n        Input: nums1 = [1], nums2 = [5], queries = [[2,0,0],[3,0,0]]\n        Output: [5]\n        Explanation: After the first query, nums2 remains [5], so the answer to the second query is 5. Thus, [5] is returned.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2566,
-        "title": "Maximum Difference by Remapping a Digit",
-        "question": "class Solution:\n    def minMaxDifference(self, num: int) -> int:\n        \"\"\"\n        You are given an integer num. You know that Danny Mittal will sneakily remap one of the 10 possible digits (0 to 9) to another digit.\n        Return the difference between the maximum and minimum values Danny can make by remapping exactly one digit in num.\n        Notes:\n            When Danny remaps a digit d1 to another digit d2, Danny replaces all occurrences of d1 in num with d2.\n            Danny can remap a digit to itself, in which case num does not change.\n            Danny can remap different digits for obtaining minimum and maximum values respectively.\n            The resulting number after remapping can contain leading zeroes.\n            We mentioned \"Danny Mittal\" to congratulate him on being in the top 10 in Weekly Contest 326.\n        Example 1:\n        Input: num = 11891\n        Output: 99009\n        Explanation: \n        To achieve the maximum value, Danny can remap the digit 1 to the digit 9 to yield 99899.\n        To achieve the minimum value, Danny can remap the digit 1 to the digit 0, yielding 890.\n        The difference between these two numbers is 99009.\n        Example 2:\n        Input: num = 90\n        Output: 99\n        Explanation:\n        The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0).\n        Thus, we return 99.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2568,
-        "title": "Minimum Impossible OR",
-        "question": "class Solution:\n    def minImpossibleOR(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums.\n        We say that an integer x is expressible from nums if there exist some integers 0 <= index1 < index2 < ... < indexk < nums.length for which nums[index1] | nums[index2] | ... | nums[indexk] = x. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of nums.\n        Return the minimum positive non-zero integer that is not expressible from nums.\n        Example 1:\n        Input: nums = [2,1]\n        Output: 4\n        Explanation: 1 and 2 are already present in the array. We know that 3 is expressible, since nums[0] | nums[1] = 2 | 1 = 3. Since 4 is not expressible, we return 4.\n        Example 2:\n        Input: nums = [5,3,2]\n        Output: 1\n        Explanation: We can show that 1 is the smallest number that is not expressible.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2567,
-        "title": "Minimum Score by Changing Two Elements",
-        "question": "class Solution:\n    def minimizeSum(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums.\n            The low score of nums is the minimum value of |nums[i] - nums[j]| over all 0 <= i < j < nums.length.\n            The high score of nums is the maximum value of |nums[i] - nums[j]| over all 0 <= i < j < nums.length.\n            The score of nums is the sum of the high and low scores of nums.\n        To minimize the score of nums, we can change the value of at most two elements of nums.\n        Return the minimum possible score after changing the value of at most two elements of nums.\n        Note that |x| denotes the absolute value of x.\n        Example 1:\n        Input: nums = [1,4,3]\n        Output: 0\n        Explanation: Change value of nums[1] and nums[2] to 1 so that nums becomes [1,1,1]. Now, the value of |nums[i] - nums[j]| is always equal to 0, so we return 0 + 0 = 0.\n        Example 2:\n        Input: nums = [1,4,7,8,5]\n        Output: 3\n        Explanation: Change nums[0] and nums[1] to be 6. Now nums becomes [6,6,7,8,5].\n        Our low score is achieved when i = 0 and j = 1, in which case |nums[i] - nums[j]| = |6 - 6| = 0.\n        Our high score is achieved when i = 3 and j = 4, in which case |nums[i] - nums[j]| = |8 - 5| = 3.\n        The sum of our high and low score is 3, which we can prove to be minimal.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2570,
-        "title": "Merge Two 2D Arrays by Summing Values",
-        "question": "class Solution:\n    def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n        \"\"\"\n        You are given two 2D integer arrays nums1 and nums2.\n            nums1[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.\n            nums2[i] = [idi, vali] indicate that the number with the id idi has a value equal to vali.\n        Each array contains unique ids and is sorted in ascending order by id.\n        Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:\n            Only ids that appear in at least one of the two arrays should be included in the resulting array.\n            Each id should be included only once and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be 0.\n        Return the resulting array. The returned array must be sorted in ascending order by id.\n        Example 1:\n        Input: nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]\n        Output: [[1,6],[2,3],[3,2],[4,6]]\n        Explanation: The resulting array contains the following:\n        - id = 1, the value of this id is 2 + 4 = 6.\n        - id = 2, the value of this id is 3.\n        - id = 3, the value of this id is 2.\n        - id = 4, the value of this id is 5 + 1 = 6.\n        Example 2:\n        Input: nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]\n        Output: [[1,3],[2,4],[3,6],[4,3],[5,5]]\n        Explanation: There are no common ids, so we just include each id with its value in the resulting list.\n        \"\"\"\n",
-        "difficulty": 0
-    },
-    {
-        "number": 2573,
-        "title": "Find the String with LCP",
-        "question": "class Solution:\n    def findTheString(self, lcp: List[List[int]]) -> str:\n        \"\"\"\n        We define the lcp matrix of any 0-indexed string word of n lowercase English letters as an n x n grid such that:\n            lcp[i][j] is equal to the length of the longest common prefix between the substrings word[i,n-1] and word[j,n-1].\n        Given an n x n matrix lcp, return the alphabetically smallest string word that corresponds to lcp. If there is no such string, return an empty string.\n        A 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, \"aabd\" is lexicographically smaller than \"aaca\" because the first position they differ is at the third letter, and 'b' comes before 'c'.\n        Example 1:\n        Input: lcp = [[4,0,2,0],[0,3,0,1],[2,0,2,0],[0,1,0,1]]\n        Output: \"abab\"\n        Explanation: lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is \"abab\".\n        Example 2:\n        Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,1]]\n        Output: \"aaaa\"\n        Explanation: lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is \"aaaa\". \n        Example 3:\n        Input: lcp = [[4,3,2,1],[3,3,2,1],[2,2,2,1],[1,1,1,3]]\n        Output: \"\"\n        Explanation: lcp[3][3] cannot be equal to 3 since word[3,...,3] consists of only a single letter; Thus, no answer exists.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2572,
-        "title": "Count the Number of Square-Free Subsets",
-        "question": "class Solution:\n    def squareFreeSubsets(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a positive integer 0-indexed array nums.\n        A subset of the array nums is square-free if the product of its elements is a square-free integer.\n        A square-free integer is an integer that is divisible by no square number other than 1.\n        Return the number of square-free non-empty subsets of the array nums. Since the answer may be too large, return it modulo 109 + 7.\n        A non-empty subset of nums is an array that can be obtained by deleting some (possibly none but not all) elements from nums. Two subsets are different if and only if the chosen indices to delete are different.\n        Example 1:\n        Input: nums = [3,4,4,5]\n        Output: 3\n        Explanation: There are 3 square-free subsets in this example:\n        - The subset consisting of the 0th element [3]. The product of its elements is 3, which is a square-free integer.\n        - The subset consisting of the 3rd element [5]. The product of its elements is 5, which is a square-free integer.\n        - The subset consisting of 0th and 3rd elements [3,5]. The product of its elements is 15, which is a square-free integer.\n        It can be proven that there are no more than 3 square-free subsets in the given array.\n        Example 2:\n        Input: nums = [1]\n        Output: 1\n        Explanation: There is 1 square-free subset in this example:\n        - The subset consisting of the 0th element [1]. The product of its elements is 1, which is a square-free integer.\n        It can be proven that there is no more than 1 square-free subset in the given array.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2571,
-        "title": "Minimum Operations to Reduce an Integer to 0",
-        "question": "class Solution:\n    def minOperations(self, n: int) -> int:\n        \"\"\"\n        You are given a positive integer n, you can do the following operation any number of times:\n            Add or subtract a power of 2 from n.\n        Return the minimum number of operations to make n equal to 0.\n        A number x is power of 2 if x == 2i where i >= 0.\n        Example 1:\n        Input: n = 39\n        Output: 3\n        Explanation: We can do the following operations:\n        - Add 20 = 1 to n, so now n = 40.\n        - Subtract 23 = 8 from n, so now n = 32.\n        - Subtract 25 = 32 from n, so now n = 0.\n        It can be shown that 3 is the minimum number of operations we need to make n equal to 0.\n        Example 2:\n        Input: n = 54\n        Output: 3\n        Explanation: We can do the following operations:\n        - Add 21 = 2 to n, so now n = 56.\n        - Add 23 = 8 to n, so now n = 64.\n        - Subtract 26 = 64 from n, so now n = 0.\n        So the minimum number of operations is 3.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2577,
-        "title": "Minimum Time to Visit a Cell In a Grid",
-        "question": "class Solution:\n    def minimumTime(self, grid: List[List[int]]) -> int:\n        \"\"\"\n        You are given a m x n matrix grid consisting of non-negative integers where grid[row][col] represents the minimum time required to be able to visit the cell (row, col), which means you can visit the cell (row, col) only when the time you visit it is greater than or equal to grid[row][col].\n        You are standing in the top-left cell of the matrix in the 0th second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.\n        Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return -1.\n        Example 1:\n        Input: grid = [[0,1,3,2],[5,1,2,5],[4,3,8,6]]\n        Output: 7\n        Explanation: One of the paths that we can take is the following:\n        - at t = 0, we are on the cell (0,0).\n        - at t = 1, we move to the cell (0,1). It is possible because grid[0][1] <= 1.\n        - at t = 2, we move to the cell (1,1). It is possible because grid[1][1] <= 2.\n        - at t = 3, we move to the cell (1,2). It is possible because grid[1][2] <= 3.\n        - at t = 4, we move to the cell (1,1). It is possible because grid[1][1] <= 4.\n        - at t = 5, we move to the cell (1,2). It is possible because grid[1][2] <= 5.\n        - at t = 6, we move to the cell (1,3). It is possible because grid[1][3] <= 6.\n        - at t = 7, we move to the cell (2,3). It is possible because grid[2][3] <= 7.\n        The final time is 7. It can be shown that it is the minimum time possible.\n        Example 2:\n        Input: grid = [[0,2,4],[3,2,1],[1,0,4]]\n        Output: -1\n        Explanation: There is no path from the top left to the bottom-right cell.\n        \"\"\"\n",
-        "difficulty": 2
-    },
-    {
-        "number": 2576,
-        "title": "Find the Maximum Number of Marked Indices",
-        "question": "class Solution:\n    def maxNumOfMarkedIndices(self, nums: List[int]) -> int:\n        \"\"\"\n        You are given a 0-indexed integer array nums.\n        Initially, all of the indices are unmarked. You are allowed to make this operation any number of times:\n            Pick two different unmarked indices i and j such that 2 * nums[i] <= nums[j], then mark i and j.\n        Return the maximum possible number of marked indices in nums using the above operation any number of times.\n        Example 1:\n        Input: nums = [3,5,2,4]\n        Output: 2\n        Explanation: In the first operation: pick i = 2 and j = 1, the operation is allowed because 2 * nums[2] <= nums[1]. Then mark index 2 and 1.\n        It can be shown that there's no other valid operation so the answer is 2.\n        Example 2:\n        Input: nums = [9,2,5,4]\n        Output: 4\n        Explanation: In the first operation: pick i = 3 and j = 0, the operation is allowed because 2 * nums[3] <= nums[0]. Then mark index 3 and 0.\n        In the second operation: pick i = 1 and j = 2, the operation is allowed because 2 * nums[1] <= nums[2]. Then mark index 1 and 2.\n        Since there is no other operation, the answer is 4.\n        Example 3:\n        Input: nums = [7,6,8]\n        Output: 0\n        Explanation: There is no valid operation to do, so the answer is 0.\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2575,
-        "title": "Find the Divisibility Array of a String",
-        "question": "class Solution:\n    def divisibilityArray(self, word: str, m: int) -> List[int]:\n        \"\"\"\n        You are given a 0-indexed string word of length n consisting of digits, and a positive integer m.\n        The divisibility array div of word is an integer array of length n such that:\n            div[i] = 1 if the numeric value of word[0,...,i] is divisible by m, or\n            div[i] = 0 otherwise.\n        Return the divisibility array of word.\n        Example 1:\n        Input: word = \"998244353\", m = 3\n        Output: [1,1,0,0,0,1,1,0,0]\n        Explanation: There are only 4 prefixes that are divisible by 3: \"9\", \"99\", \"998244\", and \"9982443\".\n        Example 2:\n        Input: word = \"1010\", m = 10\n        Output: [0,1,0,1]\n        Explanation: There are only 2 prefixes that are divisible by 10: \"10\", and \"1010\".\n        \"\"\"\n",
-        "difficulty": 1
-    },
-    {
-        "number": 2574,
-        "title": "Left and Right Sum Differences",
-        "question": "class Solution:\n    def leftRigthDifference(self, nums: List[int]) -> List[int]:\n        \"\"\"\n        Given a 0-indexed integer array nums, find a 0-indexed integer array answer where:\n            answer.length == nums.length.\n            answer[i] = |leftSum[i] - rightSum[i]|.\n        Where:\n            leftSum[i] is the sum of elements to the left of the index i in the array nums. If there is no such element, leftSum[i] = 0.\n            rightSum[i] is the sum of elements to the right of the index i in the array nums. If there is no such element, rightSum[i] = 0.\n        Return the array answer.\n        Example 1:\n        Input: nums = [10,4,8,3]\n        Output: [15,1,11,22]\n        Explanation: The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].\n        The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].\n        Example 2:\n        Input: nums = [1]\n        Output: [0]\n        Explanation: The array leftSum is [0] and the array rightSum is [0].\n        The array answer is [|0 - 0|] = [0].\n        \"\"\"\n",
-        "difficulty": 0
-    }
-]
\ No newline at end of file